'use client'

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

const orderStatusLabel: Record<string, string> = {
  pending_payment: '待支付',
  paid: '已支付',
  closed: '已关闭',
}

const paymentStatusLabel: Record<string, string> = {
  created: '已创建',
  succeeded: '已成功',
  expired: '已过期',
  failed: '已失败',
}

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

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

function formatDate(value?: string | null) {
  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(' / ')
}

export default function AdminReconcilePage() {
  const defaultMonth = currentMonthValue()
  const defaultRange = monthBounds(defaultMonth)
  const [items, setItems] = useState<BackendReconcileRow[]>([])
  const [month, setMonth] = useState(defaultMonth)
  const [from, setFrom] = useState(defaultRange.from)
  const [to, setTo] = useState(defaultRange.to)
  const [search, setSearch] = useState('')
  const [loading, setLoading] = useState(false)
  const [exporting, setExporting] = useState(false)
  const [error, setError] = useState('')
  const activeRangeLabel = month ? monthLabel(month) : (from || to ? '自定义日期' : '全部月份')
  const thisMonth = currentMonthValue()
  const lastMonth = previousMonthValue(thisMonth)

  async function reload(next = { from, to, search }) {
    setLoading(true)
    try {
      const result = await backend.adminReconcile(next)
      setItems(result.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '对账数据加载失败')
    } finally {
      setLoading(false)
    }
  }

  async function exportCsv() {
    setExporting(true)
    try {
      const token = getStaffToken()
      const response = await fetch(backend.adminReconcileExportUrl({ from, to, search: search.trim() }), {
        headers: token ? { authorization: `Bearer ${token}` } : adminToken ? { 'x-admin-token': adminToken } : {},
      })
      if (!response.ok) throw new Error(`导出失败：${response.status}`)
      const blob = await response.blob()
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `对账导出-${exportPeriod()}.csv`
      document.body.appendChild(link)
      link.click()
      link.remove()
      URL.revokeObjectURL(url)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '对账导出失败')
    } finally {
      setExporting(false)
    }
  }

  useEffect(() => {
    void reload({ ...monthBounds(currentMonthValue()), search: '' })
    // 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, search: search.trim() })
  }

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

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

  function exportPeriod() {
    if (month) return month
    if (from || to) return `${from || '开始'}-${to || '至今'}`
    return '全部月份'
  }

  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 summary = items.reduce((result, item) => ({
    count: result.count + 1,
    paid: result.paid + item.paidAmount,
    platform: result.platform + item.platformKeepAmount,
    expert: result.expert + item.expertShareAmount,
  }), { count: 0, paid: 0, platform: 0, expert: 0 })

  return (
    <AdminShell
      title="对账导出"
      description="按订单、支付单和专家分账生成对账预览，并导出 CSV。"
      topbarMetrics={[
        { label: '记录数', value: summary.count.toLocaleString() },
        { label: '实付金额', value: money(summary.paid) },
        { label: '平台留存', value: money(summary.platform) },
        { label: '专家应结', value: money(summary.expert) },
      ]}
    >
      {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 xl:flex-row xl:flex-wrap xl: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" />
          <div className="relative min-w-0 flex-1">
            <Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-soft" />
            <input
              value={search}
              onChange={(event) => setSearch(event.target.value)}
              placeholder="搜索订单号、支付单号、结算批次、手机号或商品名"
              className="h-8 w-full rounded-[4px] border border-line pl-9 pr-3 text-xs outline-none focus:border-brand"
            />
          </div>
          <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>
          <button type="button" onClick={() => void exportCsv()} disabled={exporting} className="inline-flex h-8 shrink-0 items-center justify-center gap-1.5 whitespace-nowrap rounded-[4px] bg-brand px-3 text-xs font-extrabold text-white disabled:opacity-60">
            <Download className="h-4 w-4" />
            {exporting ? '导出中' : '导出 CSV'}
          </button>
        </form>
        <div className="shrink-0 border-b border-line bg-bg/40 px-3 py-2 text-xs font-bold text-muted">
          当前口径：<b className="text-ink">{activeRangeLabel}</b>
        </div>

        <div className="min-h-0 flex-1 overflow-auto">
          <div className="min-w-[1180px]">
            <div className="grid sticky top-0 z-10 grid-cols-[110px_minmax(260px,1fr)_140px_100px_100px_110px_110px_110px_150px] border-b border-line bg-white px-3 py-2 text-xs font-extrabold text-soft">
              <span>日期</span><span>订单/支付</span><span>用户</span><span>类型</span><span>渠道</span><span>实付</span><span>平台留存</span><span>专家应结</span><span>状态/时间</span>
            </div>
            {loading && <div className="px-4 py-8 text-sm font-bold text-muted">正在加载对账数据...</div>}
            {!loading && items.length === 0 && <div className="px-4 py-8 text-sm font-bold text-muted">暂无对账记录</div>}
            {!loading && items.map((item) => (
              <div key={item.id} className="grid grid-cols-[110px_minmax(260px,1fr)_140px_100px_100px_110px_110px_110px_150px] items-center border-b border-line px-3 py-2 text-sm hover:bg-bg">
                <span className="text-xs font-bold text-muted">{item.date || '-'}</span>
                <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-1 truncate text-xs font-bold text-muted">{item.paymentNo || '无支付单'} · {item.settlementNo || '无结算批次'} · {item.itemSummary || '-'}</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="truncate text-xs font-bold text-muted">{item.paymentChannel || '-'}</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">{orderStatusLabel[item.orderStatus] || item.orderStatus} / {paymentStatusLabel[item.paymentStatus || ''] || item.paymentStatus || '-'} · {formatDate(item.createdAt)}</span>
              </div>
            ))}
          </div>
        </div>
      </section>
    </AdminShell>
  )
}
