import { Text, View } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useEffect, useState } from 'react'
import { AgreementModal, Field, Page } from '@/components/ui'
import { backend, mapUser } 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 BindPhonePage() {
  const [redirect, setRedirect] = useState('/pages/home/index')
  const [miniappSessionToken, setMiniappSessionToken] = useState('')
  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)
  const [agreed, setAgreed] = useState(false)
  const [agreementTitle, setAgreementTitle] = useState('')

  useLoad((query) => {
    setRedirect(query.redirect ? safeMiniappPath(decodeURIComponent(String(query.redirect))) : '/pages/home/index')
    setMiniappSessionToken(String(query.miniappSessionToken || query.miniapp_session_token || ''))
    setPcSessionId(String(query.pcSessionId || query.pc_session_id || ''))
    const nextDebugMode = isAuthDebugEnabled(query.debug)
    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 (!debugMode && !agreed) {
      toast('请先阅读并同意用户协议')
      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 : '验证码发送失败')
    }
  }

  async function submitPhone() {
    tapMedium()
    if (!debugMode && !agreed) {
      toast('请先阅读并同意用户协议')
      return
    }
    if (!/^1\d{10}$/.test(phone)) {
      toast('请输入正确手机号')
      return
    }
    if (!code) {
      toast('请输入验证码')
      return
    }
    if (debugMode) {
      saveToken('debug-miniapp-token')
      saveUser({
        id: 'debug-user',
        name: '',
        phone,
        authProvider: 'phone',
        onboardingCompleted: false,
        membershipLevel: 0
      })
      const pcQuery = pcSessionId ? `&pcSessionId=${encodeURIComponent(pcSessionId)}` : ''
      Taro.navigateTo({ url: `/pages/auth/onboarding/index?debug=1&redirect=${encodeURIComponent(redirect)}${pcQuery}` })
      return
    }
    if (!miniappSessionToken) {
      toast('微信登录会话已失效，请重新登录')
      const pcQuery = pcSessionId ? `&pcSessionId=${encodeURIComponent(pcSessionId)}` : ''
      Taro.navigateTo({ url: `/pages/auth/login/index?redirect=${encodeURIComponent(redirect)}${pcQuery}` })
      return
    }
    try {
      const result = await backend.bindMiniappPhone(miniappSessionToken, phone, code)
      saveToken(result.token)
      saveUser(mapUser(result.user))
      const finalPcSessionId = result.pcSessionId || pcSessionId
      const pcQuery = finalPcSessionId ? `&pcSessionId=${encodeURIComponent(finalPcSessionId)}` : ''
      if (result.nextAction === 'complete_profile') {
        Taro.navigateTo({ url: `/pages/auth/onboarding/index?redirect=${encodeURIComponent(redirect)}${pcQuery}` })
        return
      }
      if (finalPcSessionId) {
        Taro.navigateTo({ url: `/pages/auth/pc-confirm/index?sessionId=${encodeURIComponent(finalPcSessionId)}` })
        return
      }
      Taro.reLaunch({ url: redirect.startsWith('/pages/account') ? '/pages/account/index' : safeMiniappPath(redirect) })
    } catch (error) {
      toast(error instanceof Error ? error.message : '绑定失败')
    }
  }

  function openAgreement(title: string, event: { stopPropagation: () => void }) {
    event.stopPropagation()
    tapMedium()
    setAgreementTitle(title)
  }

  return (
    <Page>
      <View className="auth-minimal auth-flow-shell phone-shell bind-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="login-agreement auth-agreement" onClick={() => setAgreed(!agreed)}>
          <View className={agreed ? 'agree-box checked' : 'agree-box'}>{agreed && <Text>✓</Text>}</View>
          <View className="agree-text">
            <Text>我已阅读并同意</Text>
            <Text className="agree-link" onClick={(event) => openAgreement('用户服务条款', event)}>《用户服务条款》</Text>
            <Text className="agree-link" onClick={(event) => openAgreement('隐私政策', event)}>《隐私政策》</Text>
          </View>
        </View>
        {agreementTitle && (
          <AgreementModal
            title={agreementTitle}
            onClose={() => setAgreementTitle('')}
          />
        )}
        <View className="auth-fixed-actions">
          <View className={(debugMode || agreed) ? 'auth-flow-primary' : 'auth-flow-primary disabled'} onClick={() => void submitPhone()}>
            <Text>继续</Text>
          </View>
        </View>
      </View>
    </Page>
  )
}
