import { ref } from 'vue'
import { api } from '../api/client'

export function useVerification(toast: { success: (msg: string) => void; apiError: (e: any, msg: string) => void; warning: (msg: string) => void }) {
  const emailCodeSent = ref(false)
  const phoneCodeSent = ref(false)
  const emailVerified = ref(false)
  const phoneVerified = ref(false)
  const sendingEmail = ref(false)
  const sendingPhone = ref(false)
  const emailCountdown = ref(0)
  const phoneCountdown = ref(0)

  let emailTimer: ReturnType<typeof setInterval> | null = null
  let phoneTimer: ReturnType<typeof setInterval> | null = null

  function startCountdown(type: 'email' | 'phone') {
    if (type === 'email') {
      emailCountdown.value = 60
      if (emailTimer) clearInterval(emailTimer)
      emailTimer = setInterval(() => {
        if (emailCountdown.value > 0) emailCountdown.value--
        else if (emailTimer) { clearInterval(emailTimer); emailTimer = null }
      }, 1000)
    } else {
      phoneCountdown.value = 60
      if (phoneTimer) clearInterval(phoneTimer)
      phoneTimer = setInterval(() => {
        if (phoneCountdown.value > 0) phoneCountdown.value--
        else if (phoneTimer) { clearInterval(phoneTimer); phoneTimer = null }
      }, 1000)
    }
  }

  async function sendEmailCode() {
    sendingEmail.value = true
    try {
      await api.post('/auth/verification/send-email', { email: '' })
      emailCodeSent.value = true
      startCountdown('email')
      toast.success('验证码已发送到您的邮箱')
    } catch (e: any) {
      toast.apiError(e, '发送失败')
    } finally {
      sendingEmail.value = false
    }
  }

  async function verifyEmail(code: string) {
    try {
      await api.post('/auth/verification/verify-email', { code })
      emailVerified.value = true
      toast.success('邮箱已通过验证')
    } catch (e: any) {
      toast.apiError(e, '验证失败')
      throw e
    }
  }

  async function sendPhoneCode(phone: string) {
    sendingPhone.value = true
    try {
      await api.post('/auth/verification/send-phone', { phone })
      phoneCodeSent.value = true
      startCountdown('phone')
      toast.success('验证码已发送到您的手机')
    } catch (e: any) {
      toast.apiError(e, '发送失败')
    } finally {
      sendingPhone.value = false
    }
  }

  async function verifyPhone(code: string) {
    try {
      await api.post('/auth/verification/verify-phone', { code })
      phoneVerified.value = true
      toast.success('手机已通过验证')
    } catch (e: any) {
      toast.apiError(e, '验证失败')
      throw e
    }
  }

  return {
    emailCodeSent, phoneCodeSent, emailVerified, phoneVerified,
    sendingEmail, sendingPhone, emailCountdown, phoneCountdown,
    sendEmailCode, verifyEmail, sendPhoneCode, verifyPhone,
  }
}
