import { ScrollView, Text, View } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useEffect, useMemo, useState } from 'react'
import { Page } from '@/components/ui'
import {
  backend,
  type BackendAccountMembership,
  type BackendMembershipCatalog,
  type BackendMembershipPlan,
  yuan
} from '@/api/backend'
import { addToCart, getToken, getUser } from '@/stores/storage'
import { tapMedium } from '@/utils/feedback'

type BillingCycle = 'monthly' | 'yearly'
type MembershipLevel = BackendAccountMembership['level'] | BackendMembershipPlan['level']
type MembershipGroup = { id: string; title: string; items: string[] }
type CompareColumnKey = 'registeredValue' | 'juniorValue' | 'seniorValue'
type DisplayMembershipPlan = {
  id: string
  level: MembershipLevel
  name: string
  badge: string
  description: string
  ctaLabel: string
  tone?: string
  monthlyPriceAmount: number
  yearlyPriceAmount: number
  groups: MembershipGroup[]
  source?: BackendMembershipPlan
}

const registeredGroups: MembershipGroup[] = [
  { id: 'registered-base', title: '基础访问', items: ['浏览公开内容', '参加免费活动', '购买所有付费产品'] },
  { id: 'registered-service', title: '专家与产品', items: ['查看专家主页', '数据服务预览', '智能体产品体验'] }
]

const registeredPlan: DisplayMembershipPlan = {
  id: 'registered',
  level: 'registered',
  name: '注册用户',
  badge: '免费',
  description: '适合初次了解研究院服务的个人与机构用户。',
  ctaLabel: '免费注册',
  tone: 'base',
  monthlyPriceAmount: 0,
  yearlyPriceAmount: 0,
  groups: registeredGroups
}

const compareColumns: { key: CompareColumnKey; label: string; tone: string }[] = [
  { key: 'registeredValue', label: '注册用户', tone: 'registered' },
  { key: 'juniorValue', label: '初级会员', tone: 'junior' },
  { key: 'seniorValue', label: '高级会员', tone: 'senior' }
]

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

function formatDate(value?: string | null) {
  if (!value) return '未开通'
  const date = new Date(value)
  return Number.isNaN(date.getTime()) ? '未开通' : date.toLocaleDateString('zh-CN')
}

function planTone(plan: DisplayMembershipPlan) {
  if (plan.level === 'senior' || plan.tone === 'gold') return 'senior'
  if (plan.level === 'junior' || plan.tone === 'brand') return 'junior'
  return 'registered'
}

function compareCellText(value?: string) {
  const raw = String(value || '').trim()
  const normalized = raw.toLowerCase()
  if (!raw || normalized === 'false' || raw === '-' || raw === '—' || raw === '无') return '—'
  if (normalized === 'true' || raw === '有' || raw === '是' || raw === '✓') return '✓'
  return raw
}

function compareCellTone(value?: string) {
  const text = compareCellText(value)
  if (text === '✓') return 'yes'
  if (text === '—') return 'empty'
  return 'text'
}

export default function MembershipPage() {
  const user = getUser()
  const token = getToken()
  const [membership, setMembership] = useState<BackendAccountMembership | null>(null)
  const [catalog, setCatalog] = useState<BackendMembershipCatalog | null>(null)
  const [cycle, setCycle] = useState<BillingCycle>('monthly')
  const level = membership ? levelFromBackend(membership.level) : user?.membershipLevel || 0

  useEffect(() => {
    if (!token) {
      setMembership(null)
      return
    }
    backend.accountMembership(token).then(setMembership).catch(() => setMembership(null))
  }, [token])

  useEffect(() => {
    backend.membershipCatalog().then(setCatalog).catch(() => setCatalog(null))
  }, [])

  const backendPlans = useMemo(() => {
    const items: BackendMembershipPlan[] = catalog?.plans?.length ? catalog.plans : []
    return [...items].sort((left, right) => (left.sortOrder || 0) - (right.sortOrder || 0))
  }, [catalog])

  const displayPlans = useMemo<DisplayMembershipPlan[]>(() => [
    registeredPlan,
    ...backendPlans.map((plan) => ({
      id: plan.productId,
      level: plan.level,
      name: plan.name,
      badge: plan.badge || (plan.recommended ? '推荐' : '会员'),
      description: plan.description,
      ctaLabel: plan.ctaLabel || `开通${plan.name}`,
      tone: plan.tone,
      monthlyPriceAmount: plan.monthlyPriceAmount,
      yearlyPriceAmount: plan.yearlyPriceAmount,
      groups: plan.groups || [],
      source: plan
    }))
  ], [backendPlans])

  const compareRows = useMemo(() => Array.isArray(catalog?.compareRows) ? catalog.compareRows : [], [catalog])
  const subscription = membership?.subscription || membership?.latestSubscription || membership?.activeSubscriptions?.[0] || null
  const identityText = level === 2 ? '高级会员' : level === 1 ? '初级会员' : '注册用户'
  const tierClass = level === 2 ? 'senior' : level === 1 ? 'junior' : 'registered'
  const tierMark = level === 2 ? 'SENIOR' : level === 1 ? 'JUNIOR' : 'BASIC'
  const expiryText = level > 0 ? formatDate(membership?.expiresAt || subscription?.expiresAt) : '未开通'

  function cyclePrice(plan: DisplayMembershipPlan | BackendMembershipPlan) {
    return yuan(cycle === 'yearly' ? plan.yearlyPriceAmount : plan.monthlyPriceAmount)
  }

  function planActionLabel(plan: DisplayMembershipPlan) {
    const planLevel = levelFromBackend(plan.level)
    const isCurrent = level === planLevel && membership?.status !== 'expired'
    if (isCurrent) return '当前身份'
    if (plan.level === 'registered') return user ? '注册权益' : '免费注册'
    if (membership?.status === 'expired' && level === planLevel) return `重新开通${plan.name}`
    if (level === 1 && planLevel === 2) return '升级高级会员'
    return plan.ctaLabel || `开通${plan.name}`
  }

  function handlePlanAction(plan: DisplayMembershipPlan) {
    const planLevel = levelFromBackend(plan.level)
    const isCurrent = level === planLevel && membership?.status !== 'expired'
    if (isCurrent) return
    if (!plan.source) {
      if (!user) Taro.navigateTo({ url: '/pages/auth/login/index?redirect=/pages/account/membership/index' })
      return
    }
    if (!user) {
      Taro.navigateTo({ url: '/pages/auth/login/index?redirect=/pages/account/membership/index' })
      return
    }
    tapMedium()
    addToCart({
      id: plan.source.productId,
      type: 'membership',
      title: plan.source.name,
      subtitle: `会员权益 · ${cycle === 'yearly' ? '年付' : '月付'}`,
      price: cyclePrice(plan.source),
      cover: 'membership',
      billingCycle: cycle
    })
    Taro.navigateTo({ url: '/pages/checkout/index' })
  }

  return (
    <Page title="会员权益">
      <View className={`membership-hero membership-hero-${tierClass}`}>
        <View className="membership-card-top">
          <View>
            <Text className="membership-card-kicker">会员身份</Text>
            <Text className="membership-title">{identityText}</Text>
          </View>
          <Text className="membership-card-mark">{tierMark}</Text>
        </View>
        <View className="membership-card-footer">
          <View>
            <Text className="membership-card-label">到期日</Text>
            <Text className="membership-card-expiry">{expiryText}</Text>
          </View>
          <Text className="membership-card-institute">DLBDI</Text>
        </View>
      </View>

      <View className="membership-cycle">
        <View className={cycle === 'monthly' ? 'cycle-btn active' : 'cycle-btn'} onClick={() => setCycle('monthly')}>
          <Text>按月</Text>
        </View>
        <View className={cycle === 'yearly' ? 'cycle-btn active' : 'cycle-btn'} onClick={() => setCycle('yearly')}>
          <Text>按年</Text>
          <Text className="cycle-sub">年付更省</Text>
        </View>
      </View>

      <View className="membership-package-list">
        {displayPlans.map((plan) => {
          const tone = planTone(plan)
          const planLevel = levelFromBackend(plan.level)
          const isCurrent = level === planLevel && membership?.status !== 'expired'
          const isPaid = planLevel > 0
          const price = cyclePrice(plan)
          return (
            <View key={plan.id} className={`membership-package-card membership-package-${tone} ${isCurrent ? 'active' : ''}`}>
              <View className="membership-package-head">
                <View>
                  <Text className="membership-package-badge">{plan.badge}</Text>
                  <Text className="membership-package-name">{plan.name}</Text>
                </View>
                {isCurrent && <Text className="membership-package-current">当前</Text>}
              </View>
              <View className="membership-package-price-row">
                {isPaid ? (
                  <>
                    <Text className="membership-package-price">¥{cycle === 'yearly' ? Math.round(yuan(plan.yearlyPriceAmount) / 12) : price}</Text>
                    <Text className="membership-package-unit">/月</Text>
                  </>
                ) : (
                  <Text className="membership-package-free">免费</Text>
                )}
              </View>
              <Text className="membership-package-note">
                {isPaid ? (cycle === 'yearly' ? `按年支付 ¥${yuan(plan.yearlyPriceAmount).toLocaleString()}` : '按月支付，可后续调整') : '永久免费'}
              </Text>
              <Text className="membership-package-desc">{plan.description}</Text>
              <View className={isCurrent ? 'membership-package-action disabled' : `membership-package-action ${tone}`} onClick={() => handlePlanAction(plan)}>
                {planActionLabel(plan)}
              </View>
            </View>
          )
        })}
      </View>

      {compareRows.length ? (
        <View className="membership-compare-card">
          <ScrollView scrollX className="membership-compare-scroll">
            <View className="membership-compare-table">
              <View className="membership-compare-row membership-compare-head">
                <Text className="membership-compare-label">权益项</Text>
                {compareColumns.map((column) => (
                  <Text key={column.key} className={`membership-compare-cell membership-compare-head-cell ${column.tone}`}>
                    {column.label}
                  </Text>
                ))}
              </View>
              {compareRows.map((row) => (
                <View key={row.id || row.label} className="membership-compare-row">
                  <Text className="membership-compare-label">{row.label}</Text>
                  {compareColumns.map((column) => (
                    <Text key={`${row.id}-${column.key}`} className={`membership-compare-cell ${column.tone} ${compareCellTone(row[column.key])}`}>
                      {compareCellText(row[column.key])}
                    </Text>
                  ))}
                </View>
              ))}
            </View>
          </ScrollView>
        </View>
      ) : null}
    </Page>
  )
}
