import { RichText, ScrollView, Text, View } from '@tarojs/components'
import Taro, { useDidHide, useDidShow, useUnload } from '@tarojs/taro'
import { useEffect, useMemo, useRef, useState } from 'react'
import { backend, mapUser, type BackendSiteAgreement } from '@/api/backend'
import { BottomDrawer, Field, Page } from '@/components/ui'
import { clearStaffToken, getToken, getUser, saveCart, saveDeliveryTasks, saveOrders, saveToken, saveUser } from '@/stores/storage'
import type { UserProfile } from '@/types'
import { tapLight, tapMedium } from '@/utils/feedback'

type Draft = {
  name: string
  contactPhone: string
  email: string
  organization: string
  title: string
  industry: string
  city: string
  address: string
  invoiceTitle: string
  taxNumber: string
  invoiceEmail: string
}

type SettingsView = 'menu' | 'profile' | 'agreements'

const agreementRows = [
  { id: 'user-terms', title: '用户服务条款', desc: '服务边界、用户责任与平台规则' },
  { id: 'privacy-policy', title: '隐私政策', desc: '个人信息收集、使用与保护' },
  { id: 'purchase-terms', title: '线上购买条款', desc: '支付、订单、开票与售后说明' },
  { id: 'expert-cooperation-rules', title: '专家合作规则', desc: '预约咨询与专家服务边界' }
]

function draftFromUser(user: UserProfile | null): Draft {
  return {
    name: user?.name || '',
    contactPhone: user?.contactPhone || user?.phone || '',
    email: user?.email || '',
    organization: user?.organization || '',
    title: user?.title || '',
    industry: user?.industry || '',
    city: user?.city || '',
    address: user?.address || '',
    invoiceTitle: user?.invoiceTitle || user?.organization || '',
    taxNumber: user?.taxNumber || '',
    invoiceEmail: user?.invoiceEmail || user?.email || ''
  }
}

export default function SettingsPage() {
  const [user, setUser] = useState<UserProfile | null>(() => getUser())
  const [draft, setDraft] = useState<Draft>(() => draftFromUser(getUser()))
  const [view, setView] = useState<SettingsView>('menu')
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState('')
  const [agreement, setAgreement] = useState<BackendSiteAgreement | null>(null)
  const [agreementTitle, setAgreementTitle] = useState('')
  const [agreementLoading, setAgreementLoading] = useState(false)
  const userRef = useRef(user)
  const draftRef = useRef(draft)
  const viewRef = useRef(view)
  const savingRef = useRef(false)

  useEffect(() => { userRef.current = user }, [user])
  useEffect(() => { draftRef.current = draft }, [draft])
  useEffect(() => { viewRef.current = view }, [view])

  useDidShow(() => {
    const token = getToken()
    if (!token) {
      const local = getUser()
      setUser(local)
      setDraft(draftFromUser(local))
      return
    }
    void backend.me(token)
      .then((remote) => {
        if (viewRef.current === 'profile' && draftChanged()) return
        const next = mapUser(remote)
        saveUser(next)
        setUser(next)
        setDraft(draftFromUser(next))
      })
      .catch(() => {
        if (viewRef.current === 'profile' && draftChanged()) return
        const local = getUser()
        setUser(local)
        setDraft(draftFromUser(local))
      })
  })

  useDidHide(() => {
    if (viewRef.current === 'profile') void saveProfile({ silent: true, navigateIfLoggedOut: false })
  })

  useUnload(() => {
    if (viewRef.current === 'profile') void saveProfile({ silent: true, navigateIfLoggedOut: false })
  })

  function draftChanged(nextDraft = draftRef.current, nextUser = userRef.current) {
    const original = draftFromUser(nextUser)
    return Object.keys(nextDraft).some((key) => nextDraft[key as keyof Draft] !== original[key as keyof Draft])
  }

  const profileChanged = useMemo(() => draftChanged(draft, user), [draft, user])
  const profileSubtle = saving ? '正在自动保存资料...' : message || (profileChanged ? '已有修改，返回账号设置时会自动保存。' : '姓名、联系方式、机构信息与开票资料。')

  function setField(key: keyof Draft, value: string) {
    setDraft((current) => ({ ...current, [key]: value }))
    setMessage('')
  }

  async function saveProfile(options: { silent?: boolean; navigateIfLoggedOut?: boolean } = {}) {
    const silent = Boolean(options.silent)
    const navigateIfLoggedOut = options.navigateIfLoggedOut !== false
    const currentDraft = draftRef.current
    const currentUser = userRef.current
    if (!draftChanged(currentDraft, currentUser) || savingRef.current) return true
    const token = getToken()
    if (!token) {
      if (navigateIfLoggedOut) Taro.navigateTo({ url: '/pages/auth/login/index?redirect=/pages/account/settings/index' })
      return false
    }
    if (!currentDraft.name.trim() || !currentDraft.contactPhone.trim()) {
      Taro.showToast({ title: '请填写姓名和联系电话', icon: 'none' })
      return false
    }
    savingRef.current = true
    setSaving(true)
    if (!silent) setMessage('')
    try {
      const remote = await backend.updateProfile(token, {
        displayName: currentDraft.name.trim(),
        contactPhone: currentDraft.contactPhone.trim(),
        email: currentDraft.email.trim(),
        organization: currentDraft.organization.trim(),
        title: currentDraft.title.trim(),
        industry: currentDraft.industry.trim(),
        city: currentDraft.city.trim(),
        address: currentDraft.address.trim(),
        invoiceTitle: currentDraft.invoiceTitle.trim(),
        taxNumber: currentDraft.taxNumber.trim(),
        invoiceEmail: currentDraft.invoiceEmail.trim()
      })
      const next = mapUser(remote)
      saveUser(next)
      setUser(next)
      setDraft(draftFromUser(next))
      tapMedium()
      setMessage(silent ? '已自动保存' : '资料已保存')
      return true
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '资料保存失败', icon: 'none' })
      return false
    } finally {
      savingRef.current = false
      setSaving(false)
    }
  }

  async function leaveProfile() {
    const ok = await saveProfile({ silent: true, navigateIfLoggedOut: false })
    if (ok) setView('menu')
  }

  async function openAgreement(id: string, fallbackTitle: string) {
    tapLight()
    setAgreementTitle(fallbackTitle)
    setAgreement(null)
    setAgreementLoading(true)
    try {
      setAgreement(await backend.siteAgreement(id))
    } catch {
      setAgreement({
        id,
        title: fallbackTitle,
        summary: '内容待维护',
        content: '<p>该协议内容暂未在管理端发布。</p>',
        status: 'draft',
        updatedBy: '',
        createdAt: '',
        updatedAt: ''
      })
    } finally {
      setAgreementLoading(false)
    }
  }

  function clearLocalState() {
    saveUser(null)
    saveToken('')
    saveCart([])
    saveOrders([])
    saveDeliveryTasks([])
    clearStaffToken()
  }

  async function clearCache() {
    tapLight()
    const confirm = await Taro.showModal({
      title: '清理缓存',
      content: '将清理本机订单、服务进度和 AI 草稿缓存；不会退出登录，也不会清空购物车。',
      confirmText: '清理',
      cancelText: '取消'
    })
    if (!confirm.confirm) return
    try {
      saveOrders([])
      saveDeliveryTasks([])
      const info = Taro.getStorageInfoSync()
      ;(info.keys || []).forEach((key) => {
        if (key.startsWith('dlbdi-mini:ai-lead-draft:')) Taro.removeStorageSync(key)
      })
      tapMedium()
      Taro.showToast({ title: '缓存已清理', icon: 'success' })
    } catch {
      Taro.showToast({ title: '清理失败，请稍后再试', icon: 'none' })
    }
  }

  async function logout() {
    tapLight()
    const confirm = await Taro.showModal({ title: '退出登录', content: '退出后需要重新登录才能查看订单和服务进度。', confirmText: '退出' })
    if (!confirm.confirm) return
    clearLocalState()
    Taro.reLaunch({ url: '/pages/home/index' })
  }

  async function closeAccount() {
    tapLight()
    const token = getToken()
    if (!token) {
      clearLocalState()
      Taro.reLaunch({ url: '/pages/home/index' })
      return
    }
    const confirm = await Taro.showModal({
      title: '注销账号',
      content: '注销后将清空账号手机号、微信号、单位、邮箱和发票信息，并退出登录。历史订单和服务记录会保留用于履约和财务追溯。',
      confirmText: '确认注销',
      cancelText: '再想想'
    })
    if (!confirm.confirm) return
    try {
      await backend.closeAccount(token, { reason: '用户在小程序账号设置中主动注销' })
      clearLocalState()
      Taro.showToast({ title: '账号已注销', icon: 'success' })
      setTimeout(() => Taro.reLaunch({ url: '/pages/home/index' }), 500)
    } catch (error) {
      Taro.showToast({ title: error instanceof Error ? error.message : '注销失败', icon: 'none' })
    }
  }

  function MenuRow({ title, desc, danger, onClick }: { title: string; desc: string; danger?: boolean; onClick: () => void }) {
    return (
      <View className={danger ? 'settings-row clean danger' : 'settings-row clean'} onClick={onClick}>
        <View style={{ flex: 1, minWidth: 0 }}>
          <Text className="account-menu-title">{title}</Text>
          <Text className="account-menu-sub">{desc}</Text>
        </View>
        <Text className="arrow">›</Text>
      </View>
    )
  }

  function renderMenu() {
    return (
      <>
        <View className="settings-section">
          <Text className="settings-title">账号设置</Text>
          <View className="settings-list">
            <MenuRow title="更改信息" desc="姓名、联系方式、单位、开票资料" onClick={() => { setMessage(''); setView('profile') }} />
            <MenuRow title="协议与规则" desc="服务条款、隐私政策、购买条款、专家规则" onClick={() => setView('agreements')} />
            <MenuRow title="AI 助手" desc="管理 AI 可读取和可辅助的范围" onClick={() => Taro.navigateTo({ url: '/pages/account/ai-settings/index' })} />
            <MenuRow title="清理缓存" desc="清理本机缓存，保留登录状态和购物车" onClick={clearCache} />
            <MenuRow title="注销账号" desc="清空账号资料并退出登录，历史履约记录保留" danger onClick={closeAccount} />
          </View>
        </View>

        <View className="settings-logout-wrap">
          <View className="settings-logout-btn" onClick={logout}><Text>退出登录</Text></View>
        </View>
      </>
    )
  }

  function renderProfileEditor() {
    return (
      <View className="settings-subpage-shell settings-profile-shell">
        <View className="settings-back-row" onClick={() => void leaveProfile()}>
          <Text>‹ 返回</Text>
        </View>

        <View className="settings-profile-head">
          <Text className="settings-profile-title">更改信息</Text>
          <Text className="settings-profile-desc">{profileSubtle}</Text>
        </View>

        <View className="settings-profile-panel">
          <ScrollView scrollY className="settings-profile-scroll">
            <View className="settings-profile-content">
              <View className="form-group auth-soft-form onboarding-form-step">
                <Text className="settings-profile-group-title">基础资料</Text>
                <Field label="姓名" value={draft.name} onInput={(value) => setField('name', value)} placeholder="请输入真实姓名" />
                <Field label="联系电话" value={draft.contactPhone} onInput={(value) => setField('contactPhone', value)} placeholder="请输入联系电话" />
                <Field label="邮箱（可选）" value={draft.email} onInput={(value) => setField('email', value)} placeholder="用于接收服务通知" />

                <Text className="settings-profile-group-title gap">机构信息</Text>
                <Field label="单位名称" value={draft.organization} onInput={(value) => setField('organization', value)} placeholder="请输入单位名称" />
                <Field label="所属行业" value={draft.industry} onInput={(value) => setField('industry', value)} placeholder="请输入所属行业" />
                <Field label="所在城市" value={draft.city} onInput={(value) => setField('city', value)} placeholder="请输入所在城市" />
                <Field label="职务" value={draft.title} onInput={(value) => setField('title', value)} placeholder="请输入职务" />
                <Field label="联系地址（可选）" value={draft.address} onInput={(value) => setField('address', value)} placeholder="用于线下服务联系" />

                <Text className="settings-profile-group-title gap">开票信息</Text>
                <Field label="发票抬头" value={draft.invoiceTitle} onInput={(value) => setField('invoiceTitle', value)} placeholder="单位或个人名称" />
                <Field label="税号" value={draft.taxNumber} onInput={(value) => setField('taxNumber', value)} placeholder="企业开票必填" />
                <Field label="发票邮箱" value={draft.invoiceEmail} onInput={(value) => setField('invoiceEmail', value)} placeholder="电子发票接收邮箱" />
              </View>
            </View>
          </ScrollView>
        </View>
      </View>
    )
  }

  function renderAgreements() {
    return (
      <View className="settings-subpage-shell">
        <View className="settings-back-row" onClick={() => setView('menu')}>
          <Text>‹ 返回</Text>
        </View>
        <View className="settings-section">
          <View className="settings-list">
            {agreementRows.map((item) => (
              <View key={item.id} className="settings-row clean" onClick={() => openAgreement(item.id, item.title)}>
                <View style={{ flex: 1, minWidth: 0 }}>
                  <Text className="account-menu-title">{item.title}</Text>
                  <Text className="account-menu-sub">{item.desc}</Text>
                </View>
                <Text className="arrow">›</Text>
              </View>
            ))}
          </View>
        </View>
      </View>
    )
  }

  return (
    <Page title={view === 'menu' ? '账号设置' : undefined} subtle={view === 'menu' ? '更改信息、协议规则、AI 助手和账号操作' : undefined}>
      {view === 'menu' ? renderMenu() : null}
      {view === 'profile' ? renderProfileEditor() : null}
      {view === 'agreements' ? renderAgreements() : null}

      {agreementTitle ? (
        <BottomDrawer title={agreement?.title || agreementTitle} onClose={() => setAgreementTitle('')} className="agreement-drawer">
          <ScrollView scrollY className="agreement-scroll">
            {agreementLoading ? <Text className="agreement-text">正在加载协议内容...</Text> : null}
            {agreement?.summary ? <Text className="agreement-summary">{agreement.summary}</Text> : null}
            {agreement?.content ? <RichText className="agreement-richtext" nodes={agreement.content} /> : null}
          </ScrollView>
        </BottomDrawer>
      ) : null}
    </Page>
  )
}
