import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { formatCurrency, formatNumber, formatPercent } from '@/lib/utils'
import { useState, useMemo } from 'react'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'

const PAGE_SIZE = 15

export function RiskPage() {
  const [anomalyPage, setAnomalyPage] = useState(1)
  const [cashierPage, setCashierPage] = useState(1)
  const [zeroPage, setZeroPage] = useState(1)
  const [riskTab, setRiskTab] = useState<'anomaly' | 'zero' | 'cashier'>('anomaly')

  const { data: anomalyData, isLoading: anomalyLoading } = useQuery({
    queryKey: ['risk/anomaly'],
    queryFn: () => api.get('/risk/anomaly'),
  })

  const { data: zeroData, isLoading: zeroLoading } = useQuery({
    queryKey: ['risk/zero-received'],
    queryFn: () => api.get('/risk/zero-received'),
  })

  const { data: cashierData, isLoading: cashierLoading } = useQuery({
    queryKey: ['risk/cashier'],
    queryFn: () => api.get('/risk/cashier'),
  })

  const anomalyRows = (anomalyData as any)?.data || []
  const zeroRows = (zeroData as any)?.data || []
  const cashierRows = (cashierData as any)?.data || []

  const pageLoading = anomalyLoading || zeroLoading || cashierLoading

  const totalAnomaly = anomalyRows.length
  const totalZero = zeroRows.length
  const highRiskCashiers = cashierRows.filter((r: any) => Number(r.anomaly_rate_pct || 0) >= 10).length
  const avgAnomalyRate = cashierRows.length > 0
    ? cashierRows.reduce((s: number, r: any) => s + Number(r.anomaly_rate_pct || 0), 0) / cashierRows.length
    : 0

  const pagedAnomaly = useMemo(() => anomalyRows.slice((anomalyPage - 1) * PAGE_SIZE, anomalyPage * PAGE_SIZE), [anomalyRows, anomalyPage])
  const pagedZero = useMemo(() => zeroRows.slice((zeroPage - 1) * PAGE_SIZE, zeroPage * PAGE_SIZE), [zeroRows, zeroPage])
  const pagedCashier = useMemo(() => cashierRows.slice((cashierPage - 1) * PAGE_SIZE, cashierPage * PAGE_SIZE), [cashierRows, cashierPage])

  const cashierChartData = cashierRows.slice(0, 15)

  if (pageLoading) {
    return <LoadingSpinner text="加载风险数据..." />
  }

  return (
    <div className="space-y-4">
      <div>
        <h1 className="text-xl font-bold">风险与内控管理</h1>
        <p className="mt-0.5 text-xs text-muted-foreground">异常账单 · 零实收 · 收银风险 · 2026年4月</p>
      </div>

      {/* 概览指标 */}
      <CollapsibleSection title="风险概览" subtitle="异常账单与收银操作风险汇总">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="异常账单数" value={totalAnomaly} format="number" description="触发异常规则的账单数量，需逐单核查" />
          <MetricCard title="零实收账单" value={totalZero} format="number" description="实收为0的账单，可能为全额优惠或操作异常" />
          <MetricCard title="高风险收银员(≥10%)" value={highRiskCashiers} format="number" description="异常操作率≥10%的收银员数量" />
          <MetricCard title="平均异常率" value={avgAnomalyRate} format="percent" description="所有收银员的平均异常操作率" />
        </div>
      </CollapsibleSection>

      {/* 收银员风险图 */}
      <CollapsibleSection title="收银员异常率TOP15" subtitle="异常操作率最高的收银员">
        <ResponsiveContainer width="100%" height={250}>
          <BarChart data={cashierChartData} layout="vertical" margin={{ left: 60 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis type="number" unit="%" tick={{ fontSize: 10 }} />
            <YAxis type="category" dataKey="cashier" tick={{ fontSize: 10 }} width={60} />
            <Tooltip formatter={(v: any) => `${Number(v).toFixed(2)}%`} />
            <Bar dataKey="anomaly_rate_pct" fill="#ef4444" name="异常率" />
          </BarChart>
        </ResponsiveContainer>
      </CollapsibleSection>

      {/* 风险明细表 — Tab切换 */}
      <CollapsibleSection title="风险明细" subtitle="异常账单 / 零实收 / 收银员风险">
        <div className="mb-3 flex gap-2">
          <button onClick={() => setRiskTab('anomaly')} className={`rounded-md border px-3 py-1.5 text-sm ${riskTab === 'anomaly' ? 'border-primary bg-primary text-primary-foreground' : ''}`}>
            异常账单 ({totalAnomaly})
          </button>
          <button onClick={() => setRiskTab('zero')} className={`rounded-md border px-3 py-1.5 text-sm ${riskTab === 'zero' ? 'border-primary bg-primary text-primary-foreground' : ''}`}>
            零实收 ({totalZero})
          </button>
          <button onClick={() => setRiskTab('cashier')} className={`rounded-md border px-3 py-1.5 text-sm ${riskTab === 'cashier' ? 'border-primary bg-primary text-primary-foreground' : ''}`}>
            收银员风险 ({cashierRows.length})
          </button>
        </div>

        {riskTab === 'anomaly' && (
          <>
            <Pagination page={anomalyPage} pageSize={PAGE_SIZE} total={anomalyRows.length} onPageChange={setAnomalyPage} />
            <div className="mt-3">
              <DataTable
                columns={[
                  { key: 'store_name', label: '门店' },
                  { key: 'bill_no', label: '账单号' },
                  { key: 'meal_period', label: '餐段' },
                  { key: 'consumption', label: '消费额', align: 'right', render: (r) => formatCurrency(r.consumption) },
                  { key: 'discount_total', label: '优惠', align: 'right', render: (r) => formatCurrency(r.discount_total) },
                  { key: 'received_total', label: '实收', align: 'right', render: (r) => formatCurrency(r.received_total) },
                  { key: 'anomaly_reason', label: '异常原因' },
                  { key: 'closed_at', label: '结账时间', render: (r) => r.closed_at?.substring(0, 16) },
                ]}
                data={pagedAnomaly}
              />
            </div>
          </>
        )}

        {riskTab === 'zero' && (
          <>
            <Pagination page={zeroPage} pageSize={PAGE_SIZE} total={zeroRows.length} onPageChange={setZeroPage} />
            <div className="mt-3">
              <DataTable
                columns={[
                  { key: 'store_name', label: '门店' },
                  { key: 'bill_no', label: '账单号' },
                  { key: 'meal_period', label: '餐段' },
                  { key: 'consumption', label: '消费额', align: 'right', render: (r) => formatCurrency(r.consumption) },
                  { key: 'discount_total', label: '优惠', align: 'right', render: (r) => formatCurrency(r.discount_total) },
                  { key: 'zero_received_type', label: '零实收类型' },
                  { key: 'cashier', label: '收银员' },
                  { key: 'closed_at', label: '结账时间', render: (r) => r.closed_at?.substring(0, 16) },
                ]}
                data={pagedZero}
              />
            </div>
          </>
        )}

        {riskTab === 'cashier' && (
          <>
            <Pagination page={cashierPage} pageSize={PAGE_SIZE} total={cashierRows.length} onPageChange={setCashierPage} />
            <div className="mt-3">
              <DataTable
                columns={[
                  { key: 'cashier', label: '收银员' },
                  { key: 'bill_count', label: '账单数', align: 'right', render: (r) => formatNumber(r.bill_count) },
                  { key: 'received', label: '实收', align: 'right', render: (r) => formatCurrency(r.received) },
                  { key: 'anomaly_bills', label: '异常账单数', align: 'right', render: (r) => formatNumber(r.anomaly_bills) },
                  { key: 'anomaly_rate_pct', label: '异常率', align: 'right', render: (r) => {
                    const v = Number(r.anomaly_rate_pct || 0)
                    return <span className={v >= 10 ? 'font-medium text-red-600' : v >= 5 ? 'text-yellow-600' : 'text-green-600'}>{v.toFixed(2)}%</span>
                  }},
                  { key: 'anomaly_consumption', label: '异常消费额', align: 'right', render: (r) => formatCurrency(r.anomaly_consumption) },
                ]}
                data={pagedCashier}
              />
            </div>
          </>
        )}
      </CollapsibleSection>
    </div>
  )
}
