'use client'

import Link from 'next/link'
import { Check, Minus } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useApp } from '@/components/providers/AppProvider'
import { backend, type BackendAccountMembership, type BackendMembershipCatalog, yuan } from '@/lib/backend'

const plans = [
  {
    name: '注册用户',
    badge: '免费',
    monthlyPrice: 0,
    yearlyPrice: 0,
    desc: '适合初次了解研究院服务的个人与机构用户。',
    cta: '免费注册',
    href: '/login',
    tone: 'base',
    groups: {
      基础访问: ['浏览公开内容', '参加免费活动', '购买所有付费产品'],
      专家与产品: ['查看专家主页', '数据服务预览', '智能体产品体验'],
      专属服务: [],
    },
  },
  {
    name: '初级会员',
    badge: '推荐',
    monthlyPrice: 99,
    yearlyPrice: 998,
    desc: '适合持续学习、定期参加活动并需要权益摘要的专业用户。',
    cta: '开通初级会员',
    href: '/checkout?type=membership&plan=junior',
    tone: 'brand',
    groups: {
      基础访问: ['全部注册用户权益', '会员专属课程', '会员专属活动'],
      专家与产品: ['专家预约权益', '服务报价会员提示', '后台配置会员价'],
      专属服务: ['每月 AI 行业报告', '智能体月度额度', '会员专属服务群'],
    },
  },
  {
    name: '高级会员',
    badge: '高级',
    monthlyPrice: 299,
    yearlyPrice: 2988,
    desc: '适合高频咨询、参与高端闭门活动并需要专属对接的机构客户。',
    cta: '开通高级会员',
    href: '/checkout?type=membership&plan=senior',
    tone: 'gold',
    groups: {
      基础访问: ['全部初级会员权益', '高级会员专属高端课程', '高级会员专属高端沙龙'],
      专家与产品: ['专家预约权益', '智能体月度额度', '优先专家预约'],
      专属服务: ['专属客户经理', '优先客服响应', '年度峰会优先席位'],
    },
  },
]

function renderCell(value: boolean | string) {
  if (value === 'true') return <Check className="mx-auto h-4 w-4 text-green" />
  if (value === 'false') return <Minus className="mx-auto h-4 w-4 text-line-dark" />
  if (value === true) return <Check className="mx-auto h-4 w-4 text-green" />
  if (value === false) return <Minus className="mx-auto h-4 w-4 text-line-dark" />
  return <span className="font-bold text-brand">{value}</span>
}

function membershipLevelNumber(level?: unknown) {
  if (level === 'senior') return 2
  if (level === 'junior') return 1
  return 0
}

function formatExpiryDate(value?: string | null) {
  if (!value) return ''
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).format(new Date(value))
}

export default function MembershipPage() {
  const [yearly, setYearly] = useState(true)
  const [catalog, setCatalog] = useState<BackendMembershipCatalog | null>(null)
  const [catalogLoading, setCatalogLoading] = useState(true)
  const [catalogError, setCatalogError] = useState('')
  const [accountMembership, setAccountMembership] = useState<BackendAccountMembership | null>(null)
  const [downgradePlan, setDowngradePlan] = useState<{ name: string; level: number } | null>(null)
  const [scheduledDowngrade, setScheduledDowngrade] = useState<string | null>(null)
  const { user, token } = useApp()
  const currentLevel = accountMembership ? membershipLevelNumber(accountMembership.level) : user ? membershipLevelNumber(user.membershipLevel) : 0
  const hasActiveMembership = Boolean(accountMembership?.subscription && accountMembership.status !== 'registered' && accountMembership.status !== 'expired')
  const expiryText = hasActiveMembership ? formatExpiryDate(accountMembership?.expiresAt) : ''
  useEffect(() => {
    setCatalogLoading(true)
    void backend.membershipCatalog()
      .then((result) => {
        setCatalog(result)
        setCatalogError('')
      })
      .catch(() => {
        setCatalog(null)
        setCatalogError('会员方案加载失败，请稍后刷新。')
      })
      .finally(() => setCatalogLoading(false))
  }, [])
  useEffect(() => {
    if (!token) {
      setAccountMembership(null)
      return
    }
    void backend.accountMembership(token).then(setAccountMembership).catch(() => setAccountMembership(null))
  }, [token])
  const visiblePlans = useMemo(() => {
    if (!Array.isArray(catalog?.plans) || catalog.plans.length === 0) return [plans[0]]
    return [
      plans[0],
      ...catalog.plans.map((plan) => ({
        name: plan.name,
        badge: plan.badge,
        monthlyPrice: yuan(plan.monthlyPriceAmount),
        yearlyPrice: yuan(plan.yearlyPriceAmount),
        desc: plan.description,
        cta: plan.ctaLabel,
        href: `/checkout?type=membership&plan=${plan.level}`,
        tone: plan.tone,
        groups: Object.fromEntries((Array.isArray(plan.groups) ? plan.groups : []).map((group) => [group.title, group.items])),
      })),
    ]
  }, [catalog])
  const visibleCompareRows = Array.isArray(catalog?.compareRows)
    ? catalog.compareRows.map((row) => [row.label, row.registeredValue, row.juniorValue, row.seniorValue])
    : []
  const visibleFaqs = Array.isArray(catalog?.faqs)
    ? catalog.faqs.map((item) => [item.question, item.answer])
    : []

  if (catalogLoading) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] border border-line bg-white p-8 text-center text-sm font-extrabold text-muted">正在加载会员方案...</div>
      </section>
    )
  }

  if (catalogError || !catalog) {
    return (
      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[720px] border border-line bg-white p-8 text-center">
          <h1 className="text-xl font-extrabold text-ink">会员方案加载失败</h1>
          <p className="mt-3 text-sm font-bold text-muted">{catalogError || '请刷新后重试。'}</p>
        </div>
      </section>
    )
  }

  return (
    <>
      <section className="bg-white pt-10 pb-16">
        <div className="mx-auto max-w-[1180px] px-6">
          <div className="mb-6 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
            {expiryText ? (
              <div className="min-w-0 text-sm font-bold text-muted">
                到期时间：<span className="ml-2 font-extrabold text-ink">{expiryText}</span>
              </div>
            ) : <div />}
            <div className="inline-flex w-fit items-stretch rounded-[4px] border border-line bg-white p-1 shadow-[0_12px_32px_rgba(10,58,120,0.08)]">
              <button
                type="button"
                onClick={() => setYearly(false)}
                className={`min-h-11 px-6 text-sm font-bold ${!yearly ? 'bg-brand text-white' : 'text-muted hover:text-brand'}`}
              >
                按月
              </button>
              <button
                type="button"
                onClick={() => setYearly(true)}
                className={`flex min-h-11 flex-col items-center justify-center px-6 text-sm font-bold leading-tight ${yearly ? 'bg-brand text-white' : 'text-muted hover:text-brand'}`}
              >
                <span>按年</span>
                <span className={`mt-0.5 text-[11px] ${yearly ? 'text-white/75' : 'text-green'}`}>年付更省</span>
              </button>
            </div>
          </div>
          {scheduledDowngrade && (
            <div className="mb-6 rounded-[4px] border border-brand/20 bg-brand-light px-4 py-3 text-sm font-bold text-brand">
              已提交降级申请：{scheduledDowngrade} 将于下个月账期生效，本月权益保持不变。
            </div>
          )}
          <div className="grid gap-6 lg:grid-cols-3">
            {visiblePlans.map((plan) => {
            const isPaid = plan.monthlyPrice > 0
            const isGold = plan.tone === 'gold'
            const isBrand = plan.tone === 'brand'
            const planLevel = plan.name === '高级会员' ? 2 : plan.name === '初级会员' ? 1 : 0
            const isUpgrade = currentLevel === 1 && planLevel === 2
            const isDowngrade = Boolean(user) && currentLevel > planLevel
            const checkoutHref = isPaid ? `/checkout?type=membership&plan=${planLevel === 2 ? 'senior' : 'junior'}&cycle=${yearly ? 'yearly' : 'monthly'}${isUpgrade ? '&change=upgrade' : ''}` : plan.href
            const href = isPaid && !user ? `/login-required?redirect=${encodeURIComponent(checkoutHref)}&action=membership` : checkoutHref
            const isCurrent = Boolean(user) && currentLevel === planLevel
            const ctaLabel = isCurrent ? '当前权益' : isDowngrade ? `降级为${plan.name}` : isUpgrade ? '升级高级会员 · 补差价' : plan.cta
	            return (
	              <article
	                key={plan.name}
	                className={`relative rounded-[4px] border p-7 shadow-[0_16px_42px_rgba(10,58,120,0.08)] ${isBrand ? 'border-brand/20 bg-brand-light/70' : isGold ? 'border-[#c9a227]/25 bg-[#fdf6e4]' : 'border-line/70 bg-bg/80'}`}
	              >
	                <div>
	                  <span className={`inline-block rounded-[3px] px-3 py-1 text-[11px] font-extrabold tracking-[0.08em] text-white ${isGold ? 'bg-[#c9a227]' : isBrand ? 'bg-brand' : 'bg-muted'}`}>
                    {plan.badge}
                  </span>
                  <div className={`mt-5 text-sm font-extrabold tracking-[0.08em] ${isGold ? 'text-gold' : isBrand ? 'text-brand' : 'text-muted'}`}>
                    {plan.name}
                  </div>
                  <div className="mt-3 flex items-baseline gap-1">
                    {isPaid ? (
                      <>
                        <strong className="text-5xl font-extrabold leading-none text-ink">
                          ¥{yearly ? Math.round(plan.yearlyPrice / 12) : plan.monthlyPrice}
                        </strong>
                        <span className="text-sm text-muted">/月</span>
                      </>
                    ) : (
                      <strong className="text-4xl font-extrabold leading-none text-ink">免费</strong>
                    )}
                  </div>
                  <div className="mt-2 min-h-5 text-sm text-muted">
                    {isPaid ? (yearly ? `按年支付 ¥${plan.yearlyPrice}` : '按月支付，可后续续费') : '永久免费'}
                  </div>
                  <p className="mt-4 min-h-14 text-sm leading-7 text-muted">{plan.desc}</p>
                    {isCurrent ? (
                      <div className="mt-6 block rounded-[4px] border border-line bg-white/70 py-3 text-center text-sm font-extrabold text-muted">
                        {ctaLabel}
                      </div>
                    ) : isDowngrade ? (
                      <button
                        type="button"
                        onClick={() => setDowngradePlan({ name: plan.name, level: planLevel })}
                        className="mt-6 block w-full rounded-[4px] border border-line bg-white/70 py-3 text-center text-sm font-extrabold text-text-body hover:border-brand hover:text-brand"
                      >
                        {ctaLabel}
                      </button>
                    ) : (
	                    <Link
	                      href={href}
	                      className={`mt-6 block rounded-[4px] py-3 text-center text-sm font-extrabold ${isGold ? 'bg-[#c9a227] text-white hover:bg-[#a8861e]' : isBrand ? 'bg-brand text-white hover:bg-brand-dark' : 'border-2 border-brand text-brand hover:bg-brand-light'}`}
	                    >
	                      {ctaLabel}
	                    </Link>
                    )}
	                </div>
	              </article>
            )
            })}
          </div>
	        </div>
      </section>

      {downgradePlan && (
        <div className="fixed inset-0 z-[80] grid place-items-center bg-ink/35 px-6">
          <div className="w-full max-w-[420px] rounded-[4px] border border-line bg-white p-6 shadow-[0_22px_70px_rgba(15,23,42,0.22)]">
            <div className="text-xl font-extrabold text-ink">确认降级会员？</div>
            <p className="mt-3 text-sm leading-7 text-muted">
              你正在申请降级为{downgradePlan.name}。降级不会立即生效，将在下个月账期开始时生效；当前账期内仍保留现有会员权益。
            </p>
            <div className="mt-6 grid gap-3 sm:grid-cols-2">
              <button
                type="button"
                autoFocus
                onClick={() => setDowngradePlan(null)}
                className="rounded-[4px] bg-brand px-4 py-2.5 text-sm font-extrabold text-white hover:bg-brand-dark"
              >
                不降级
              </button>
              <button
                type="button"
                onClick={() => {
                  setScheduledDowngrade(downgradePlan.name)
                  setDowngradePlan(null)
                }}
                className="rounded-[4px] border border-line px-4 py-2.5 text-sm font-extrabold text-text-body hover:border-brand hover:text-brand"
              >
                确认降级
              </button>
            </div>
          </div>
        </div>
      )}

      <section className="bg-white pb-16">
        <div className="mx-auto max-w-[1180px] px-6">
          <h2 className="mb-8 text-3xl font-extrabold text-ink">权益详细对比</h2>
          <div className="overflow-x-auto rounded-[4px] border border-line">
            <table className="w-full min-w-[760px] border-collapse text-sm">
              <thead>
                <tr className="bg-bg text-left">
                  <th className="border-b border-line px-5 py-4 font-bold text-ink">权益项</th>
                  <th className="border-b border-line px-5 py-4 text-center font-bold text-muted">注册用户</th>
                  <th className="border-b border-line bg-brand-light px-5 py-4 text-center font-bold text-brand">初级会员</th>
                  <th className="border-b border-line bg-gold-light px-5 py-4 text-center font-bold text-gold">高级会员</th>
                </tr>
              </thead>
              <tbody>
                {visibleCompareRows.map(([label, free, pro, max]) => (
                  <tr key={String(label)} className="hover:bg-bg">
                    <td className="border-b border-line px-5 py-4 text-text-body">{label}</td>
                    <td className="border-b border-line px-5 py-4 text-center">{renderCell(free)}</td>
                    <td className="border-b border-line bg-[rgba(10,58,120,0.03)] px-5 py-4 text-center">{renderCell(pro)}</td>
                    <td className="border-b border-line bg-[rgba(184,134,11,0.03)] px-5 py-4 text-center">{renderCell(max)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </section>

      <section className="bg-bg py-16">
        <div className="mx-auto max-w-[1180px] px-6">
          <h2 className="mb-8 text-3xl font-extrabold text-ink">常见问题</h2>
          <div className="grid overflow-hidden rounded-[4px] border border-line bg-line md:grid-cols-2">
            {visibleFaqs.map(([q, a]) => (
              <div key={q} className="bg-white p-7">
                <h3 className="text-base font-bold text-ink">{q}</h3>
                <p className="mt-3 text-sm leading-7 text-muted">{a}</p>
              </div>
            ))}
          </div>
        </div>
      </section>

    </>
  )
}
