'use client'

import { useEffect, useMemo, useState } from 'react'
import Link from 'next/link'
import { Download, ExternalLink, RefreshCw, Search } from 'lucide-react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendInvoiceApplication, yuan } from '@/lib/backend'

const statusOptions = [
  { label: '全部状态', value: '' },
  { label: '待开票', value: 'pending' },
  { label: '开票中', value: 'processing' },
  { label: '已开票', value: 'issued' },
  { label: '已驳回', value: 'rejected' },
  { label: '开票失败', value: 'failed' },
]

const statusLabel: Record<string, string> = {
  pending: '待开票',
  processing: '开票中',
  issued: '已开票',
  rejected: '已驳回',
  failed: '开票失败',
}

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

export default function AdminInvoicesPage() {
  const [items, setItems] = useState<BackendInvoiceApplication[]>([])
  const [q, setQ] = useState('')
  const [status, setStatus] = useState('')
  const [from, setFrom] = useState('')
  const [to, setTo] = useState('')
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [exporting, setExporting] = useState(false)
  const [error, setError] = useState('')
  const summary = useMemo(() => items.reduce((result, item) => ({
    count: result.count + 1,
    amount: result.amount + item.amount,
    pending: result.pending + (item.status === 'pending' ? 1 : 0),
  }), { count: 0, amount: 0, pending: 0 }), [items])

  async function reload(next = { q, status, from, to }) {
    setLoading(true)
    try {
      const result = await backend.adminInvoiceApplications(next)
      setItems(result.items || [])
      setTotal(result.total || 0)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '发票申请加载失败')
    } finally {
      setLoading(false)
    }
  }

  async function exportCsv() {
    setExporting(true)
    try {
      const blob = await backend.adminInvoiceApplicationsCsv({ q, status, from, to })
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `发票申请-${new Date().toISOString().slice(0, 10)}.csv`
      link.click()
      URL.revokeObjectURL(url)
    } catch (err) {
      setError(err instanceof Error ? err.message : '发票导出失败')
    } finally {
      setExporting(false)
    }
  }

  useEffect(() => {
    void reload()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return (
    <AdminShell
      title="发票中心"
      description="财务查看用户发票申请，线下开票后回填税票号码并上传 PDF/OFD。"
      topbarMetrics={[
        { label: '当前列表', value: `${summary.count} / ${total}` },
        { label: '申请金额', value: `¥${yuan(summary.amount).toLocaleString()}` },
        { label: '待开票', value: summary.pending },
      ]}
    >
      {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({ q, status, 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={q}
              onChange={(event) => setQ(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>
          <input type="date" value={from} onChange={(event) => setFrom(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) => setTo(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({ q, status: event.target.value, 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 rounded-[4px] bg-ink px-3 text-xs font-extrabold text-white">查询</button>
          <button type="button" onClick={() => void reload({ q, status, from, to })} className="inline-flex h-8 shrink-0 items-center justify-center gap-1.5 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 rounded-[4px] border border-line px-3 text-xs font-bold text-muted hover:border-brand hover:text-brand disabled:opacity-60">
            <Download className="h-4 w-4" />
            {exporting ? '导出中' : '导出 CSV'}
          </button>
        </form>

        <div className="hidden shrink-0 grid-cols-[128px_minmax(280px,1fr)_110px_100px_110px_145px] border-b border-line px-3 py-2 text-xs font-extrabold text-soft xl:grid">
          <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) => (
            <div key={item.id} className="grid gap-2 border-b border-line px-3 py-2 text-sm last:border-b-0 xl:grid-cols-[128px_minmax(280px,1fr)_110px_100px_110px_145px] xl:items-center">
              <Link href={`/admin/invoices/${encodeURIComponent(item.invoiceNo)}`} className="font-extrabold text-brand hover:text-brand-dark">{item.invoiceNo}</Link>
              <div className="min-w-0">
                <div className="truncate font-bold text-ink">{item.title}</div>
                <div className="mt-0.5 flex flex-wrap items-center gap-2 text-xs font-bold text-muted">
                  <span>订单 {item.orderNo}</span>
                  <span>{item.userPhone || '-'}</span>
                  <Link href={`/admin/orders/${encodeURIComponent(item.orderNo)}`} className="text-brand hover:text-brand-dark" aria-label="查看订单">
                    <ExternalLink className="h-3.5 w-3.5" />
                  </Link>
                </div>
              </div>
              <span className="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="truncate text-xs font-bold text-muted">{item.taxNumber || '-'}</span>
              <span className="text-xs font-bold text-muted">{formatDate(item.createdAt)}</span>
            </div>
          ))}
        </div>
      </section>
    </AdminShell>
  )
}
