<script setup lang="ts">
import type { LoginRequest } from '@/service/types' // 假设你的类型定义
import { computed, reactive, ref } from 'vue'

// 扩展 Props 和 Emits 定义
interface Props {
  mode: 'login' | 'reset'
}

// 定义登录载荷类型（根据实际情况调整）
type LoginPayload
  = | { type: 'password', data: LoginRequest }
    | { type: 'code', data: { phone: string, code: string } }

interface Emits {
  // 登录事件：区分密码登录和验证码登录
  (e: 'login', payload: LoginPayload): void
  // 重置密码事件
  (e: 'reset', data: { phone: string, code: string, password: string }): void
  // 切换模式事件
  (e: 'switchMode', mode: 'login' | 'reset'): void
  // 发送验证码事件：type 区分是登录用还是重置用
  (e: 'sendCode', payload: { phone: string, type: 'login' | 'reset' }): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// --- 状态管理 ---
const loading = ref(false)
const agreed = ref(false)
const loginType = ref<'password' | 'code'>('password') // 登录方式：密码 | 验证码
const countdown = ref(0) // 倒计时
let timer: ReturnType<typeof setInterval> | null = null

// --- 表单数据 ---
// 1. 密码登录表单
const loginPwdForm = reactive({
  username_or_phone: '',
  password: '',
})

// 2. 验证码登录表单
const loginCodeForm = reactive({
  phone: '',
  code: '',
})

// 3. 重置密码表单
const resetForm = reactive({
  phone: '',
  code: '',
  password: '',
  confirmPassword: '',
})

// --- 计算属性 ---
const isLogin = computed(() => props.mode === 'login')
// 获取验证码按钮文字
const codeBtnText = computed(() => countdown.value > 0 ? `${countdown.value}s后重发` : '获取验证码')
const isCodeSending = computed(() => countdown.value > 0)

// --- 辅助函数：手机号验证 ---
function isValidPhone(phone: string) {
  return /^1[3-9]\d{9}$/.test(phone)
}

// --- 表单验证 ---
function validatePwdLogin() {
  if (!loginPwdForm.username_or_phone)
    return uni.showToast({ title: '请输入账号', icon: 'none' })
  if (!loginPwdForm.password)
    return uni.showToast({ title: '请输入密码', icon: 'none' })
  if (!agreed.value)
    return uni.showToast({ title: '请先同意用户协议', icon: 'none' })
  return true
}

function validateCodeLogin() {
  if (!loginCodeForm.phone || !isValidPhone(loginCodeForm.phone))
    return uni.showToast({ title: '请输入正确手机号', icon: 'none' })
  if (!loginCodeForm.code || loginCodeForm.code.length !== 6)
    return uni.showToast({ title: '请输入6位验证码', icon: 'none' })
  if (!agreed.value)
    return uni.showToast({ title: '请先同意用户协议', icon: 'none' })
  return true
}

function validateReset() {
  if (!resetForm.phone || !isValidPhone(resetForm.phone))
    return uni.showToast({ title: '请输入正确手机号', icon: 'none' })
  if (!resetForm.code || resetForm.code.length !== 6)
    return uni.showToast({ title: '请输入6位验证码', icon: 'none' })
  if (!resetForm.password || resetForm.password.length < 8)
    return uni.showToast({ title: '新密码不能少于8位', icon: 'none' })
  if (resetForm.password !== resetForm.confirmPassword)
    return uni.showToast({ title: '两次密码不一致', icon: 'none' })
  if (!agreed.value)
    return uni.showToast({ title: '请先同意用户协议', icon: 'none' })
  return true
}

// --- 事件处理 ---

// 1. 发送验证码
function handleSendCode() {
  if (isCodeSending.value)
    return

  const isResetMode = !isLogin.value
  const targetPhone = isResetMode ? resetForm.phone : loginCodeForm.phone

  if (!targetPhone || !isValidPhone(targetPhone)) {
    return uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
  }

  // 触发父组件发送请求
  emit('sendCode', {
    phone: targetPhone,
    type: isResetMode ? 'reset' : 'login',
  })

  // 启动倒计时 (实际项目中建议在父组件请求成功后再启动，这里为了交互演示直接启动)
  startCountdown()
}

function startCountdown() {
  countdown.value = 60
  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      if (timer)
        clearInterval(timer)
    }
  }, 1000)
}

// 2. 提交表单
function handleSubmit() {
  if (isLogin.value) {
    if (loginType.value === 'password') {
      if (validatePwdLogin()) {
        emit('login', { type: 'password', data: { ...loginPwdForm } })
      }
    }
    else {
      if (validateCodeLogin()) {
        emit('login', { type: 'code', data: { ...loginCodeForm } })
      }
    }
  }
  else {
    if (validateReset()) {
      emit('reset', {
        phone: resetForm.phone,
        code: resetForm.code,
        password: resetForm.password,
      })
    }
  }
}

// 3. 切换 登录/重置 模式
function handleSwitchMode() {
  // 清除状态
  loginType.value = 'password'
  const newMode = isLogin.value ? 'reset' : 'login'
  emit('switchMode', newMode)
}
</script>

<template>
  <view class="w-full px-5 py-6">
    <view class="mb-6 pl-1">
      <text class="block text-center text-lg text-slate-800 font-bold">
        {{ isLogin ? '' : '设置新密码' }}
      </text>

      <view v-if="isLogin" class="flex justify-center space-x-6">
        <view
          class="relative pb-2 transition-all"
          @click="loginType = 'password'"
        >
          <text
            class="text-sm transition-colors"
            :class="loginType === 'password' ? 'text-blue-600 font-bold' : 'text-slate-400'"
          >
            账号密码登录
          </text>
          <view
            class="absolute bottom-0 left-1/2 h-0.5 w-4 rounded-full bg-blue-600 transition-all duration-300 -translate-x-1/2"
            :class="loginType === 'password' ? 'opacity-100' : 'opacity-0'"
          />
        </view>

        <view
          class="relative pb-2 transition-all"
          @click="loginType = 'code'"
        >
          <text
            class="text-sm transition-colors"
            :class="loginType === 'code' ? 'text-blue-600 font-bold' : 'text-slate-400'"
          >
            验证码登录
          </text>
          <view
            class="absolute bottom-0 left-1/2 h-0.5 w-4 rounded-full bg-blue-600 transition-all duration-300 -translate-x-1/2"
            :class="loginType === 'code' ? 'opacity-100' : 'opacity-0'"
          />
        </view>
      </view>
    </view>

    <view class="space-y-3">
      <view v-if="isLogin" class="space-y-3">
        <template v-if="loginType === 'password'">
          <view class="h-10 w-full flex items-center rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
            <text class="i-carbon-user mr-2 text-base text-slate-400" />
            <input
              v-model="loginPwdForm.username_or_phone"
              type="text"
              placeholder="手机号 / 用户名"
              placeholder-class="text-slate-400 text-xs"
              class="h-full flex-1 bg-transparent text-xs text-slate-800 outline-none"
            >
          </view>
          <view class="h-10 w-full flex items-center rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
            <text class="i-carbon-locked mr-2 text-base text-slate-400" />
            <input
              v-model="loginPwdForm.password"
              type="password"
              placeholder="请输入密码"
              placeholder-class="text-slate-400 text-xs"
              class="h-full flex-1 bg-transparent text-xs text-slate-800 outline-none"
            >
          </view>
        </template>

        <template v-else>
          <view class="h-10 w-full flex items-center rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
            <text class="i-carbon-phone mr-2 text-base text-slate-400" />
            <input
              v-model="loginCodeForm.phone"
              type="number"
              maxlength="11"
              placeholder="请输入手机号"
              placeholder-class="text-slate-400 text-xs"
              class="h-full flex-1 bg-transparent text-xs text-slate-800 outline-none"
            >
          </view>
          <view class="h-10 w-full flex items-center justify-between rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
            <view class="flex flex-1 items-center">
              <text class="i-carbon-security mr-2 text-base text-slate-400" />
              <input
                v-model="loginCodeForm.code"
                type="number"
                maxlength="6"
                placeholder="输入验证码"
                placeholder-class="text-slate-400 text-xs"
                class="h-full w-full bg-transparent text-xs text-slate-800 outline-none"
              >
            </view>
            <view class="mx-2 h-4 w-1px bg-slate-300" />
            <text
              class="whitespace-nowrap text-xs font-medium transition-colors"
              :class="isCodeSending ? 'text-slate-400' : 'text-blue-600 active:opacity-70'"
              @click="handleSendCode"
            >
              {{ codeBtnText }}
            </text>
          </view>
        </template>
      </view>

      <view v-else class="space-y-3">
        <view class="h-10 w-full flex items-center rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
          <text class="i-carbon-phone mr-2 text-base text-slate-400" />
          <input
            v-model="resetForm.phone"
            type="number"
            maxlength="11"
            placeholder="请输入手机号"
            placeholder-class="text-slate-400 text-xs"
            class="h-full flex-1 bg-transparent text-xs text-slate-800 outline-none"
          >
        </view>

        <view class="h-10 w-full flex items-center justify-between rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
          <view class="flex flex-1 items-center">
            <text class="i-carbon-security mr-2 text-base text-slate-400" />
            <input
              v-model="resetForm.code"
              type="number"
              placeholder="6位验证码"
              maxlength="6"
              placeholder-class="text-slate-400 text-xs"
              class="h-full w-full bg-transparent text-xs text-slate-800 outline-none"
            >
          </view>
          <view class="mx-2 h-4 w-1px bg-slate-300" />
          <text
            class="whitespace-nowrap text-xs font-medium transition-colors"
            :class="isCodeSending ? 'text-slate-400' : 'text-blue-600 active:opacity-70'"
            @click="handleSendCode"
          >
            {{ codeBtnText }}
          </text>
        </view>

        <view class="h-10 w-full flex items-center rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
          <text class="i-carbon-locked mr-2 text-base text-slate-400" />
          <input
            v-model="resetForm.password"
            type="password"
            placeholder="新密码 (8位以上)"
            placeholder-class="text-slate-400 text-xs"
            class="h-full flex-1 bg-transparent text-xs text-slate-800 outline-none"
          >
        </view>

        <view class="h-10 w-full flex items-center rounded-lg bg-slate-100 px-3 transition-all focus-within:bg-white focus-within:ring-1 focus-within:ring-blue-500">
          <text class="i-carbon-checkbox-checked mr-2 text-base text-slate-400" />
          <input
            v-model="resetForm.confirmPassword"
            type="password"
            placeholder="确认新密码"
            placeholder-class="text-slate-400 text-xs"
            class="h-full flex-1 bg-transparent text-xs text-slate-800 outline-none"
          >
        </view>

        <text class="block px-1 text-12px text-slate-400">
          * 密码需包含字母与数字，不能包含中文
        </text>
      </view>

      <view class="mt-1 flex items-center px-1" @click="agreed = !agreed">
        <view
          class="mr-2 h-3 w-3 flex items-center justify-center border rounded-full transition-colors"
          :class="agreed ? 'border-blue-500 bg-blue-500' : 'border-slate-300 bg-white'"
        >
          <text v-if="agreed" class="i-carbon-checkmark text-8px text-white" />
        </view>
        <text class="text-[10px] text-slate-500">
          我同意《用户协议》与《隐私政策》
        </text>
      </view>
    </view>

    <view class="mt-6">
      <button
        class="h-10 w-full flex items-center justify-center rounded-full bg-blue-600 text-xs text-white font-bold transition-all active:scale-95 active:bg-blue-700"
        :disabled="loading"
        @click="handleSubmit"
      >
        <text v-if="loading" class="i-carbon-loading mr-2 animate-spin" />
        {{ isLogin ? '登 录' : '确认重置' }}
      </button>

      <view class="mt-4 text-center">
        <text
          class="text-14px text-slate-400 transition-colors active:text-slate-600"
          @click="handleSwitchMode"
        >
          {{ isLogin ? '忘记密码？' : '想起密码了，去登录' }}
        </text>
      </view>
    </view>
  </view>
</template>
