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

export default function OnboardingPage() {
  const [redirect, setRedirect] = useState('/pages/home/index')
  const [pcSessionId, setPcSessionId] = useState('')
  const [debugMode, setDebugMode] = useState(TEMP_AUTH_DEV_BYPASS)
  const [step, setStep] = useState(0)
  const [name, setName] = useState('')
  const [contactPhone, setContactPhone] = useState('')
  const [email, setEmail] = useState('')
  const [organization, setOrganization] = useState('')
  const [industry, setIndustry] = useState('')
  const [city, setCity] = useState('')
  const [title, setTitle] = useState('')
  const [invoiceTitle, setInvoiceTitle] = useState('')
  const [taxNumber, setTaxNumber] = useState('')
  const [invoiceEmail, setInvoiceEmail] = useState('')

  useLoad((query) => {
    setRedirect(query.redirect ? safeMiniappPath(decodeURIComponent(String(query.redirect))) : '/pages/home/index')
    setPcSessionId(String(query.pcSessionId || query.pc_session_id || ''))
    setDebugMode(isAuthDebugEnabled(query.debug))
  })

  useEffect(() => {
    const user = getUser()
    if (!user) {
      if (debugMode) {
        saveToken('debug-miniapp-token')
        saveUser({
          id: 'debug-user',
          name: '',
          phone: DEBUG_PHONE,
          authProvider: 'phone',
          onboardingCompleted: false,
          membershipLevel: 0
        })
        setContactPhone(DEBUG_PHONE)
      }
      return
    }
    setName(user.name || '')
    setContactPhone(user.contactPhone || user.phone || '')
    setEmail(user.email || '')
    setOrganization(user.organization || '')
    setIndustry(user.industry || '')
    setCity(user.city || '')
    setTitle(user.title || '')
    setInvoiceTitle(user.invoiceTitle || '')
    setTaxNumber(user.taxNumber || '')
    setInvoiceEmail(user.invoiceEmail || '')
    const token = getToken()
    if (pcSessionId && token && !debugMode) void backend.preparePcScanLogin(token, pcSessionId).catch(() => undefined)
  }, [debugMode, pcSessionId])

  async function next() {
    if (step === 0 && (!name || !contactPhone)) {
      tapMedium()
      toast('请填写姓名和联系电话')
      return
    }
    if (step < 2) {
      setStep(step + 1)
      return
    }
    const user = getUser()
    if (!user) {
      toast('请先完成登录')
      return
    }
    const token = getToken()
    try {
      const updated = token && !debugMode
        ? mapUser(await backend.completeOnboarding(token, {
            displayName: name,
            contactPhone,
            email,
            organization,
            title,
            city,
            industry,
            invoiceTitle,
            taxNumber,
            invoiceEmail
          }))
        : user
      saveUser({
        ...user,
        ...updated,
        name,
        contactPhone,
        email,
        organization,
        industry,
        city,
        title,
        invoiceTitle,
        taxNumber,
        invoiceEmail,
        onboardingCompleted: true
      })
      tapMedium()
      if (pcSessionId) {
        if (token && !debugMode) await backend.preparePcScanLogin(token, pcSessionId).catch(() => undefined)
        Taro.navigateTo({ url: `/pages/auth/pc-confirm/index?sessionId=${encodeURIComponent(pcSessionId)}` })
        return
      }
      Taro.reLaunch({ url: redirect.startsWith('/pages/account') ? '/pages/account/index' : safeMiniappPath(redirect) })
    } catch (error) {
      toast(error instanceof Error ? error.message : '资料保存失败')
    }
  }

  const stepCopy = [
    '确认基础联系方式，联系电话已同步绑定手机号。',
    '机构信息用于咨询评估和服务推荐。',
    '发票信息可后续修改，也可以先跳过。'
  ]

  return (
    <Page>
      <View className="auth-shell auth-flow-shell onboarding-shell">
        <View className="auth-flow-head onboarding-head">
          <Text className="auth-flow-title">完善资料</Text>
          <Text className="auth-flow-subtitle">{stepCopy[step]}</Text>
        </View>
        <View className="onboarding-card">
          <View key={step} className="form-group auth-soft-form onboarding-form-step">
            {step === 0 && (
              <>
                <Field label="姓名" value={name} onInput={setName} placeholder="请输入真实姓名" />
                <Field label="联系电话" value={contactPhone} onInput={setContactPhone} placeholder="请输入联系电话" />
                <Field label="邮箱（可选）" value={email} onInput={setEmail} placeholder="请输入邮箱" />
              </>
            )}
            {step === 1 && (
              <>
                <Field label="单位名称" value={organization} onInput={setOrganization} placeholder="请输入单位名称" />
                <Field label="所属行业" value={industry} onInput={setIndustry} placeholder="请输入所属行业" />
                <Field label="所在城市" value={city} onInput={setCity} placeholder="请输入所在城市" />
                <Field label="职务" value={title} onInput={setTitle} placeholder="请输入职务" />
              </>
            )}
            {step === 2 && (
              <>
                <Field label="发票抬头" value={invoiceTitle} onInput={setInvoiceTitle} placeholder="请输入发票抬头" />
                <Field label="税号" value={taxNumber} onInput={setTaxNumber} placeholder="请输入税号" />
                <Field label="发票邮箱" value={invoiceEmail} onInput={setInvoiceEmail} placeholder="请输入发票邮箱" />
              </>
            )}
          </View>
        </View>
        <View className="auth-fixed-actions onboarding-fixed-actions">
          <View className="auth-action-row">
            {step > 0 && (
              <View className="auth-flow-secondary" onClick={() => setStep(step - 1)}>
                <Text>上一步</Text>
              </View>
            )}
            <View className={step > 0 ? 'auth-flow-primary flex' : 'auth-flow-primary'} onClick={() => void next()}>
              <Text>{step === 2 ? '完成注册' : '下一步'}</Text>
            </View>
          </View>
        </View>
      </View>
    </Page>
  )
}
