'use client'

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

const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '已创建', value: 'created' },
  { label: '支付中', value: 'paying' },
  { label: '已成功', value: 'succeeded' },
  { label: '已过期', value: 'expired' },
  { label: '已失败', value: 'failed' },
  { label: '已关闭', value: 'closed' },
]

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

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

function AdminPaymentsContent() {
  const searchParams = useSearchParams()
  const selectedNo = searchParams.get('selected') || ''
  const initialSearch = selectedNo || searchParams.get('search') || ''
  const defaultMonth = currentMonthValue()
  const defaultRange = monthBounds(defaultMonth)
  const [items, setItems] = useState<BackendPaymentOrder[]>([])
  const [search, setSearch] = useState(initialSearch)
  const [status, setStatus] = useState('')
  const [month, setMonth] = useState(defaultMonth)
  const [from, setFrom] = useState(defaultRange.from)
  const [to, setTo] = useState(defaultRange.to)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const activeRangeLabel = month ? monthLabel(month) : (from || to ? '自定义日期' : '全部月份')
  const thisMonth = currentMonthValue()
  const lastMonth = previousMonthValue(thisMonth)

  const summary = useMemo(() => items.reduce((result, item) => ({
    count: result.count + 1,
    amount: result.amount + item.amount,
    succeeded: result.succeeded + (item.status === 'succeeded' ? item.amount : 0),
  }), { count: 0, amount: 0, succeeded: 0 }), [items])

  async function reload(nextSearch = search, nextStatus = status, nextMonth = month, nextFrom = from, nextTo = to) {
    setLoading(true)
    try {
      const range = nextMonth ? monthBounds(nextMonth) : { from: nextFrom, to: nextTo }
      const result = await backend.adminPayments({ search: nextSearch.trim(), status: nextStatus, from: range.from, to: range.to })
      setItems(result.items)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '支付记录加载失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    setSearch(initialSearch)
    void reload(initialSearch, '', month, from, to)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [initialSearch])

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

  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'}`
  }

  return (
    <AdminShell
      title="支付记录"
      description="查看支付单、关联订单、渠道、金额和支付状态。"
      topbarMetrics={[
        { label: `${activeRangeLabel}支付单数`, value: summary.count },
        { label: `${activeRangeLabel}支付金额`, value: `¥${yuan(summary.amount).toLocaleString()}` },
        { label: `${activeRangeLabel}成功金额`, value: `¥${yuan(summary.succeeded).toLocaleString()}` },
      ]}
    >
      {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(search, status, month, from, to) }}>
          <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.toUpperCase())}
              placeholder="搜索支付单号、订单号、结算批次、手机号或商品名"
              className="h-8 w-full rounded-[4px] border border-line pl-9 pr-3 text-xs outline-none focus:border-brand"
            />
          </div>
          <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={status} onChange={(event) => { setStatus(event.target.value); void reload(search, event.target.value, month, from, to) }} 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(search, status, month, from, to)} 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 grid-cols-[minmax(300px,1fr)_140px_90px_110px_100px_150px] 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="min-h-0 flex-1 overflow-y-auto">
          {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) => {
            const selected = selectedNo && (item.paymentNo === selectedNo || item.id === selectedNo)
            return (
              <div key={item.id} className={`grid grid-cols-[minmax(300px,1fr)_140px_90px_110px_100px_150px] items-center border-b border-line px-3 py-2 text-sm hover:bg-bg ${selected ? 'bg-brand-light' : ''}`}>
                <div className="min-w-0">
                  <div className="truncate font-extrabold text-ink">{item.paymentNo}</div>
                  <div className="mt-0.5 flex min-w-0 items-center gap-2 text-xs font-bold text-muted">
                    <span className="truncate">订单 {item.orderNo} · {item.itemSummary || '-'}</span>
                    <Link href={`/admin/orders/${encodeURIComponent(item.orderNo)}`} className="shrink-0 text-brand hover:text-brand-dark" aria-label="查看订单">
                      <ExternalLink className="h-3.5 w-3.5" />
                    </Link>
                  </div>
                </div>
                <span className="truncate text-xs font-bold text-muted">{item.userPhone || '-'}</span>
                <span className="text-xs font-bold text-muted">{item.channel}</span>
                <span className="text-sm font-extrabold text-ink">¥{yuan(item.amount).toLocaleString()}</span>
                <span className="text-xs font-extrabold text-brand">{statusLabel[item.status] || item.status}</span>
                <span className="text-xs font-bold text-muted">{formatDate(item.createdAt)}</span>
              </div>
            )
          })}
        </div>
      </section>
    </AdminShell>
  )
}

export default function AdminPaymentsPage() {
  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>}>
      <AdminPaymentsContent />
    </Suspense>
  )
}
