<template>
  <div class="sms-login">
    <el-form
      ref="smsFormRef"
      :model="smsForm"
      :rules="smsRules"
      label-position="top"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input
          v-model="smsForm.phone"
          placeholder="请输入手机号"
          prefix-icon="Phone"
          clearable
          maxlength="11"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="验证码" prop="code">
        <el-input
          v-model="smsForm.code"
          placeholder="请输入验证码"
          prefix-icon="Message"
          clearable
          maxlength="6"
          show-word-limit
        >
          <template #append>
            <el-button
              :disabled="countdown > 0"
              @click="handleSendCode"
              type="primary"
              :loading="sendingCode"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
            </el-button>
          </template>
        </el-input>
      </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 { SmsLoginFormData } 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 smsFormRef = ref<FormInstance>();

// SMS form data
const smsForm = reactive<SmsLoginFormData>({
  phone: '',
  code: ''
});

// Loading states
const loading = ref(false);
const sendingCode = ref(false);
const countdown = ref(0);
let countdownTimer: number | null = null;

// Form rules
const smsRules = reactive<FormRules>({
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { pattern: /^\d{6}$/, message: '请输入6位数字验证码', trigger: 'blur' }
  ]
});

// Handle send verification code
const handleSendCode = async () => {
  if (!smsFormRef.value) return;

  try {
    await smsFormRef.value.validateField('phone');
    sendingCode.value = true;

    // Mock send code request - replace with actual API call in production
    await new Promise(resolve => setTimeout(resolve, 800));

    ElMessage.success('验证码发送成功');
    startCountdown();
  } catch (error) {
    ElMessage.error('请输入正确的手机号');
  } finally {
    sendingCode.value = false;
  }
};

// Start countdown for resending code
const startCountdown = () => {
  countdown.value = 60;
  
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
  
  countdownTimer = window.setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      if (countdownTimer) {
        clearInterval(countdownTimer);
        countdownTimer = null;
      }
    }
  }, 1000);
};

// Handle login with SMS code
const handleLogin = async () => {
  if (!smsFormRef.value) return;

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

    // Call actual SMS login method from auth store
    const tokenData = await authStore.loginWithSms(smsForm.phone, smsForm.code);

    ElMessage.success('登录成功');
    emit('login-success', tokenData, authStore.user);
  } catch (error: any) {
    ElMessage.error(error.message || '登录失败，请检查验证码是否正确');
  } finally {
    loading.value = false;
  }
};
</script>

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