'use client'

import { useEffect, useState } from 'react'
import Link from 'next/link'
import { Crown, QrCode, Settings } from 'lucide-react'
import { AccountAuthPrompt } from '@/components/account/AccountAuthPrompt'
import { useApp } from '@/components/providers/AppProvider'
import { PassportQrCode } from '@/components/shared/PassportQrCode'
import { backend, type BackendAccountMembership } from '@/lib/backend'

const levelLabel = ['注册用户', '初级会员', '高级会员']

export default function AccountMembershipPage() {
  const { user, token } = useApp()
  const [membership, setMembership] = useState<BackendAccountMembership | null>(null)
  const [membershipLoading, setMembershipLoading] = useState(true)
  const [message, setMessage] = useState('')
  const [error, setError] = useState('')

  useEffect(() => {
    if (!token) {
      setMembership(null)
      setMembershipLoading(false)
      return
    }
    let mounted = true
    setMembershipLoading(true)
    void backend.accountMembership(token)
      .then((result) => {
        if (mounted) {
          setMembership(result)
          setError('')
        }
      })
      .catch((err) => {
        if (mounted) {
          setMembership(null)
          setError(err instanceof Error ? `会员状态加载失败：${err.message}` : '会员状态加载失败，请刷新页面重试。')
        }
      })
      .finally(() => {
        if (mounted) setMembershipLoading(false)
      })
    return () => {
      mounted = false
    }
  }, [token])

  if (!user) return <AccountAuthPrompt message="登录后可查看我的资料。" />

  const level = membership?.level === 'senior' ? 2 : membership?.level === 'junior' ? 1 : 0
  const passId = user.passportNo || '待生成'
  const status = membership?.status || 'registered'
  const statusText = status === 'expired'
    ? '已到期'
    : status === 'expiring'
      ? '即将到期'
      : status === 'active'
        ? '有效'
        : '未开通'
  const statusTone = status === 'expired'
    ? 'text-red-700'
    : status === 'expiring'
      ? 'text-amber-700'
      : status === 'active'
        ? 'text-green'
        : 'text-muted'
  const avatarTone = level === 2
    ? {
        ring: 'ring-[#d2ad39]/55',
        badge: 'bg-[#d2ad39] text-white',
        body: 'bg-[#9b7b26]',
      }
    : level === 1
      ? {
          ring: 'ring-brand/25',
          badge: 'bg-brand-light text-brand',
          body: 'bg-brand',
        }
      : {
          ring: 'ring-transparent',
          badge: '',
          body: 'bg-[#56657a]',
        }
  const profileItems = [
    ['登录手机号', user.phone || '-'],
    ['微信 ID', user.wechatId || '-'],
    ['联系人电话', user.contactPhone || '未填写'],
    ['邮箱', user.email || '未填写'],
    ['所属机构', user.organization || '未填写'],
    ['职务', user.title || '未填写'],
    ['所在城市', user.city || '未填写'],
    ['联系地址', user.address || '未填写'],
    ['行业方向', user.industry || '未填写'],
    ['发票抬头', user.invoiceTitle || '未填写'],
    ['纳税人识别号', user.taxNumber || '未填写'],
    ['发票接收邮箱', user.invoiceEmail || '未填写'],
    ['通行证编号', passId],
  ]
  const customerManager = membership?.serviceAssignments?.find((item) => item.assignmentType === 'customer_manager')
  const benefitLabels = new Map((membership?.benefits || []).map((item) => [item.code, item.displayLabel || item.label || item.code]))

  async function requestCancel() {
    if (!token || !membership?.subscription) return
    try {
      setMessage('')
      setError('')
      await backend.cancelAccountMembership(token, membership.subscription.id, { reason: '用户提交到期不续申请' })
      const refreshed = await backend.accountMembership(token)
      setMembership(refreshed)
      setMessage('已提交取消申请，后台会按到期不续或人工处理流程跟进。')
    } catch (err) {
      setError(err instanceof Error ? err.message : '取消申请提交失败')
    }
  }

  return (
    <div className="mx-auto max-w-[900px]">
      {(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="grid gap-0 md:grid-cols-[1fr_260px]">
          <div className="p-7">
            <div className="flex flex-col gap-5 sm:flex-row sm:items-center">
              <div className="relative shrink-0 pb-5">
                <div className={`relative h-24 w-24 overflow-hidden rounded-full bg-[radial-gradient(circle_at_50%_30%,#ffe8d6_0_18%,#d7a07c_19%_30%,#eef3f8_31%_100%)] shadow-[0_10px_26px_rgba(15,23,42,0.12)] ring-4 ${avatarTone.ring}`}>
                  <div className="absolute left-1/2 top-[18px] h-9 w-9 -translate-x-1/2 rounded-full bg-[#f2c3a5]" />
                  <div className={`absolute left-1/2 top-[48px] h-16 w-20 -translate-x-1/2 rounded-t-full ${avatarTone.body}`} />
                  <div className="absolute left-[31px] top-[29px] h-1.5 w-1.5 rounded-full bg-ink/70" />
                  <div className="absolute right-[31px] top-[29px] h-1.5 w-1.5 rounded-full bg-ink/70" />
                  <div className="absolute left-1/2 top-[39px] h-1 w-5 -translate-x-1/2 rounded-full bg-[#b97c63]" />
                </div>
                {level > 0 && (
                  <div className={`absolute bottom-0 left-1/2 grid h-8 w-8 -translate-x-1/2 place-items-center rounded-full border-2 border-white shadow-[0_8px_18px_rgba(15,23,42,0.16)] ${avatarTone.badge}`}>
                    <Crown className="h-4 w-4" />
                  </div>
                )}
              </div>
              <div>
                <div className="flex flex-wrap items-center gap-3">
                  <h1 className="text-3xl font-extrabold leading-tight text-ink">{user.name}</h1>
                </div>
              </div>
            </div>

            <div className="mt-8 border-y border-line">
              <div className="grid gap-3 border-b border-line py-3 text-sm sm:grid-cols-[120px_1fr]">
                <div className="font-bold text-muted">会员状态</div>
                <div>
                  <div className={`text-sm font-extrabold ${error && !membership ? 'text-red-700' : statusTone}`}>
                    {membershipLoading ? '会员状态加载中...' : error && !membership ? '会员状态加载失败' : `${levelLabel[level]} · ${statusText}`}
                  </div>
                  {membership?.expiresAt && <div className="mt-1 text-xs font-bold text-muted">有效期至 {new Date(membership.expiresAt).toLocaleString('zh-CN')} · 剩余 {membership.daysLeft ?? '-'} 天</div>}
                  {membership?.subscription?.cancelRequestedAt && <div className="mt-1 text-xs font-bold text-amber-700">已提交取消申请：{new Date(membership.subscription.cancelRequestedAt).toLocaleString('zh-CN')}</div>}
                  {!membership && !membershipLoading && !error && <div className="mt-1 text-xs font-bold text-muted">当前为注册用户，可开通会员方案。</div>}
                </div>
              </div>
              {customerManager && (
                <div className="grid gap-3 border-b border-line py-3 text-sm sm:grid-cols-[120px_1fr]">
                  <div className="font-bold text-muted">客户经理</div>
                  <div className="font-extrabold text-ink">{customerManager.assignedStaffName || customerManager.assignedStaffPhone || '已分配'}</div>
                </div>
              )}
              {(membership?.quotas || []).length > 0 && (
                <div className="grid gap-3 border-b border-line py-3 text-sm sm:grid-cols-[120px_1fr]">
                  <div className="font-bold text-muted">会员额度</div>
                  <div className="space-y-1">
                    {membership?.quotas?.map((item) => (
                      <div key={item.id} className="font-extrabold text-ink">{benefitLabels.get(item.benefitCode) || item.benefitCode}：剩余 {item.quotaRemaining}/{item.quotaTotal}</div>
                    ))}
                  </div>
                </div>
              )}
              {(membership?.contentDeliveries || []).length > 0 && (
                <div className="grid gap-3 border-b border-line py-3 text-sm sm:grid-cols-[120px_1fr]">
                  <div className="font-bold text-muted">会员报告</div>
                  <div className="space-y-1">
                    {membership?.contentDeliveries?.slice(0, 3).map((item) => (
                      item.href || item.fileId ? (
                        <a key={item.id} href={item.href || `/api/files/${item.fileId}`} className="block font-extrabold text-brand hover:text-brand-dark">
                          {item.periodKey} · {item.title}
                        </a>
                      ) : (
                        <div key={item.id} className="font-extrabold text-ink">{item.periodKey} · {item.title}</div>
                      )
                    ))}
                  </div>
                </div>
              )}
              {(membership?.benefits || []).length > 0 && (
                <div className="grid gap-3 border-b border-line py-3 text-sm sm:grid-cols-[120px_1fr]">
                  <div className="font-bold text-muted">有效权益</div>
                  <div className="flex flex-wrap gap-2">
                    {membership?.benefits?.slice(0, 8).map((item) => (
                      <span key={item.code} className="rounded-[4px] bg-bg px-2 py-1 text-xs font-extrabold text-muted">{item.displayLabel || item.label}</span>
                    ))}
                  </div>
                </div>
              )}
              {profileItems.map(([label, value]) => (
                <div key={label} className="grid gap-3 border-b border-line py-3 text-sm last:border-b-0 sm:grid-cols-[120px_1fr]">
                  <div className="font-bold text-muted">{label}</div>
                  <div className="font-extrabold text-ink">{value as string}</div>
                </div>
              ))}
            </div>

            <div className="mt-6 flex flex-wrap gap-3">
              <Link href="/account/settings" className="inline-flex h-9 items-center gap-2 rounded-[4px] bg-brand px-4 text-sm font-bold text-white hover:bg-brand-dark">
                <Settings className="h-4 w-4" />
                编辑资料
              </Link>
              <Link href="/membership" className="inline-flex h-9 items-center rounded-[4px] border border-line px-4 text-sm font-bold text-text-body hover:border-brand hover:text-brand">
                查看会员方案
              </Link>
              {membership?.subscription && !membership.subscription.cancelRequestedAt && (
                <button type="button" onClick={() => void requestCancel()} className="inline-flex h-9 items-center rounded-[4px] border border-line px-4 text-sm font-bold text-text-body hover:border-brand hover:text-brand">
                  到期不续申请
                </button>
              )}
            </div>
          </div>

          <aside className="border-t border-line bg-bg p-7 md:border-l md:border-t-0">
            <div className="flex items-center gap-2 text-sm font-extrabold text-ink">
              <QrCode className="h-4 w-4 text-brand" />
              会员通行证
            </div>
            <div className="mx-auto mt-5 h-40 w-40 rounded-[4px] bg-white p-2 shadow-[0_8px_24px_rgba(15,23,42,0.06)]">
              <PassportQrCode passportNo={user.passportNo || ''} className="h-full w-full" />
            </div>
            <div className="mt-4 text-center text-xs font-bold text-muted">{passId}</div>
            <div className="mt-2 text-center text-[11px] font-bold text-soft">扫码核验身份与会员状态</div>
          </aside>
        </div>
      </section>
    </div>
  )
}
