<template>
  <div class="admin--site-info">
    <div v-if="isLoading" class="admin--loading">
      데이터를 불러오는 중...
    </div>

    <form v-else @submit.prevent="handleSubmit" class="admin--form">
      <!-- 사이트명 -->
      <div class="admin--form-group">
        <label class="admin--form-label">사이트명 <span class="admin--required">*</span></label>
        <input
          v-model="formData.site_name"
          type="text"
          class="admin--form-input"
          placeholder="사이트명을 입력하세요"
          required
        >
      </div>

      <!-- 사이트 URL -->
      <div class="admin--form-group">
        <label class="admin--form-label">사이트 URL <span class="admin--required">*</span></label>
        <input
          v-model="formData.site_url"
          type="url"
          class="admin--form-input"
          placeholder="https://example.com"
          required
        >
      </div>

      <!-- 대표명 -->
      <div class="admin--form-group">
        <label class="admin--form-label">대표명 <span class="admin--required">*</span></label>
        <input
          v-model="formData.ceo_name"
          type="text"
          class="admin--form-input"
          placeholder="대표명을 입력하세요"
          required
        >
      </div>

      <!-- 대표 이메일 -->
      <div class="admin--form-group">
        <label class="admin--form-label">대표 이메일 <span class="admin--required">*</span></label>
        <input
          v-model="formData.ceo_email"
          type="email"
          class="admin--form-input"
          placeholder="email@example.com"
          required
        >
      </div>

      <!-- 전화번호 -->
      <div class="admin--form-group">
        <label class="admin--form-label">전화번호 <span class="admin--required">*</span></label>
        <input
          v-model="formData.phone"
          type="tel"
          class="admin--form-input"
          placeholder="02-1234-5678"
          required
        >
      </div>

      <!-- FAX번호 -->
      <div class="admin--form-group">
        <label class="admin--form-label">FAX번호</label>
        <input
          v-model="formData.fax"
          type="tel"
          class="admin--form-input"
          placeholder="02-1234-5679"
        >
      </div>

      <!-- 회사주소 -->
      <div class="admin--form-group">
        <label class="admin--form-label">회사주소 <span class="admin--required">*</span></label>
        <input
          v-model="formData.address"
          type="text"
          class="admin--form-input"
          placeholder="회사 주소를 입력하세요"
          required
        >
      </div>

      <!-- SMS발신번호 (다중) -->
      <div class="admin--form-group">
        <label class="admin--form-label">SMS발신번호</label>
        <div class="admin--multi-input-wrapper">
          <div
            v-for="(item, index) in formData.sms_sender_numbers"
            :key="index"
            class="admin--multi-input-item"
          >
            <div class="admin--sender-row">
              <input
                v-model="formData.sms_sender_numbers[index].name"
                type="text"
                class="admin--form-input"
                placeholder="지점명"
                style="flex: 1; margin-right: 10px;"
              >
              <input
                v-model="formData.sms_sender_numbers[index].number"
                type="tel"
                class="admin--form-input"
                placeholder="010-1234-5678"
                style="flex: 1;"
              >
            </div>
            <button
              v-if="formData.sms_sender_numbers.length > 1"
              type="button"
              class="admin--btn-remove"
              @click="removeSenderNumber(index)"
            >
              삭제
            </button>
          </div>
          <button
            type="button"
            class="admin--btn-add"
            @click="addSenderNumber"
          >
            + 발신번호 추가
          </button>
        </div>
      </div>

      <!-- SMS수신번호 -->
      <div class="admin--form-group">
        <label class="admin--form-label">SMS수신번호</label>
        <input
          v-model="formData.sms_receiver_number"
          type="tel"
          class="admin--form-input"
          placeholder="010-9876-5432"
        >
      </div>

      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button
          type="submit"
          class="admin--btn admin--btn-primary"
          :disabled="isSaving"
        >
          {{ isSaving ? '저장 중...' : '저장' }}
        </button>
      </div>

      <!-- 성공/에러 메시지 -->
      <div v-if="successMessage" class="admin--alert admin--alert-success">
        {{ successMessage }}
      </div>
      <div v-if="errorMessage" class="admin--alert admin--alert-error">
        {{ errorMessage }}
      </div>
    </form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

definePageMeta({
  layout: 'admin',
  middleware: ['auth']
})

const { get, post } = useApi()

const isLoading = ref(true)
const isSaving = ref(false)
const successMessage = ref('')
const errorMessage = ref('')
const siteInfoId = ref(null)

const formData = ref({
  site_name: '',
  site_url: '',
  ceo_name: '',
  ceo_email: '',
  phone: '',
  fax: '',
  address: '',
  sms_sender_numbers: [{ name: '', number: '' }],
  sms_receiver_number: ''
})

// 데이터 로드
const loadSiteInfo = async () => {
  isLoading.value = true

  const { data } = await get('/basic/site-info')

  if (data && data.id) {
    siteInfoId.value = data.id

    // SMS 발신번호 데이터 변환 (기존 문자열 배열 → 객체 배열)
    let senderNumbers = [{ name: '', number: '' }]
    if (data.sms_sender_numbers && data.sms_sender_numbers.length > 0) {
      senderNumbers = data.sms_sender_numbers.map(item => {
        // 이미 객체 형태인 경우
        if (typeof item === 'object' && item.name !== undefined) {
          return item
        }
        // 문자열인 경우 (기존 데이터)
        return { name: '', number: item }
      })
    }

    formData.value = {
      site_name: data.site_name || '',
      site_url: data.site_url || '',
      ceo_name: data.ceo_name || '',
      ceo_email: data.ceo_email || '',
      phone: data.phone || '',
      fax: data.fax || '',
      address: data.address || '',
      sms_sender_numbers: senderNumbers,
      sms_receiver_number: data.sms_receiver_number || ''
    }
  }

  isLoading.value = false
}

// 발신번호 추가
const addSenderNumber = () => {
  formData.value.sms_sender_numbers.push({ name: '', number: '' })
}

// 발신번호 삭제
const removeSenderNumber = (index) => {
  formData.value.sms_sender_numbers.splice(index, 1)
}

// 폼 제출
const handleSubmit = async () => {
  successMessage.value = ''
  errorMessage.value = ''
  isSaving.value = true

  try {
    // 빈 발신번호 제거 (지점명 또는 번호가 비어있지 않은 것만)
    const cleanedSenderNumbers = formData.value.sms_sender_numbers.filter(
      sender => (sender.name && sender.name.trim() !== '') || (sender.number && sender.number.trim() !== '')
    )

    const submitData = {
      ...formData.value,
      sms_sender_numbers: cleanedSenderNumbers
    }

    // POST로 통일 (등록/수정 모두)
    const result = await post('/basic/site-info', submitData)

    if (result.error) {
      errorMessage.value = result.error.message || '저장에 실패했습니다.'
    } else {
      successMessage.value = '사이트 정보가 저장되었습니다.'

      // 저장된 데이터로 업데이트
      if (result.data) {
        siteInfoId.value = result.data.id

        // SMS 발신번호 데이터 변환 (기존 문자열 배열 → 객체 배열)
        let senderNumbers = [{ name: '', number: '' }]
        if (result.data.sms_sender_numbers && result.data.sms_sender_numbers.length > 0) {
          senderNumbers = result.data.sms_sender_numbers.map(item => {
            // 이미 객체 형태인 경우
            if (typeof item === 'object' && item.name !== undefined) {
              return item
            }
            // 문자열인 경우 (기존 데이터)
            return { name: '', number: item }
          })
        }

        formData.value = {
          site_name: result.data.site_name || '',
          site_url: result.data.site_url || '',
          ceo_name: result.data.ceo_name || '',
          ceo_email: result.data.ceo_email || '',
          phone: result.data.phone || '',
          fax: result.data.fax || '',
          address: result.data.address || '',
          sms_sender_numbers: senderNumbers,
          sms_receiver_number: result.data.sms_receiver_number || ''
        }
      }

      // 3초 후 메시지 자동 제거
      setTimeout(() => {
        successMessage.value = ''
      }, 3000)
    }
  } catch (error) {
    errorMessage.value = '서버 오류가 발생했습니다.'
    console.error('Save error:', error)
  } finally {
    isSaving.value = false
  }
}

onMounted(() => {
  loadSiteInfo()
})
</script>
