<template>
  <div class="admin--modal-overlay" @click.self="close">
    <div class="admin--modal">
      <div class="admin--modal-header">
        <h4>비밀번호 변경</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--info-box">
            <p><strong>관리자:</strong> {{ admin.name }} ({{ admin.username }})</p>
          </div>

          <div class="admin--form-group" v-if="isCurrentUser">
            <label class="admin--form-label">현재 비밀번호</label>
            <input
              v-model="formData.current_password"
              type="password"
              class="admin--form-input"
              placeholder="현재 비밀번호 입력"
            />
            <small class="admin--help-text">본인 계정의 경우 현재 비밀번호를 입력해주세요.</small>
          </div>

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

          <div class="admin--form-group">
            <label class="admin--form-label">새 비밀번호 확인 *</label>
            <input
              v-model="formData.new_password_confirm"
              type="password"
              class="admin--form-input"
              required
              placeholder="새 비밀번호 재입력"
              minlength="8"
            />
          </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 } from 'vue'

const props = defineProps({
  admin: {
    type: Object,
    required: true
  }
})

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

const { post } = useApi()

const saving = ref(false)

// 현재 로그인한 관리자 ID
const currentAdminId = computed(() => {
  if (typeof window === 'undefined') return null
  const user = localStorage.getItem('admin_user')
  if (!user) return null
  try {
    return JSON.parse(user).id
  } catch {
    return null
  }
})

const isCurrentUser = computed(() => {
  return currentAdminId.value === props.admin.id
})

const formData = ref({
  current_password: '',
  new_password: '',
  new_password_confirm: ''
})

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

const save = async () => {
  // 비밀번호 확인
  if (formData.value.new_password !== formData.value.new_password_confirm) {
    emit('saved', '새 비밀번호가 일치하지 않습니다.')
    return
  }

  if (formData.value.new_password.length < 8) {
    emit('saved', '비밀번호는 최소 8자 이상이어야 합니다.')
    return
  }

  saving.value = true

  try {
    const requestData = {
      new_password: formData.value.new_password
    }

    // 본인 계정인 경우 현재 비밀번호 포함
    if (isCurrentUser.value && formData.value.current_password) {
      requestData.current_password = formData.value.current_password
    }

    const { data, error } = await post(`/admin/${props.admin.id}/password`, requestData)

    if (error) {
      console.error('[PasswordModal] 변경 실패:', error)
      const errorMessage = error.response?.data?.message || '비밀번호 변경에 실패했습니다.'
      emit('saved', errorMessage)
      return
    }

    if (data?.success) {
      emit('saved', '비밀번호가 변경되었습니다.')
    }
  } 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: 500px;
  max-width: 600px;
  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--info-box {
  background: #f5f5f5;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  padding: 12px 16px;
  margin-bottom: 20px;
}

.admin--info-box p {
  margin: 0;
  color: #333333;
  font-size: 14px;
}

.admin--info-box strong {
  color: #1a1a1a;
  font-weight: 600;
}

.admin--form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
}

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

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

.admin--form-input {
  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 {
  outline: none;
  border-color: var(--admin-accent-primary, #217346);
}

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

.admin--help-text {
  display: block;
  margin-top: 6px;
  font-size: 12px;
  color: #666;
  line-height: 1.4;
}

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