<template>
  <div class="admin--manager-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.branch_id"
          class="admin--form-select"
          required
        >
          <option value="">지점을 선택하세요</option>
          <option
            v-for="branch in branches"
            :key="branch.id"
            :value="branch.id"
          >
            {{ branch.name }}
          </option>
        </select>
      </div>

      <!-- 아이디 -->
      <div class="admin--form-group">
        <label class="admin--form-label">아이디 <span class="admin--required">*</span></label>
        <input
          v-model="formData.user_id"
          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>
        <div class="admin--password-input-wrapper">
          <input
            v-model="formData.password"
            :type="showPassword ? 'text' : 'password'"
            class="admin--form-input"
            placeholder="비밀번호를 입력하세요"
            required
          >
          <button
            type="button"
            class="admin--password-toggle"
            @click="showPassword = !showPassword"
          >
            {{ showPassword ? '👁️' : '👁️‍🗨️' }}
          </button>
        </div>
      </div>

      <!-- 비밀번호 확인 -->
      <div class="admin--form-group">
        <label class="admin--form-label">비밀번호 확인 <span class="admin--required">*</span></label>
        <div class="admin--password-input-wrapper">
          <input
            v-model="formData.password_confirm"
            :type="showPasswordConfirm ? 'text' : 'password'"
            class="admin--form-input"
            placeholder="비밀번호를 다시 입력하세요"
            required
          >
          <button
            type="button"
            class="admin--password-toggle"
            @click="showPasswordConfirm = !showPasswordConfirm"
          >
            {{ showPasswordConfirm ? '👁️' : '👁️‍🗨️' }}
          </button>
        </div>
      </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.email"
          type="email"
          class="admin--form-input"
          placeholder="email@example.com"
          required
        >
      </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 } = useApi()

const isSaving = ref(false)
const successMessage = ref('')
const errorMessage = ref('')
const showPassword = ref(false)
const showPasswordConfirm = ref(false)
const branches = ref([])

const formData = ref({
  branch_id: '',
  user_id: '',
  password: '',
  password_confirm: '',
  name: '',
  email: ''
})

// 지점 목록 로드
const loadBranches = async () => {
  const { data, error } = await get('/branch/list', { per_page: 1000 })
  console.log('[BranchManagerCreate] API 응답:', { data, error })

  if (data?.success && data?.data) {
    branches.value = data.data.items || []
    console.log('[BranchManagerCreate] 지점 목록 로드 성공')
  }
}

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

  // 유효성 검사
  if (!formData.value.branch_id) {
    errorMessage.value = '지점을 선택하세요.'
    return
  }

  if (!formData.value.user_id) {
    errorMessage.value = '아이디를 입력하세요.'
    return
  }

  if (!formData.value.password) {
    errorMessage.value = '비밀번호를 입력하세요.'
    return
  }

  if (formData.value.password !== formData.value.password_confirm) {
    errorMessage.value = '비밀번호가 일치하지 않습니다.'
    return
  }

  if (!formData.value.name) {
    errorMessage.value = '관리자명을 입력하세요.'
    return
  }

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

  isSaving.value = true

  try {
    const submitData = {
      branch_id: formData.value.branch_id,
      user_id: formData.value.user_id,
      password: formData.value.password,
      name: formData.value.name,
      email: formData.value.email
    }

    const { data, error } = await post('/branch/manager', submitData)

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

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

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