<template>
  <div class="admin--advisor-form">
    <form @submit.prevent="handleSubmit" class="admin--form">
      <!-- 서비스센터 -->
      <div class="admin--form-group">
        <label class="admin--form-label">서비스센터 <span class="admin--required">*</span></label>
        <select v-model="formData.service_center" class="admin--form-select" required>
          <option value="">서비스센터를 선택하세요</option>
          <option v-for="center in serviceCenters" :key="center.code" :value="center.code">
            {{ center.code }} : {{ center.name }}
          </option>
        </select>
      </div>

      <!-- 이름 -->
      <div class="admin--form-group">
        <label class="admin--form-label">이름 <span class="admin--required">*</span></label>
        <input
          v-model="formData.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.main_phone"
          type="tel"
          class="admin--form-input"
          placeholder="02-1234-5678"
          required
        >
      </div>

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

      <!-- 사진 -->
      <div class="admin--form-group">
        <label class="admin--form-label">사진</label>
        <input
          type="file"
          accept="image/*"
          class="admin--form-file"
          @change="handlePhotoUpload"
        >
        <div v-if="photoPreview" class="admin--image-preview">
          <img :src="photoPreview" alt="미리보기">
          <button type="button" class="admin--btn-remove-image" @click="removePhoto">
            삭제
          </button>
        </div>
      </div>

      <!-- 버튼 영역 -->
      <div class="admin--form-actions">
        <button
          type="submit"
          class="admin--btn admin--btn-primary"
          :disabled="isSaving"
        >
          {{ isSaving ? '저장 중...' : '확인' }}
        </button>
        <button
          type="button"
          class="admin--btn admin--btn-secondary"
          @click="goToList"
        >
          목록
        </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'
import { useRouter } from 'vue-router'

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

const router = useRouter()
const { get, post, upload } = useApi()

const isSaving = ref(false)
const successMessage = ref('')
const errorMessage = ref('')
const photoPreview = ref(null)
const photoFile = ref(null)

const formData = ref({
  service_center: '',
  name: '',
  main_phone: '',
  direct_phone: '',
  photo_url: ''
})

const serviceCenters = ref([
  { code: 'CA', name: '성수서비스센터' },
  { code: 'CB', name: '수원서비스센터' },
  { code: 'CC', name: '대전서비스센터' },
  { code: 'CD', name: '광주서비스센터' }
])

const handlePhotoUpload = (event) => {
  const file = event.target.files[0]
  if (!file) return

  if (!file.type.startsWith('image/')) {
    alert('이미지 파일만 업로드 가능합니다.')
    return
  }

  photoFile.value = file

  const reader = new FileReader()
  reader.onload = (e) => {
    photoPreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

const removePhoto = () => {
  photoPreview.value = null
  photoFile.value = null
  formData.value.photo_url = ''
}

const handleSubmit = async () => {
  successMessage.value = ''
  errorMessage.value = ''

  if (!formData.value.service_center) {
    errorMessage.value = '서비스센터를 선택하세요.'
    return
  }

  if (!formData.value.name) {
    errorMessage.value = '이름을 입력하세요.'
    return
  }

  isSaving.value = true

  try {
    let photoUrl = formData.value.photo_url

    if (photoFile.value) {
      const formDataImage = new FormData()
      formDataImage.append('file', photoFile.value)

      const { data: uploadData, error: uploadError } = await upload('/upload/advisor-image', formDataImage)

      if (uploadError) {
        errorMessage.value = '사진 업로드에 실패했습니다.'
        isSaving.value = false
        return
      }

      if (!uploadData?.success || !uploadData?.data?.url) {
        errorMessage.value = '사진 업로드 응답이 올바르지 않습니다.'
        isSaving.value = false
        return
      }

      photoUrl = uploadData.data.url
    }

    const submitData = {
      ...formData.value,
      photo_url: photoUrl
    }

    const { data, error } = await post('/staff/advisor', submitData)

    if (error) {
      errorMessage.value = error.message || '등록에 실패했습니다.'
    } else {
      successMessage.value = '어드바이저가 등록되었습니다.'
      setTimeout(() => {
        router.push('/site-manager/staff/advisor')
      }, 1000)
    }
  } catch (error) {
    errorMessage.value = '서버 오류가 발생했습니다.'
    console.error('Save error:', error)
  } finally {
    isSaving.value = false
  }
}

const goToList = () => {
  router.push('/site-manager/staff/advisor')
}
</script>
