import { Text, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { Field, Page } from '@/components/ui'
import { mapUser, backend } from '@/api/backend'
import { saveToken, saveUser } from '@/stores/storage'
import { tapMedium } from '@/utils/feedback'
import { safeMiniappPath, toast } from '@/utils/nav'
import { DEBUG_CODE, DEBUG_PHONE, isAuthDebugEnabled, TEMP_AUTH_DEV_BYPASS } from '@/utils/dev-auth'

export default function PhoneLoginPage() {
  const [redirect, setRedirect] = useState('/pages/home/index')
  const [pcSessionId, setPcSessionId] = useState('')
  const [debugMode, setDebugMode] = useState(TEMP_AUTH_DEV_BYPASS)
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [sent, setSent] = useState(false)
  const [cooldown, setCooldown] = useState(0)

  useLoad((query) => {
    const nextRedirect = query.redirect ? safeMiniappPath(decodeURIComponent(String(query.redirect))) : '/pages/home/index'
    const nextPcSessionId = String(query.pcSessionId || query.pc_session_id || '')
    const nextDebugMode = isAuthDebugEnabled(query.debug)
    if (!nextDebugMode) {
      const pcQuery = nextPcSessionId ? `&pcSessionId=${encodeURIComponent(nextPcSessionId)}` : ''
      Taro.redirectTo({ url: `/pages/auth/login/index?redirect=${encodeURIComponent(nextRedirect)}${pcQuery}` })
      return
    }
    setRedirect(nextRedirect)
    setPcSessionId(nextPcSessionId)
    setDebugMode(nextDebugMode)
    if (nextDebugMode) {
      setPhone(DEBUG_PHONE)
      setCode(DEBUG_CODE)
      setSent(true)
    }
  })

  useEffect(() => {
    if (cooldown <= 0) return
    const timer = setInterval(() => {
      setCooldown((current) => Math.max(0, current - 1))
    }, 1000)
    return () => clearInterval(timer)
  }, [cooldown])

  async function sendCode() {
    tapMedium()
    if (cooldown > 0) return
    if (!/^1\d{10}$/.test(phone)) {
      toast('请输入正确手机号')
      return
    }
    if (debugMode) {
      setSent(true)
      setCode(DEBUG_CODE)
      setCooldown(8)
      toast(`调试验证码：${DEBUG_CODE}`)
      return
    }
    try {
      await backend.sendPhoneCode(phone)
      setSent(true)
      setCooldown(60)
      toast('验证码已发送')
    } catch (error) {
      const retryAfter = Number((error as { retryAfter?: unknown })?.retryAfter || 0)
      if (Number.isFinite(retryAfter) && retryAfter > 0) setCooldown(Math.ceil(retryAfter))
      toast(error instanceof Error ? error.message : '验证码发送失败')
    }
  }

  function routeAfterLogin(user: ReturnType<typeof mapUser>) {
    const pcQuery = pcSessionId ? `&pcSessionId=${encodeURIComponent(pcSessionId)}` : ''
    if (!user.onboardingCompleted) {
      Taro.navigateTo({ url: `/pages/auth/onboarding/index?redirect=${encodeURIComponent(redirect)}${pcQuery}` })
      return
    }
    if (pcSessionId) {
      Taro.navigateTo({ url: `/pages/auth/pc-confirm/index?sessionId=${encodeURIComponent(pcSessionId)}` })
      return
    }
    Taro.reLaunch({ url: redirect.startsWith('/pages/account') ? '/pages/account/index' : safeMiniappPath(redirect) })
  }

  async function submitPhone() {
    tapMedium()
    if (!/^1\d{10}$/.test(phone)) {
      toast('请输入正确手机号')
      return
    }
    if (!code) {
      toast('请输入验证码')
      return
    }
    if (debugMode) {
      saveToken('debug-miniapp-token')
      const user = {
        id: 'debug-user',
        name: '',
        phone,
        authProvider: 'phone' as const,
        onboardingCompleted: false,
        membershipLevel: 0 as const
      }
      saveUser(user)
      const pcQuery = pcSessionId ? `&pcSessionId=${encodeURIComponent(pcSessionId)}` : ''
      Taro.navigateTo({ url: `/pages/auth/onboarding/index?debug=1&redirect=${encodeURIComponent(redirect)}${pcQuery}` })
      return
    }
    try {
      const result = await backend.loginByPhone(phone, code)
      const user = mapUser(result.user)
      saveToken(result.token)
      saveUser(user)
      routeAfterLogin(user)
    } catch (error) {
      toast(error instanceof Error ? error.message : '登录失败')
    }
  }

  return (
    <Page>
      <View className="auth-minimal auth-flow-shell phone-shell">
        <View className="auth-flow-head">
          <Text className="auth-flow-title">手机号登录</Text>
          <Text className="auth-flow-subtitle">手机号验证后即可登录账号</Text>
        </View>
        <View className="phone-form auth-soft-form">
          <Field label="手机号" value={phone} onInput={setPhone} placeholder="请输入手机号" />
          <View className="code-row">
            <View style={{ flex: 1 }}>
              <Field label="验证码" value={code} onInput={setCode} placeholder="请输入验证码" />
            </View>
            <View className={cooldown > 0 ? 'code-btn disabled' : 'code-btn'} onClick={() => void sendCode()}>
              {cooldown > 0 ? `${cooldown}s` : sent ? '重新获取' : '获取验证码'}
            </View>
          </View>
        </View>
        <View className="auth-fixed-actions">
          <View className="auth-flow-primary" onClick={() => void submitPhone()}>
            <Text>登录</Text>
          </View>
          <Text className="auth-flow-secondary-text">使用密码登录</Text>
        </View>
        <Text className="phone-bottom-note">登录即表示同意《用户服务条款》和《隐私政策》</Text>
      </View>
    </Page>
  )
}
