<template>
  <div class="login-page">
    <div class="container mx-auto px-4 py-8">
      <div class="max-w-md mx-auto card">
        <div class="text-center mb-8">
          <h1 class="text-3xl font-bold text-gray-900 mb-2">登录</h1>
          <p class="text-gray-600">欢迎回到情绪博物馆</p>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          label-position="top"
          label-width="0"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="loginForm.phone"
              placeholder="请输入11位手机号"
              :prefix-icon="User"
              clearable
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <el-form-item label="短信验证码" prop="smsCode">
            <div class="sms-code-row">
              <el-input
                v-model="loginForm.smsCode"
                placeholder="请输入6位验证码"
                :prefix-icon="Key"
                clearable
                class="flex-1 sms-code-input"
                @keyup.enter="handleLogin"
                maxlength="6"
                show-word-limit
              />
              <el-button
                type="primary"
                plain
                class="sms-code-button"
                @click="handleSendSmsCode"
                :disabled="smsSending || countdown > 0"
              >
                {{ countdown > 0 ? `${countdown}s` : (smsSending ? '发送中...' : '获取验证码') }}
              </el-button>
            </div>
          </el-form-item>

          <el-form-item>
            <div class="flex justify-between items-center mb-4">
              <el-checkbox v-model="loginForm.rememberMe">
                记住我
              </el-checkbox>
              <router-link to="/forgot-password" class="text-primary-600 hover:underline text-sm">
                忘记密码？
              </router-link>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              class="w-full"
              :loading="loading"
              @click="handleLogin"
            >
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>

        </el-form>

        <div class="divider">
          <span>或</span>
        </div>

        <div class="social-login">
          <el-button class="social-btn wechat" @click="handleSocialLogin('wechat')">
            <el-icon><ChatDotRound /></el-icon>
            微信登录
          </el-button>
          <el-button class="social-btn qq" @click="handleSocialLogin('qq')">
            <el-icon><User /></el-icon>
            QQ登录
          </el-button>
        </div>

        <div class="text-center mt-6">
          <router-link to="/register" class="text-primary-600 hover:underline">
            还没有账号？立即注册
          </router-link>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElForm } from 'element-plus'
import {
  User,
  Lock,
  Key,
  Loading,
  ChatDotRound
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import AuthService from '@/services/auth'
import { envConfig } from '@/config/env'
import type { LoginRequest } from '@/types/auth'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()
const route = useRoute()
const authStore = useAuthStore()

// 表单引用
const loginFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 短信验证码发送状态
const smsSending = ref(false)
const countdown = ref(0)
let timer: number | null = null

// 登录表单数据（手机号+短信验证码）
const loginForm = reactive<LoginRequest>({
  phone: '',
  smsCode: '',
  rememberMe: false
})

// 表单验证规则（手机号 + 短信验证码）
const loginRules: FormRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 6, max: 6, message: '验证码必须为6位', trigger: 'blur' }
  ]
}

/**
 * 发送短信验证码
 */
const handleSendSmsCode = async () => {
  if (!loginForm.phone) {
    ElMessage.warning('请先填写手机号')
    return
  }
  if (!/^1[3-9]\d{9}$/.test(loginForm.phone)) {
    ElMessage.warning('手机号格式不正确')
    return
  }
  try {
    smsSending.value = true
    await AuthService.sendSmsCode(loginForm.phone)
    ElMessage.success('验证码已发送，请注意查收')
    // 启动倒计时
    countdown.value = 60
    timer && clearInterval(timer)
    timer = window.setInterval(() => {
      countdown.value -= 1
      if (countdown.value <= 0 && timer) {
        clearInterval(timer)
        timer = null
      }
    }, 1000)
  } catch (error) {
    console.error('发送短信验证码失败:', error)
  } finally {
    smsSending.value = false
  }
}

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

  try {
    console.log('🔐 开始登录流程...')

    // 表单验证
    await loginFormRef.value.validate()

    loading.value = true

    // 调用登录接口（手机号 + 短信验证码）
    const success = await authStore.login(loginForm)

    if (success) {
      const redirect = (route.query.redirect as string) || '/'
      await router.push(redirect)
    }
  } catch (error) {
    console.error('登录过程中发生错误:', error)
    ElMessage.error('登录失败，请检查网络连接或稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 处理第三方登录
 */
const handleSocialLogin = (platform: 'wechat' | 'qq') => {
  ElMessage.info(`${platform === 'wechat' ? '微信' : 'QQ'}登录功能开发中...`)
  // TODO: 实现第三方登录逻辑
}

// 组件挂载时：如果已登录直接跳转
onMounted(() => {
  if (authStore.isLoggedIn) {
    const redirect = (route.query.redirect as string) || '/'
    router.push(redirect)
  }
})
</script>
<style scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  background-attachment: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 1rem;
}

.container {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  padding: 2rem;
  width: 100%;
  max-width: 450px;
}

.card {
  background: transparent;
  border: none;
  box-shadow: none;
}

.login-form {
  margin-top: 0.5rem;
}

.sms-code-row {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  width: 100%;
}

.sms-code-button {
  white-space: nowrap;
  min-width: 110px;
}

.captcha-container {
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  transition: border-color 0.3s;
}

.captcha-container:hover {
  border-color: #409eff;
}

.captcha-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 3px;
}

.captcha-loading {
  color: #909399;
  font-size: 14px;
}

.divider {
  position: relative;
  text-align: center;
  margin: 1.5rem 0;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e4e7ed;
}

.divider span {
  background: rgba(255, 255, 255, 0.95);
  padding: 0 1rem;
  color: #909399;
  font-size: 14px;
}

.social-login {
  display: flex;
  gap: 0.5rem;
}

.social-btn {
  flex: 1;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s;
}

.social-btn.wechat {
  background: #07c160;
  border-color: #07c160;
  color: white;
}

.social-btn.wechat:hover {
  background: #06ad56;
  border-color: #06ad56;
  transform: translateY(-1px);
}

.social-btn.qq {
  background: #12b7f5;
  border-color: #12b7f5;
  color: white;
}

.social-btn.qq:hover {
  background: #0ea5e9;
  border-color: #0ea5e9;
  transform: translateY(-1px);
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #303133;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
  transition: all 0.3s;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

:deep(.el-button--primary) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  font-weight: 500;
  padding: 12px 20px;
  transition: all 0.3s;
}

:deep(.el-button--primary:hover) {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.text-primary-600 {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.text-primary-600:hover {
  color: #5a6fd8;
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .container {
    margin: 1rem;
    padding: 1.5rem;
    border-radius: 16px;
  }

  .captcha-container {
    width: 100px;
    height: 36px;
  }

  .social-login {
    flex-direction: column;
  }

  .sms-code-row {
    flex-direction: column;
    align-items: stretch;
    gap: 0.75rem;
  }

  .sms-code-button {
    width: 100%;
    text-align: center;
  }
}
</style>