<template>
  <div class="admin--branch-form">
    <form @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.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.phone"
          type="tel"
          class="admin--form-input"
          placeholder="02-1234-5678"
          required
        >
      </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>

      <!-- 상세주소 -->
      <div class="admin--form-group">
        <label class="admin--form-label">상세주소</label>
        <input
          v-model="formData.detail_address"
          type="text"
          class="admin--form-input"
          placeholder="상세주소를 입력하세요"
        >
      </div>

      <!-- 위도/경도 -->
      <div class="admin--form-group">
        <label class="admin--form-label">위치 좌표</label>
        <div class="admin--coordinate-group">
          <div class="admin--coordinate-item">
            <label>위도</label>
            <input
              v-model.number="formData.latitude"
              type="number"
              step="any"
              class="admin--form-input"
              placeholder="37.5665"
            >
          </div>
          <div class="admin--coordinate-item">
            <label>경도</label>
            <input
              v-model.number="formData.longitude"
              type="number"
              step="any"
              class="admin--form-input"
              placeholder="126.9780"
            >
          </div>
        </div>
      </div>

      <!-- 영업시간 -->
      <div class="admin--form-group">
        <label class="admin--form-label">영업시간</label>
        <textarea
          v-model="formData.business_hours"
          class="admin--form-textarea"
          rows="3"
          placeholder="평일: 09:00 - 18:00&#10;주말: 10:00 - 17:00"
        ></textarea>
      </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 } from 'vue'
import { useRouter } from 'vue-router'

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

const router = useRouter()
const { post } = useApi()

const isSaving = ref(false)
const successMessage = ref('')
const errorMessage = ref('')

const formData = ref({
  name: '',
  phone: '',
  address: '',
  detail_address: '',
  latitude: null,
  longitude: null,
  business_hours: ''
})

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

  // 유효성 검사
  if (!formData.value.name) {
    errorMessage.value = '지점명을 입력하세요.'
    return
  }

  if (!formData.value.phone) {
    errorMessage.value = '대표번호를 입력하세요.'
    return
  }

  if (!formData.value.address) {
    errorMessage.value = '주소를 입력하세요.'
    return
  }

  isSaving.value = true

  try {
    const { data, error } = await post('/branch', formData.value)

    if (error || !data?.success) {
      errorMessage.value = error?.message || data?.message || '등록에 실패했습니다.'
    } else {
      successMessage.value = data.message || '지점이 등록되었습니다.'
      setTimeout(() => {
        router.push('/admin/branch/list')
      }, 1000)
    }
  } catch (error) {
    errorMessage.value = '서버 오류가 발생했습니다.'
    console.error('Save error:', error)
  } finally {
    isSaving.value = false
  }
}

// 목록으로 이동
const goToList = () => {
  router.push('/admin/branch/list')
}
</script>

<style scoped>
.admin--coordinate-group {
  display: flex;
  gap: 16px;
}

.admin--coordinate-item {
  flex: 1;
}

.admin--coordinate-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}
</style>
