'use client'

import Link from 'next/link'
import { AlertTriangle, ArrowRight, BarChart3, Clock3, ListChecks, RefreshCw, Search, WalletCards } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { AdminShell } from '@/components/admin/AdminShell'
import { backend, type BackendAdminDashboardSummary, type BackendDashboardListItem, yuan } from '@/lib/backend'

type RangeKey = 'today' | '7d' | '30d'

const rangeOptions: { label: string; value: RangeKey }[] = [
  { label: '今日', value: 'today' },
  { label: '7 天', value: '7d' },
  { label: '30 天', value: '30d' },
]

const statusLabel: Record<string, string> = {
  pending_payment: '待支付',
  paid: '已支付',
  completed: '已完成',
  closed: '已关闭',
  pending_material: '待资料',
  assigned: '已接单',
  in_progress: '处理中',
  pending_confirm: '待确认',
  open: '待处理',
  acknowledged: '处理中',
  resolved: '已解决',
  ignored: '已忽略',
}

function formatDate(value?: string | null) {
  if (!value) return '-'
  return new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}

function formatAmount(cents?: number) {
  return `¥${yuan(Number(cents || 0)).toLocaleString()}`
}

function formatMetric(value: number, valueType?: string) {
  if (valueType === 'money') return formatAmount(value)
  return Number(value || 0).toLocaleString()
}

function toneClass(tone?: string) {
  if (tone === 'danger') return 'border-red-200 bg-red-50 text-red-700'
  if (tone === 'warning') return 'border-amber-200 bg-amber-50 text-amber-700'
  return 'border-line bg-white text-ink'
}

function CompactItem({ item, showAmount = false }: { item: BackendDashboardListItem; showAmount?: boolean }) {
  const body = (
    <div className="grid min-w-0 grid-cols-[96px_minmax(0,1fr)_78px] items-center gap-3 px-3 py-2 text-left text-xs hover:bg-bg">
      <div className="min-w-0">
        <div className="truncate font-extrabold text-ink">{item.title || item.key}</div>
        <div className="mt-0.5 text-[11px] font-bold text-brand">{item.label}</div>
      </div>
      <div className="min-w-0">
        <div className="truncate font-bold text-muted">{item.description || '-'}</div>
        <div className="mt-0.5 text-[11px] text-soft">{formatDate(item.updatedAt || item.createdAt)}</div>
      </div>
      <div className="text-right">
        {showAmount && <div className="font-extrabold text-brand">{formatAmount(item.amount)}</div>}
        <div className="text-[11px] font-bold text-muted">{statusLabel[item.status || ''] || item.status || '-'}</div>
      </div>
    </div>
  )
  if (!item.href) return body
  return <Link href={item.href}>{body}</Link>
}

export default function AdminPage() {
  const [range, setRange] = useState<RangeKey>('7d')
  const [summary, setSummary] = useState<BackendAdminDashboardSummary | null>(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  async function reload(nextRange = range) {
    setLoading(true)
    try {
      const result = await backend.adminDashboardSummary({ range: nextRange })
      setSummary(result)
      setError('')
    } catch (err) {
      setError(err instanceof Error ? err.message : '经营看板加载失败')
    } finally {
      setLoading(false)
    }
  }

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

  const criticalRiskCount = useMemo(() => summary?.risks.filter((item) => ['critical', 'error'].includes(item.severity)).length || 0, [summary])

  return (
    <AdminShell title="经营看板" description="总览交易、受理、履约、财务和异常，先看风险，再进单据处理。">
      <div className="flex h-[calc(100vh-88px)] flex-col gap-2 overflow-hidden">
        <div className="flex shrink-0 flex-wrap items-center justify-between gap-2">
          <div className="inline-flex overflow-hidden rounded-[4px] border border-line bg-white">
            {rangeOptions.map((item) => (
              <button
                key={item.value}
                type="button"
                onClick={() => setRange(item.value)}
                className={`h-7 px-3 text-xs font-extrabold ${range === item.value ? 'bg-ink text-white' : 'text-muted hover:bg-bg hover:text-ink'}`}
              >
                {item.label}
              </button>
            ))}
          </div>
          <div className="flex items-center gap-2">
            <Link href="/admin/search" className="inline-flex h-7 items-center gap-1.5 rounded-[4px] border border-line bg-white px-2.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">
              <Search className="h-3.5 w-3.5" />
              编号搜索
            </Link>
            <button type="button" onClick={() => void reload()} className="inline-flex h-7 items-center gap-1.5 rounded-[4px] border border-line bg-white px-2.5 text-xs font-bold text-muted hover:border-brand hover:text-brand">
              <RefreshCw className={`h-3.5 w-3.5 ${loading ? 'animate-spin' : ''}`} />
              刷新
            </button>
          </div>
        </div>

        {error && <div className="shrink-0 rounded-[4px] border border-red-200 bg-red-50 px-3 py-2 text-xs font-bold text-red-700">{error}</div>}

        <section className="shrink-0 border border-line bg-white px-2 py-1.5">
          {summary ? (
            <div className="grid divide-y divide-line md:grid-cols-3 md:divide-x md:divide-y-0 xl:grid-cols-6">
              {summary.metrics.map((item) => (
                <Link key={item.key} href={item.href || '#'} className="min-w-0 px-2.5 py-1 hover:bg-bg">
                  <div className="flex items-center justify-between gap-2 text-[11px] font-bold text-muted">
                    <span className="truncate">{item.label}</span>
                    {item.key.includes('Settlement') ? <WalletCards className="h-3.5 w-3.5 shrink-0 text-brand" /> : item.key.includes('Exception') ? <AlertTriangle className="h-3.5 w-3.5 shrink-0 text-red-600" /> : <BarChart3 className="h-3.5 w-3.5 shrink-0 text-brand" />}
                  </div>
                  <div className="mt-0.5 truncate text-base font-extrabold text-ink">{formatMetric(item.value, item.valueType)}</div>
                  <div className="truncate text-[11px] font-bold text-soft">{item.helper || summary.range.label}</div>
                </Link>
              ))}
            </div>
          ) : !error ? (
            <div className="px-3 py-6 text-center text-xs font-bold text-muted">正在加载经营数据...</div>
          ) : null}
        </section>

        <section className="grid min-h-0 flex-[0.9] gap-2 xl:grid-cols-[minmax(0,1.2fr)_340px]">
          <div className="flex min-h-0 flex-col border border-line bg-white">
          <div className="flex h-9 items-center justify-between border-b border-line px-3">
            <h2 className="text-sm font-extrabold text-ink">业务线状态</h2>
            <span className="text-[11px] font-bold text-soft">{summary?.range.label || '-'}</span>
          </div>
          <div className="grid grid-cols-[1.1fr_70px_70px_70px_70px_28px] border-b border-line px-3 py-2 text-[11px] font-extrabold text-soft">
            <span>业务</span><span>总量</span><span>待办</span><span>处理中</span><span>完成</span><span />
          </div>
          <div className="min-h-0 flex-1 overflow-auto">
            {(summary?.businessLines || []).map((line) => (
              <Link key={line.key} href={line.href || '#'} className="grid grid-cols-[1.1fr_70px_70px_70px_70px_28px] items-center border-b border-line px-3 py-1.5 text-xs hover:bg-bg">
                <span className="font-extrabold text-ink">{line.label}</span>
                <span className="font-bold text-muted">{line.total.toLocaleString()}</span>
                <span className={line.pending > 0 ? 'font-extrabold text-amber-700' : 'font-bold text-muted'}>{line.pending.toLocaleString()}</span>
                <span className="font-bold text-muted">{line.activeType === 'money' ? formatAmount(line.active) : line.active.toLocaleString()}</span>
                <span className="font-bold text-muted">{line.completed.toLocaleString()}</span>
                <ArrowRight className="h-3.5 w-3.5 text-soft" />
              </Link>
            ))}
            {summary?.businessLines.length === 0 && <div className="px-3 py-8 text-center text-xs font-bold text-muted">当前账号没有可展示的业务线权限</div>}
          </div>
        </div>

        <aside className="flex min-h-0 flex-col border border-line bg-white">
          <div className="flex h-9 items-center justify-between border-b border-line px-3">
            <h2 className="text-sm font-extrabold text-ink">待办队列</h2>
            <ListChecks className="h-4 w-4 text-brand" />
          </div>
          <div className="min-h-0 flex-1 overflow-auto p-2">
            <div className="grid gap-1.5">
            {(summary?.workQueues || []).slice(0, 8).map((item) => (
              <Link key={item.key} href={item.href || '#'} className={`grid grid-cols-[1fr_auto] gap-2 rounded-[4px] border px-2.5 py-1.5 text-xs hover:border-brand ${toneClass(item.tone)}`}>
                <span className="min-w-0">
                  <span className="block truncate font-extrabold">{item.label}</span>
                  <span className="mt-0.5 block truncate text-[11px] opacity-75">{item.description || '-'}</span>
                </span>
                <span className="text-lg font-extrabold">{item.count}</span>
              </Link>
            ))}
            {summary?.workQueues.length === 0 && <div className="px-3 py-8 text-center text-xs font-bold text-muted">暂无待办</div>}
            </div>
          </div>
        </aside>
      </section>

        <section className="grid min-h-0 flex-1 gap-2 xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)_340px]">
          <div className="flex min-h-0 flex-col border border-line bg-white">
          <div className="flex h-9 items-center justify-between border-b border-line px-3">
            <h2 className="text-sm font-extrabold text-ink">最近订单</h2>
            <span className="text-[11px] font-bold text-soft">{summary?.recentOrders.length || 0} 条</span>
          </div>
          <div className="min-h-0 flex-1 divide-y divide-line overflow-auto">
            {(summary?.recentOrders || []).map((item) => <CompactItem key={item.key} item={item} showAmount />)}
            {summary?.recentOrders.length === 0 && <div className="px-3 py-8 text-center text-xs font-bold text-muted">暂无订单</div>}
          </div>
        </div>

        <div className="flex min-h-0 flex-col border border-line bg-white">
          <div className="flex h-9 items-center justify-between border-b border-line px-3">
            <h2 className="text-sm font-extrabold text-ink">交付队列</h2>
            <Clock3 className="h-4 w-4 text-brand" />
          </div>
          <div className="min-h-0 flex-1 divide-y divide-line overflow-auto">
            {(summary?.fulfillmentQueue || []).map((item) => <CompactItem key={item.key} item={item} />)}
            {summary?.fulfillmentQueue.length === 0 && <div className="px-3 py-8 text-center text-xs font-bold text-muted">暂无交付任务</div>}
          </div>
        </div>

        <aside className="flex min-h-0 flex-col border border-line bg-white">
          <div className="flex h-9 items-center justify-between border-b border-line px-3">
            <h2 className="text-sm font-extrabold text-ink">风险事件</h2>
            <span className={criticalRiskCount > 0 ? 'text-xs font-extrabold text-red-700' : 'text-xs font-bold text-soft'}>{criticalRiskCount} 个高危</span>
          </div>
          <div className="min-h-0 flex-1 divide-y divide-line overflow-auto">
            {(summary?.risks || []).slice(0, 8).map((item) => (
              <Link key={item.id} href={item.linkedHref || '/admin/exceptions'} className="block px-3 py-2 text-xs hover:bg-bg">
                <div className="flex items-center justify-between gap-2">
                  <span className={`font-extrabold ${['critical', 'error'].includes(item.severity) ? 'text-red-700' : 'text-amber-700'}`}>{item.severity}</span>
                  <span className="font-bold text-muted">{statusLabel[item.status] || item.status}</span>
                </div>
                <div className="mt-1 truncate font-extrabold text-ink">{item.message || item.eventType}</div>
                <div className="mt-0.5 truncate text-[11px] font-bold text-soft">{item.resourceType || '-'} {item.resourceId || ''}</div>
              </Link>
            ))}
            {summary?.risks.length === 0 && <div className="px-3 py-8 text-center text-xs font-bold text-muted">暂无风险事件</div>}
          </div>
        </aside>
      </section>
      </div>
    </AdminShell>
  )
}
