'use client'

import Link from 'next/link'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import type { FormEvent } from 'react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { useApp } from '@/components/providers/AppProvider'
import { backend, type BackendSiteAgreement } from '@/lib/backend'

type RuleKey = 'terms' | 'privacy' | 'purchase' | 'expert'

const agreementIds: Record<RuleKey, string> = {
  terms: 'user-terms',
  privacy: 'privacy-policy',
  purchase: 'purchase-terms',
  expert: 'expert-cooperation-rules',
}

const fallbackRules: Record<RuleKey, { title: string; summary: string; content: string }> = {
  terms: {
    title: '用户服务条款',
    summary: '账号使用、服务开通、平台责任与用户行为规则。',
    content: '用户应保证注册、登录和使用服务时提交的信息真实、准确、完整。平台服务内容以页面展示、订单记录和双方确认信息为准。',
  },
  privacy: {
    title: '隐私政策',
    summary: '个人资料、订单记录、预约信息和服务资料的使用规则。',
    content: '平台会收集账号资料、订单记录、预约记录和用户主动提交的服务资料，用于账号识别、订单履约、发票处理和客服沟通。',
  },
  purchase: {
    title: '线上购买条款',
    summary: '课程、活动、数据服务、智能体、专家预约和会员权益的购买规则。',
    content: '购买人应在支付前确认服务名称、金额、联系人、发票信息和服务内容。个人中心展示的订单与履约记录作为服务进度依据。',
  },
  expert: {
    title: '专家合作规则',
    summary: '专家申请、主页展示、预约履约、收益和合作管理规则。',
    content: '专家应保证提交资料真实准确，并按确认的服务时间和方式履约。平台可根据服务质量、合规要求和合作情况调整展示或暂停合作。',
  },
}

const localSessionKeys = [
  'dlbdi:user',
  'dlbdi:token',
  'dlbdi:staffToken',
  'dlbdi:cart',
  'dlbdi:orders',
  'dlbdi:deliveryTasks',
  'dlbdi:consultingRequests',
]

function emptyDraft() {
  return {
    name: '',
    contactPhone: '',
    email: '',
    organization: '',
    title: '',
    city: '',
    address: '',
    industry: '',
    invoiceTitle: '',
    taxNumber: '',
    invoiceEmail: '',
    wechatId: '',
  }
}

export default function AccountSettingsPage() {
  const router = useRouter()
  const { user, token, logout, refreshAccount } = useApp()
  const [activeRule, setActiveRule] = useState<RuleKey | null>(null)
  const [confirmClear, setConfirmClear] = useState(false)
  const [agreements, setAgreements] = useState<Partial<Record<RuleKey, BackendSiteAgreement>>>({})
  const [draft, setDraft] = useState(emptyDraft)
  const [saving, setSaving] = useState(false)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')

  useEffect(() => {
    void Promise.all((Object.keys(agreementIds) as RuleKey[]).map(async (key) => {
      try {
        return [key, await backend.siteAgreement(agreementIds[key])] as const
      } catch {
        return [key, null] as const
      }
    })).then((entries) => {
      setAgreements(Object.fromEntries(entries.filter(([, value]) => value)) as Partial<Record<RuleKey, BackendSiteAgreement>>)
    })
  }, [])

  useEffect(() => {
    if (!user) return
    setDraft({
      name: user.name || '',
      contactPhone: user.contactPhone || '',
      email: user.email || '',
      organization: user.organization || '',
      title: user.title || '',
      city: user.city || '',
      address: user.address || '',
      industry: user.industry || '',
      invoiceTitle: user.invoiceTitle || '',
      taxNumber: user.taxNumber || '',
      invoiceEmail: user.invoiceEmail || '',
      wechatId: user.wechatId || '',
    })
  }, [user])

  if (!user) return <AccountAuthPrompt message="登录后可管理账号设置。" />

  function ruleDisplay(key: RuleKey) {
    const agreement = agreements[key]
    if (agreement) return {
      title: agreement.title,
      summary: agreement.summary,
      content: agreement.content,
    }
    return fallbackRules[key]
  }

  function setField(field: keyof ReturnType<typeof emptyDraft>, value: string) {
    setDraft((current) => ({ ...current, [field]: value }))
  }

  async function saveProfile(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!token || !user) return
    setSaving(true)
    setMessage('')
    setError('')
    try {
      await backend.updateProfile(token, {
        displayName: draft.name,
        contactPhone: draft.contactPhone,
        email: draft.email,
        organization: draft.organization,
        title: draft.title,
        city: draft.city,
        address: draft.address,
        industry: draft.industry,
        invoiceTitle: draft.invoiceTitle,
        taxNumber: draft.taxNumber,
        invoiceEmail: draft.invoiceEmail,
      })
      if (draft.wechatId !== (user.wechatId || '')) {
        await backend.bindWechat(token, draft.wechatId)
      }
      await refreshAccount()
      setMessage('资料已保存。')
    } catch (err) {
      setError(err instanceof Error ? err.message : '资料保存失败')
    } finally {
      setSaving(false)
    }
  }

  function leaveAccount() {
    logout()
    if (typeof window !== 'undefined') {
      window.location.replace('/')
      return
    }
    router.replace('/')
  }

  function clearLocalSession() {
    logout()
    if (typeof window !== 'undefined') {
      localSessionKeys.forEach((key) => window.localStorage.removeItem(key))
      window.location.replace('/')
      return
    }
    router.replace('/')
  }

  const fields: Array<{ key: keyof ReturnType<typeof emptyDraft>; label: string; placeholder?: string }> = [
    { key: 'name', label: '姓名/展示名', placeholder: '请输入姓名或展示名' },
    { key: 'contactPhone', label: '联系人电话', placeholder: '用于服务联系' },
    { key: 'email', label: '邮箱', placeholder: '用于接收服务资料' },
    { key: 'wechatId', label: '微信 ID', placeholder: '选填' },
    { key: 'organization', label: '所属机构', placeholder: '单位、企业或组织名称' },
    { key: 'title', label: '职务', placeholder: '选填' },
    { key: 'city', label: '所在城市', placeholder: '选填' },
    { key: 'industry', label: '行业方向', placeholder: '选填' },
    { key: 'address', label: '联系地址', placeholder: '选填' },
    { key: 'invoiceTitle', label: '发票抬头', placeholder: '选填' },
    { key: 'taxNumber', label: '纳税人识别号', placeholder: '选填' },
    { key: 'invoiceEmail', label: '发票接收邮箱', placeholder: '选填' },
  ]

  return (
    <div className="mx-auto max-w-[980px]">
      <nav className="mb-5 flex items-center gap-2 text-sm font-bold text-muted">
        <Link href="/account/membership" className="hover:text-brand">我的</Link>
        <span>/</span>
        <span className="text-ink">账号设置</span>
      </nav>

      {(message || error) && (
        <div className={`mb-4 rounded-[4px] px-4 py-3 text-sm font-bold ${error ? 'bg-red-50 text-red-700' : 'bg-green-50 text-green'}`}>
          {error || message}
        </div>
      )}

      <section className="overflow-hidden rounded-[4px] border border-line bg-white shadow-[0_12px_34px_rgba(15,23,42,0.05)]">
        <div className="px-6 py-7 md:px-8">
          <h1 className="text-3xl font-extrabold text-ink">账号设置</h1>
          <p className="mt-3 max-w-[680px] text-sm leading-7 text-muted">
            维护服务联系、发票和常用资料。会员状态与通行证在“我的”页面查看。
          </p>
        </div>

        <form onSubmit={saveProfile} className="border-t border-line px-6 py-6 md:px-8">
          <div className="mb-5 text-sm font-extrabold text-brand">常用资料</div>
          <div className="grid gap-4 md:grid-cols-2">
            {fields.map((field) => (
              <label key={field.key} className={field.key === 'address' ? 'md:col-span-2' : ''}>
                <span className="mb-2 block text-sm font-extrabold text-ink">{field.label}</span>
                <input
                  value={draft[field.key]}
                  onChange={(event) => setField(field.key, event.target.value)}
                  placeholder={field.placeholder}
                  className="h-11 w-full rounded-[4px] border border-line px-3 text-sm font-bold text-ink outline-none focus:border-brand"
                />
              </label>
            ))}
          </div>
          <div className="mt-6 flex justify-end">
            <button disabled={saving} className="h-10 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white hover:bg-brand-dark disabled:opacity-60">
              {saving ? '保存中...' : '保存资料'}
            </button>
          </div>
        </form>

        <div className="border-t border-line px-6 py-4 md:px-8">
          <h2 className="text-sm font-extrabold text-brand">协议与规则</h2>
        </div>
        <div className="divide-y divide-line">
          {(Object.keys(fallbackRules) as RuleKey[]).map((key) => {
            const item = ruleDisplay(key)
            return (
              <button
                key={key}
                type="button"
                onClick={() => setActiveRule(key)}
                className="grid w-full gap-3 px-6 py-4 text-left transition-colors hover:bg-[#f8fbff] md:grid-cols-[1fr_auto] md:items-center md:px-8"
              >
                <span>
                  <span className="block text-base font-extrabold text-ink">{item.title}</span>
                  <span className="mt-1 block text-sm leading-6 text-muted">{item.summary}</span>
                </span>
                <span className="text-sm font-extrabold text-brand">查看</span>
              </button>
            )
          })}
        </div>

        <div className="border-t border-line px-6 py-4 md:px-8">
          <h2 className="text-sm font-extrabold text-brand">账号操作</h2>
        </div>
        <div className="divide-y divide-line">
          <div className="grid gap-4 px-6 py-4 md:grid-cols-[1fr_auto] md:items-center md:px-8">
            <div>
              <div className="text-base font-extrabold text-ink">退出登录</div>
              <p className="mt-1 text-sm leading-6 text-muted">退出当前账号，后续可重新用手机号或微信登录。</p>
            </div>
            <button type="button" onClick={leaveAccount} className="h-10 rounded-[4px] border border-line bg-white px-5 text-sm font-extrabold text-text-body hover:border-brand hover:text-brand">
              退出登录
            </button>
          </div>

          <div className="grid gap-4 px-6 py-4 md:grid-cols-[1fr_auto] md:items-center md:px-8">
            <div>
              <div className="text-base font-extrabold text-ink">清除本机登录状态</div>
              <p className="mt-1 text-sm leading-6 text-muted">只清除当前浏览器里的登录、购物车和旧缓存记录，不会删除服务端账号或订单。</p>
            </div>
            <button type="button" onClick={() => setConfirmClear(true)} className="h-10 rounded-[4px] border border-red-200 bg-white px-5 text-sm font-extrabold text-red-600 hover:bg-red-50">
              清除本机状态
            </button>
          </div>
        </div>
      </section>

      {activeRule && (
        <div className="fixed inset-0 z-[80] grid place-items-center bg-ink/36 px-6">
          <div className="w-full max-w-[720px] rounded-[4px] bg-white p-6 shadow-[0_24px_80px_rgba(15,23,42,0.22)]">
            <div className="flex items-start justify-between gap-4 border-b border-line pb-4">
              <div>
                <h2 className="text-2xl font-extrabold text-ink">{ruleDisplay(activeRule).title}</h2>
                <p className="mt-2 text-sm text-muted">{ruleDisplay(activeRule).summary}</p>
              </div>
              <button type="button" onClick={() => setActiveRule(null)} className="text-sm font-extrabold text-muted hover:text-brand">关闭</button>
            </div>
            <div className="mt-5 max-h-[56vh] overflow-y-auto whitespace-pre-line pr-2 text-sm leading-7 text-muted">
              {ruleDisplay(activeRule).content}
            </div>
            <button type="button" onClick={() => setActiveRule(null)} className="mt-6 h-10 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">我已阅读</button>
          </div>
        </div>
      )}

      {confirmClear && (
        <div className="fixed inset-0 z-[80] grid place-items-center bg-ink/36 px-6">
          <div className="w-full max-w-[520px] rounded-[4px] bg-white p-6 shadow-[0_24px_80px_rgba(15,23,42,0.22)]">
            <h2 className="text-2xl font-extrabold text-ink">清除本机登录状态？</h2>
            <p className="mt-4 text-sm leading-7 text-muted">
              这只会清除当前浏览器保存的登录状态、购物车和旧缓存记录，不会删除账号、订单、会员、预约或服务记录。
            </p>
            <div className="mt-7 flex justify-end gap-3">
              <button type="button" onClick={() => setConfirmClear(false)} className="h-10 rounded-[4px] bg-brand px-5 text-sm font-extrabold text-white">
                取消
              </button>
              <button type="button" onClick={clearLocalSession} className="h-10 rounded-[4px] border border-red-200 bg-white px-5 text-sm font-extrabold text-red-600 hover:bg-red-50">
                确认清除
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
