'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { CalendarDays, ExternalLink, RefreshCw } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendRevenueReport, type BackendRevenueRow, yuan } from '@/lib/backend'
import { currentMonthValue, monthBounds, monthLabel, previousMonthValue } from '@/lib/month-filter'

const typeOptions = [
  { label: '全部类型', value: '' },
  { label: '会员', value: 'membership' },
  { label: '智能体', value: 'agent' },
  { label: '数据', value: 'data' },
  { label: '课程', value: 'course' },
  { label: '活动', value: 'event' },
  { label: '专家', value: 'expert' },
]

const statusOptions = [
  { label: '已支付', value: 'paid' },
  { label: '待支付', value: 'pending_payment' },
  { label: '已关闭', value: 'closed' },
]

const productTypeLabel: Record<string, string> = {
  membership: '会员',
  agent: '智能体',
  data: '数据',
  course: '课程',
  event: '活动',
  expert: '专家',
}

const statusLabel: Record<string, string> = {
  pending_payment: '待支付',
  paid: '已支付',
  closed: '已关闭',
  created: '已创建',
  succeeded: '已成功',
  expired: '已过期',
  failed: '已失败',
}

function money(value: number) {
  return `¥${yuan(value).toLocaleString()}`
}

function formatDate(value?: string) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN')
}

function readableType(value: string) {
  if (!value) return '-'
  return value.split(' / ').map((item) => productTypeLabel[item] || item).join(' / ')
}

const emptyReport: BackendRevenueReport = {
  summary: {
    dealAmount: 0,
    paidAmount: 0,
    platformIncomeAmount: 0,
    nonExpertIncomeAmount: 0,
    expertPlatformShareAmount: 0,
    expertPayableAmount: 0,
    orderCount: 0,
    paymentCount: 0,
  },
  items: [],
}

export default function AdminRevenuePage() {
  const defaultMonth = currentMonthValue()
  const defaultRange = monthBounds(defaultMonth)
  const [report, setReport] = useState<BackendRevenueReport>(emptyReport)
  const [month, setMonth] = useState(defaultMonth)
  const [from, setFrom] = useState(defaultRange.from)
  const [to, setTo] = useState(defaultRange.to)
  const [type, setType] = useState('')
  const [status, setStatus] = useState('paid')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const activeRangeLabel = month ? monthLabel(month) : (from || to ? '自定义日期' : '全部月份')
  const thisMonth = currentMonthValue()
  const lastMonth = previousMonthValue(thisMonth)

  const rows = report.items
  const typeSummary = useMemo(() => rows.reduce<Record<string, number>>((result, item) => {
    const key = readableType(item.productType)
    result[key] = (result[key] || 0) + item.platformKeepAmount
    return result
  }, {}), [rows])

  async function reload(next = { from, to, type, status }) {
    setLoading(true)
    try {
      const result = await backend.adminRevenue(next)
      setReport(result)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '平台收入加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    void reload({ ...monthBounds(currentMonthValue()), type: '', status: 'paid' })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  function applyMonth(nextMonth: string) {
    const range = monthBounds(nextMonth)
    setMonth(nextMonth)
    setFrom(range.from)
    setTo(range.to)
    void reload({ ...range, type, status })
  }

  function updateFrom(value: string) {
    setFrom(value)
    setMonth('')
  }

  function updateTo(value: string) {
    setTo(value)
    setMonth('')
  }

  function monthButtonClass(active: boolean) {
    return `h-8 rounded-[4px] border px-2.5 text-xs font-bold ${active ? 'border-brand bg-brand-light text-brand' : 'border-line text-muted hover:border-brand hover:text-brand'}`
  }

  const metrics = [
    ['平台收入', money(report.summary.platformIncomeAmount)],
    ['成交金额', money(report.summary.paidAmount)],
    ['专家平台分成', money(report.summary.expertPlatformShareAmount)],
    ['专家应结', money(report.summary.expertPayableAmount)],
    ['有效订单', report.summary.orderCount.toLocaleString()],
  ]

  return (
    <AdminShell
      title="平台收入"
      description="按已支付订单、支付流水和专家分账统计平台留存；暂不含手续费、税费和退款冲销。"
      topbarMetrics={metrics.map(([label, value]) => ({ label, value }))}
    >
      {error && <div className="mb-3 rounded-[4px] bg-red-50 px-4 py-3 text-sm font-bold text-red-700">{error}</div>}

      <section className="flex h-[calc(100vh-188px)] min-h-[520px] flex-col overflow-hidden border border-line bg-white">
        <form className="flex shrink-0 flex-col gap-2 border-b border-line px-3 py-2 lg:flex-row lg:flex-wrap lg:items-center" onSubmit={(event) => { event.preventDefault(); void reload() }}>
          <div className="flex shrink-0 flex-wrap items-center gap-2">
            <div className="relative">
              <CalendarDays className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-soft" />
              <input
                type="month"
                value={month}
                onChange={(event) => applyMonth(event.target.value)}
                className="h-8 w-[138px] rounded-[4px] border border-line pl-9 pr-3 text-xs font-bold outline-none focus:border-brand"
              />
            </div>
            <button type="button" onClick={() => applyMonth(thisMonth)} className={monthButtonClass(month === thisMonth)}>本月</button>
            <button type="button" onClick={() => applyMonth(lastMonth)} className={monthButtonClass(month === lastMonth)}>上月</button>
            <button type="button" onClick={() => applyMonth('')} className={monthButtonClass(month === '')}>全部</button>
          </div>
          <input type="date" value={from} onChange={(event) => updateFrom(event.target.value)} className="h-8 shrink-0 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand" />
          <input type="date" value={to} onChange={(event) => updateTo(event.target.value)} className="h-8 shrink-0 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand" />
          <select value={type} onChange={(event) => { setType(event.target.value); void reload({ from, to, type: event.target.value, status }) }} className="h-8 shrink-0 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            {typeOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
          </select>
          <select value={status} onChange={(event) => { setStatus(event.target.value); void reload({ from, to, type, status: event.target.value }) }} className="h-8 shrink-0 rounded-[4px] border border-line px-2 text-xs font-bold outline-none focus:border-brand">
            {statusOptions.map((item) => <option key={item.value} value={item.value}>{item.label}</option>)}
          </select>
          <button className="h-8 shrink-0 whitespace-nowrap rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white">查询</button>
          <button type="button" onClick={() => void reload()} className="inline-flex h-8 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand">
            <RefreshCw className="h-4 w-4" />
            刷新
          </button>
        </form>
        <div className="grid shrink-0 gap-2 border-b border-line bg-bg/40 px-3 py-2 text-xs font-bold text-muted md:grid-cols-3">
          <span>当前口径：<b className="text-ink">{activeRangeLabel}</b></span>
          {Object.entries(typeSummary).length === 0 ? (
            <span>暂无类型收入拆分</span>
          ) : Object.entries(typeSummary).map(([label, amount]) => (
            <span key={label}>{label}：<b className="text-ink">{money(amount)}</b></span>
          ))}
        </div>

        <div className="grid shrink-0 grid-cols-[minmax(280px,1fr)_130px_90px_105px_105px_105px_145px] border-b border-line px-3 py-2 text-xs font-extrabold text-soft">
          <span>订单/商品</span><span>用户</span><span>类型</span><span>实付</span><span>平台留存</span><span>专家应结</span><span>时间</span>
        </div>
        <div className="min-h-0 flex-1 overflow-y-auto">
          {loading && <div className="px-4 py-8 text-sm font-bold text-muted">正在加载平台收入...</div>}
          {!loading && rows.length === 0 && <div className="px-4 py-8 text-sm font-bold text-muted">暂无收入记录</div>}
          {!loading && rows.map((item: BackendRevenueRow) => (
            <div key={item.id} className="grid grid-cols-[minmax(280px,1fr)_130px_90px_105px_105px_105px_145px] items-center border-b border-line px-3 py-2 text-sm hover:bg-bg">
              <div className="min-w-0">
                <div className="flex min-w-0 items-center gap-2">
                  <Link href={`/admin/orders/${encodeURIComponent(item.orderNo)}`} className="truncate font-extrabold text-ink hover:text-brand">{item.orderNo}</Link>
                  {item.paymentNo && (
                    <Link href={`/admin/payments?selected=${encodeURIComponent(item.paymentNo)}`} className="shrink-0 text-brand hover:text-brand-dark" aria-label="查看支付记录">
                      <ExternalLink className="h-3.5 w-3.5" />
                    </Link>
                  )}
                </div>
                <div className="mt-0.5 truncate text-xs font-bold text-muted">{item.itemSummary || '-'} · {item.paymentNo || '无支付单'}</div>
              </div>
              <span className="truncate text-xs font-bold text-muted">{item.userPhone || '-'}</span>
              <span className="text-xs font-bold text-muted">{readableType(item.productType)}</span>
              <span className="text-sm font-extrabold text-ink">{money(item.paidAmount)}</span>
              <span className="text-sm font-extrabold text-brand">{money(item.platformKeepAmount)}</span>
              <span className="text-sm font-bold text-muted">{money(item.expertShareAmount)}</span>
              <span className="text-xs font-bold text-muted">{statusLabel[item.orderStatus] || item.orderStatus} · {formatDate(item.createdAt)}</span>
            </div>
          ))}
        </div>
      </section>
    </AdminShell>
  )
}
