<template>
  <div class="admin--modal-overlay" @click.self="close">
    <div class="admin--modal">
      <div class="admin--modal-header">
        <h4>{{ isEdit ? '관리자 수정' : '관리자 추가' }}</h4>
        <button @click="close" class="admin--modal-close">&times;</button>
      </div>

      <div class="admin--modal-body">
        <form @submit.prevent="save">
          <div class="admin--form-group">
            <label class="admin--label">아이디 *</label>
            <input
              v-model="formData.username"
              type="text"
              class="admin--input"
              required
              :disabled="isEdit"
              placeholder="영문, 숫자 조합"
            />
          </div>

          <div class="admin--form-group">
            <label class="admin--label">이름 *</label>
            <input
              v-model="formData.name"
              type="text"
              class="admin--input"
              required
              placeholder="관리자 이름"
            />
          </div>

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

          <div class="admin--form-group" v-if="!isEdit">
            <label class="admin--label">비밀번호 *</label>
            <input
              v-model="formData.password"
              type="password"
              class="admin--input"
              :required="!isEdit"
              placeholder="최소 8자 이상"
              minlength="8"
            />
          </div>

          <div class="admin--form-group" v-if="!isEdit">
            <label class="admin--label">비밀번호 확인 *</label>
            <input
              v-model="formData.password_confirm"
              type="password"
              class="admin--input"
              :required="!isEdit"
              placeholder="비밀번호 재입력"
              minlength="8"
            />
          </div>

          <div class="admin--form-group">
            <label class="admin--label">역할 *</label>
            <select v-model="formData.role" class="admin--select" required>
              <option value="admin">일반 관리자</option>
              <option value="super_admin">슈퍼 관리자</option>
            </select>
          </div>

          <div class="admin--form-group">
            <label class="admin--label">상태 *</label>
            <select v-model="formData.status" class="admin--select" required>
              <option value="active">활성</option>
              <option value="inactive">비활성</option>
            </select>
          </div>

          <div class="admin--modal-footer">
            <button type="button" @click="close" class="admin--btn-secondary">
              취소
            </button>
            <button type="submit" class="admin--btn-primary" :disabled="saving">
              {{ saving ? '저장 중...' : '저장' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

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

const props = defineProps({
  admin: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['close', 'saved'])

const { post, put } = useApi()

const isEdit = computed(() => !!props.admin)
const saving = ref(false)

const formData = ref({
  username: '',
  name: '',
  email: '',
  password: '',
  password_confirm: '',
  role: 'admin',
  status: 'active'
})

// props.admin이 변경되면 formData 업데이트
watch(() => props.admin, (newAdmin) => {
  if (newAdmin) {
    formData.value = {
      username: newAdmin.username || '',
      name: newAdmin.name || '',
      email: newAdmin.email || '',
      password: '',
      password_confirm: '',
      role: newAdmin.role || 'admin',
      status: newAdmin.status || 'active'
    }
  }
}, { immediate: true })

const close = () => {
  emit('close')
}

const save = async () => {
  // 비밀번호 확인 (신규 생성 시)
  if (!isEdit.value) {
    if (formData.value.password !== formData.value.password_confirm) {
      emit('saved', '비밀번호가 일치하지 않습니다.')
      return
    }
    if (formData.value.password.length < 8) {
      emit('saved', '비밀번호는 최소 8자 이상이어야 합니다.')
      return
    }
  }

  saving.value = true

  try {
    let result

    if (isEdit.value) {
      // 수정
      const updateData = {
        name: formData.value.name,
        email: formData.value.email,
        role: formData.value.role,
        status: formData.value.status
      }
      result = await put(`/admin/${props.admin.id}`, updateData)
    } else {
      // 생성
      const createData = {
        username: formData.value.username,
        name: formData.value.name,
        email: formData.value.email,
        password: formData.value.password,
        role: formData.value.role,
        status: formData.value.status
      }
      result = await post('/admin', createData)
    }

    const { data, error } = result

    if (error) {
      console.error('[AdminModal] 저장 실패:', error)
      const errorMessage = error.response?.data?.message || '저장에 실패했습니다.'
      emit('saved', errorMessage)
      return
    }

    if (data?.success) {
      emit('saved', data.message || '저장되었습니다.')
    }
  } finally {
    saving.value = false
  }
}
</script>
