'use client'

import Link from 'next/link'
import { Suspense, useEffect, useMemo, useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendSettlement, yuan } from '@/lib/backend'

const settlementTabs = [
  { label: '全部', value: '' },
  { label: '待结算', value: 'pending_settlement' },
  { label: '可提现', value: 'available' },
  { label: '提现中', value: 'withdrawal_locked' },
  { label: '已提现', value: 'withdrawn' },
]

function formatDateTime(value?: string) {
  if (!value) return '-'
  const date = new Date(value)
  return `${date.getMonth() + 1}月${date.getDate()}日 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

function statusLabel(status: string) {
  if (status === 'pending_settlement') return '待结算'
  if (status === 'available') return '可提现'
  if (status === 'withdrawal_locked') return '提现中'
  if (status === 'withdrawn') return '已提现'
  if (status === 'paid' || status === 'completed') return '已结算'
  return status
}

function AdminSettlementsContent() {
  const searchParams = useSearchParams()
  const selectedNo = searchParams.get('selected') || ''
  const [items, setItems] = useState<BackendSettlement[]>([])
  const [status, setStatus] = useState('')
  const [keyword, setKeyword] = useState('')
  const [error, setError] = useState('')

  useEffect(() => {
    void backend.adminSettlements({ status })
      .then((result) => {
        setItems(result.items)
        setError('')
      })
      .catch((err) => setError(err instanceof Error ? err.message : '结算记录加载失败'))
  }, [status])

  const expertItems = items.filter((item) => item.expertId || item.passportNo)
  const visibleItems = useMemo(() => {
    const word = keyword.trim().toLowerCase()
    if (!word) return expertItems
    return expertItems.filter((item) => [
      item.settlementNo,
      item.orderNo,
      item.productTitle,
      item.userPhone,
      item.passportNo,
      item.status,
    ].filter(Boolean).join(' ').toLowerCase().includes(word))
  }, [expertItems, keyword])
  const summary = useMemo(() => expertItems.reduce((result, item) => ({
    gross: result.gross + item.grossAmount,
    expert: result.expert + item.expertShareAmount,
    platform: result.platform + item.platformShareAmount,
    available: result.available + (item.availableAmount || 0),
    locked: result.locked + (item.lockedAmount || 0),
    withdrawn: result.withdrawn + (item.withdrawnAmount || 0),
  }), { gross: 0, expert: 0, platform: 0, available: 0, locked: 0, withdrawn: 0 }), [expertItems])

  return (
    <AdminShell
      title="专家收益结算"
      description="查看专家订单分成、可提现、提现中和已提现流水。"
      topbarMetrics={[
        { label: '订单额', value: `¥${yuan(summary.gross).toLocaleString()}` },
        { label: '专家分成', value: `¥${yuan(summary.expert).toLocaleString()}` },
        { label: '可提现', value: `¥${yuan(summary.available).toLocaleString()}` },
        { label: '提现中', value: `¥${yuan(summary.locked).toLocaleString()}` },
        { label: '已提现', value: `¥${yuan(summary.withdrawn).toLocaleString()}` },
      ]}
    >
      {error && <div className="mb-2 rounded-[4px] bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{error}</div>}
      <div className="mb-2 flex flex-wrap items-center gap-2">
        <input value={keyword} onChange={(event) => setKeyword(event.target.value)} placeholder="搜订单、结算号、用户、通行证" className="h-8 w-full rounded-[4px] border border-line bg-white px-3 text-xs font-bold outline-none focus:border-brand md:w-72" />
        {settlementTabs.map((tab) => (
          <button key={tab.value} type="button" onClick={() => setStatus(tab.value)} className={`h-8 rounded-[4px] border px-3 text-xs font-extrabold ${status === tab.value ? 'border-brand bg-brand-light text-brand' : 'border-line bg-white text-muted hover:border-brand hover:text-brand'}`}>{tab.label}</button>
        ))}
        <Link href="/admin/expert-withdrawals" className="h-8 rounded-[4px] bg-ink px-3 py-2 text-xs font-extrabold text-white hover:bg-brand">处理提现</Link>
      </div>
      <section className="h-[calc(100vh-198px)] min-h-[500px] overflow-hidden border border-line bg-white">
        <div className="grid grid-cols-[minmax(260px,1fr)_120px_100px_100px_100px_90px] 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>
        </div>
        <div className="h-[calc(100%-33px)] divide-y divide-line overflow-y-auto">
          {visibleItems.length === 0 ? (
            <div className="px-4 py-10 text-center text-sm font-bold text-muted">暂无专家结算记录</div>
          ) : visibleItems.map((item) => (
            <div key={item.id} className={`grid gap-2 px-3 py-3 text-sm lg:grid-cols-[minmax(260px,1fr)_120px_100px_100px_100px_90px] lg:items-center ${selectedNo && (item.settlementNo === selectedNo || item.id === selectedNo) ? 'bg-brand-light' : ''}`}>
              <div>
                <div className="font-extrabold text-ink">{item.productTitle}</div>
                <div className="mt-1 text-xs font-bold text-muted">{item.settlementNo || item.id} · {item.orderNo} · 用户 {item.userPhone || '-'} · 通行证 {item.passportNo || '-'}</div>
                <div className="mt-1 text-[11px] font-bold text-soft">{formatDateTime(item.createdAt)}{item.availableAt ? ` · 可提现 ${formatDateTime(item.availableAt)}` : ''}</div>
              </div>
              <div className="text-xs font-bold text-muted">{item.expertName || item.passportNo || '-'}</div>
              <div className="text-sm font-bold text-muted">¥{yuan(item.grossAmount).toLocaleString()}</div>
              <div className="text-sm font-bold text-brand">¥{yuan(item.expertShareAmount).toLocaleString()}</div>
              <div className="text-sm font-bold text-muted">¥{yuan(item.platformShareAmount).toLocaleString()}</div>
              <div className="text-xs font-extrabold text-muted">{statusLabel(item.status)}</div>
            </div>
          ))}
        </div>
      </section>
    </AdminShell>
  )
}

export default function AdminSettlementsPage() {
  return (
    <Suspense fallback={<AdminShell title="专家分账" description="查看专家订单分成记录，分成比例来自支付时的专家档案快照。"><div className="border border-line bg-white px-4 py-6 text-sm font-bold text-muted">正在加载专家分账...</div></AdminShell>}>
      <AdminSettlementsContent />
    </Suspense>
  )
}
