<template>
  <div class="password-login">
    <el-form
      ref="loginFormRef"
      :model="loginForm"
      :rules="loginRules"
      label-position="top"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="loginForm.username"
          placeholder="请输入用户名"
          prefix-icon="User"
          clearable
          autocomplete="username"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          placeholder="请输入密码"
          prefix-icon="Lock"
          show-password
          clearable
          autocomplete="current-password"
        />
      </el-form-item>

      <el-form-item>
        <el-checkbox v-model="loginForm.remember" size="large">记住密码</el-checkbox>
        <el-link type="primary" :underline="false" class="forgot-password" @click="handleForgotPassword">
          忘记密码？
        </el-link>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleLogin"
          size="large"
          block
        >
          登录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import type { LoginFormData } from '@/types';
import { useAuthStore } from '../../stores/auth.ts';

// Define props and emit
const emit = defineEmits<{
  'login-success': [token: any, user: any];
}>();

// Initialize auth store
const authStore = useAuthStore();

// Form ref
const loginFormRef = ref<FormInstance>();

// Login form data
const loginForm = reactive<LoginFormData & { remember: boolean }>({
  username: '',
  password: '',
  remember: false
});

// Loading state
const loading = ref(false);

// Form rules
const loginRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ]
});

// Handle login
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate();
    loading.value = true;

    // Call actual login method from auth store
    const tokenData = await authStore.loginWithPassword(loginForm.username, loginForm.password);

    ElMessage.success('登录成功');
    emit('login-success', tokenData, authStore.user);
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败，请检查用户名和密码');
  } finally {
    loading.value = false;
  }
};

// Handle forgot password
const handleForgotPassword = () => {
  ElMessage.info('忘记密码功能开发中');
};
</script>

<style scoped>
.password-login {
  margin-top: 20px;
}

.forgot-password {
  float: right;
}
</style>