<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>

      <form @submit.prevent="save" class="admin--modal-form">
        <div class="admin--modal-body">
          <div class="admin--form-row">
            <div class="admin--form-group">
              <label class="admin--form-label">아이디 *</label>
              <div v-if="!isEdit" class="admin--input-with-button">
                <input
                  v-model="formData.username"
                  type="text"
                  class="admin--form-input"
                  required
                  placeholder="영문, 숫자 조합"
                  @input="handleUsernameInput"
                />
                <button
                  type="button"
                  class="admin--btn-check"
                  @click="checkDuplicateUsername"
                  :disabled="!formData.username || isCheckingUsername"
                >
                  {{ isCheckingUsername ? '확인 중...' : '중복 체크' }}
                </button>
              </div>
              <input
                v-else
                v-model="formData.username"
                type="text"
                class="admin--form-input"
                required
                :disabled="true"
                placeholder="영문, 숫자 조합"
              />
              <p v-if="!isEdit && usernameCheckResult === 'available'" class="admin--form-help admin--text-success">
                사용 가능한 아이디입니다.
              </p>
              <p v-if="!isEdit && usernameCheckResult === 'duplicate'" class="admin--form-help admin--text-error">
                이미 사용 중인 아이디입니다.
              </p>
            </div>

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

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

            <div class="admin--form-group">
              <label class="admin--form-label">부서명</label>
              <input
                v-model="formData.department"
                type="text"
                class="admin--form-input"
                placeholder="예: 개발팀, 영업팀"
              />
            </div>
          </div>

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

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

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

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

        <div class="admin--modal-footer">
          <button type="button" @click="close" class="admin--btn-small admin--btn-small-secondary">
            취소
          </button>
          <button type="submit" class="admin--btn-small admin--btn-small-primary" :disabled="saving">
            {{ saving ? '저장 중...' : '저장' }}
          </button>
        </div>
      </form>
    </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 { get, post, put } = useApi()

const isEdit = computed(() => !!props.admin)
const saving = ref(false)
const isCheckingUsername = ref(false)
const usernameCheckResult = ref('') // 'available', 'duplicate', ''

const formData = ref({
  username: '',
  name: '',
  email: '',
  department: '',
  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 || '',
      department: newAdmin.department || '',
      password: '',
      password_confirm: '',
      role: newAdmin.role || 'admin',
      status: newAdmin.status || 'active'
    }
  }
}, { immediate: true })

// 아이디 입력 시 중복 체크 결과 초기화
const handleUsernameInput = () => {
  usernameCheckResult.value = ''
}

// 아이디 중복 체크
const checkDuplicateUsername = async () => {
  if (!formData.value.username) {
    alert('아이디를 입력하세요.')
    return
  }

  isCheckingUsername.value = true
  usernameCheckResult.value = ''

  try {
    const { data, error } = await get('/admin/check-username', {
      params: {
        username: formData.value.username
      }
    })

    console.log('[AdminModal] 중복 체크 응답:', { data, error })

    if (error) {
      alert('중복 체크에 실패했습니다.')
      return
    }

    if (data?.success) {
      if (data?.data?.available) {
        usernameCheckResult.value = 'available'
      } else {
        usernameCheckResult.value = 'duplicate'
      }
    }
  } catch (error) {
    console.error('중복 체크 오류:', error)
    alert('중복 체크 중 오류가 발생했습니다.')
  } finally {
    isCheckingUsername.value = false
  }
}

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

const save = async () => {
  // 신규 생성 시 유효성 검사
  if (!isEdit.value) {
    // 아이디 중복 체크 확인
    if (usernameCheckResult.value !== 'available') {
      alert('아이디 중복 체크를 해주세요.')
      return
    }

    // 비밀번호 확인
    if (formData.value.password !== formData.value.password_confirm) {
      alert('비밀번호가 일치하지 않습니다.')
      return
    }
    if (formData.value.password.length < 8) {
      alert('비밀번호는 최소 8자 이상이어야 합니다.')
      return
    }
  }

  saving.value = true

  try {
    let result

    if (isEdit.value) {
      // 수정
      const updateData = {
        name: formData.value.name,
        email: formData.value.email,
        department: formData.value.department,
        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,
        department: formData.value.department,
        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>

<style scoped>
.admin--modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.admin--modal {
  background: #ffffff;
  padding: 0;
  border-radius: 8px;
  min-width: 700px;
  max-width: 800px;
  width: 90%;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.admin--modal-form {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-height: 0;
}

.admin--modal-header {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.admin--modal-header h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
}

.admin--modal-close {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #999;
  line-height: 1;
  transition: color 0.2s;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.admin--modal-close:hover {
  color: #333;
}

.admin--modal-body {
  padding: 24px;
  overflow-y: auto;
  flex: 1;
  min-height: 0;
}

.admin--form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 20px;
}

.admin--form-row:last-child {
  margin-bottom: 0;
}

.admin--form-group {
  display: flex;
  flex-direction: column;
}

.admin--form-label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #333333;
}

.admin--form-input,
.admin--form-select {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  background: #ffffff;
  color: #333333;
  font-size: 14px;
  transition: border-color 0.2s;
}

.admin--form-input:focus,
.admin--form-select:focus {
  outline: none;
  border-color: var(--admin-accent-primary, #217346);
}

.admin--form-input:disabled {
  background: #f5f5f5;
  color: #999;
  cursor: not-allowed;
}

.admin--form-input::placeholder {
  color: #999;
}

.admin--modal-footer {
  padding: 20px 24px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
  flex-shrink: 0;
}

.admin--btn-small {
  padding: 6px 14px;
  border: none;
  border-radius: 4px;
  font-size: 13px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  font-family: 'FORDKOREAType', sans-serif;
  white-space: nowrap;
}

.admin--btn-small:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.admin--btn-small-secondary {
  background: #f5f5f5;
  color: #333333;
  border: 1px solid #e0e0e0;
}

.admin--btn-small-secondary:hover:not(:disabled) {
  background: #eeeeee;
  border-color: var(--admin-accent-primary, #217346);
  color: #333333;
}

.admin--btn-small-primary {
  background: var(--admin-accent-primary, #217346);
  color: #ffffff;
}

.admin--btn-small-primary:hover:not(:disabled) {
  background: var(--admin-accent-hover, #1a5c37);
}

</style>
