<template>
  <Teleport to="body">
    <Transition name="modal">
      <div
        v-if="isOpen"
        class="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm px-4"
        @click.self="closeModal"
      >
        <div
          ref="modalRef"
          class="relative w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden"
          @click.stop
        >
          <!-- 关闭按钮 -->
          <button
            @click="closeModal"
            class="absolute top-4 right-4 w-8 h-8 flex items-center justify-center rounded-full hover:bg-gray-100 transition-colors z-10"
            aria-label="Close"
          >
            <Icon name="ph:x" class="w-5 h-5 text-gray-600" />
          </button>

          <!-- 登录表单 -->
          <div class="p-8">
            <h2 class="text-2xl md:text-3xl font-bold text-black mb-2">{{ t('auth.login') }}</h2>
            <p class="text-gray-600 mb-8">{{ t('auth.loginDescription') }}</p>

            <form @submit.prevent="handleLogin" class="space-y-5">
              <div>
                <label for="account" class="block text-sm font-semibold text-gray-800 mb-2">
                  {{ t('auth.account') }}
                </label>
                <input
                  id="account"
                  v-model="account"
                  type="text"
                  required
                  :disabled="isLoggingIn"
                  class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                  :placeholder="t('auth.accountPlaceholder')"
                />
              </div>

              <div>
                <label for="password" class="block text-sm font-semibold text-gray-800 mb-2">
                  {{ t('auth.password') }}
                </label>
                <input
                  id="password"
                  v-model="password"
                  type="password"
                  required
                  :disabled="isLoggingIn"
                  class="w-full px-4 py-3 rounded-xl border border-gray-200 focus:border-black focus:ring-2 focus:ring-black/5 outline-none transition-all duration-300 disabled:opacity-50 disabled:cursor-not-allowed"
                  :placeholder="t('auth.passwordPlaceholder')"
                />
              </div>

              <!-- 错误消息 -->
              <div v-if="errorMessage" class="p-3 rounded-lg bg-red-50 border border-red-200 text-red-800 text-sm">
                {{ errorMessage }}
              </div>

              <!-- 登录按钮 -->
              <button
                type="submit"
                :disabled="isLoggingIn || !account || !password"
                class="w-full py-3 rounded-xl font-semibold text-white transition-all duration-300 flex items-center justify-center gap-2"
                :class="isLoggingIn || !account || !password
                  ? 'bg-gray-400 cursor-not-allowed'
                  : 'bg-black hover:bg-gray-800 shadow-lg hover:shadow-xl'"
              >
                <Icon v-if="isLoggingIn" name="ph:circle-notch" class="w-5 h-5 animate-spin" />
                <span>{{ isLoggingIn ? t('auth.loggingIn') : t('auth.loginButton') }}</span>
              </button>
            </form>

            <!-- 提示信息 -->
            <p class="mt-6 text-center text-sm text-gray-500">
              {{ t('auth.demoHint') }}
            </p>

            <!-- 注册账号链接 -->
            <p class="mt-4 text-center text-sm text-gray-600">
              {{ t('auth.noAccount') }}
              <button @click="switchToRegister" class="text-black font-semibold hover:underline">
                {{ t('auth.createAccount') }}
              </button>
            </p>
          </div>
        </div>
      </div>
    </Transition>
  </Teleport>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useUserStore } from '~/stores/user'

const { t } = useI18n()
const userStore = useUserStore()

interface Props {
  isOpen: boolean
}

const props = defineProps<Props>()
const emit = defineEmits<{
  close: []
  switchToRegister: []
}>()

const modalRef = ref<HTMLElement | null>(null)
const account = ref('')
const password = ref('')
const isLoggingIn = ref(false)
const errorMessage = ref('')

// 关闭模态框
const closeModal = () => {
  if (!isLoggingIn.value) {
    emit('close')
  }
}

// 切换到注册
const switchToRegister = () => {
  emit('switchToRegister')
}

// 处理登录
const handleLogin = async () => {
  if (isLoggingIn.value) return

  isLoggingIn.value = true
  errorMessage.value = ''

  try {
    const result = await userStore.login(account.value, password.value)

    if (result.success) {
      // 登录成功，关闭模态框
      account.value = ''
      password.value = ''
      closeModal()
    } else {
      errorMessage.value = t('auth.loginError')
    }
  } catch (error) {
    console.error('Login error:', error)
    errorMessage.value = t('auth.loginError')
  } finally {
    isLoggingIn.value = false
  }
}

// 监听打开状态，重置表单
watch(() => props.isOpen, (isOpen) => {
  if (isOpen) {
    account.value = ''
    password.value = ''
    errorMessage.value = ''
    // 禁止背景滚动
    document.body.style.overflow = 'hidden'
  } else {
    // 恢复滚动
    document.body.style.overflow = ''
  }
})

// ESC 键关闭
const handleKeydown = (e: KeyboardEvent) => {
  if (e.key === 'Escape' && props.isOpen) {
    closeModal()
  }
}

// 添加键盘事件监听
if (typeof window !== 'undefined') {
  window.addEventListener('keydown', handleKeydown)
}
</script>

<style scoped>
.modal-enter-active,
.modal-leave-active {
  transition: opacity 0.3s ease;
}

.modal-enter-from,
.modal-leave-to {
  opacity: 0;
}

.modal-enter-active .relative,
.modal-leave-active .relative {
  transition: transform 0.3s ease, opacity 0.3s ease;
}

.modal-enter-from .relative {
  transform: scale(0.95) translateY(20px);
  opacity: 0;
}

.modal-leave-to .relative {
  transform: scale(0.95) translateY(20px);
  opacity: 0;
}
</style>
