import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell, ScatterChart, Scatter } from 'recharts'
import api from '@/lib/api'
import { MetricCard } from '@/components/MetricCard'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { FilterableTable } from '@/components/FilterableTable'
import { formatNumber, formatCurrency, formatPercent } from '@/lib/utils'
import { Truck, AlertTriangle, PackageSearch, BarChart3 } from 'lucide-react'
import { MonthPicker } from '@/components/MonthPicker'

function varianceStatus(pct: number): 'good' | 'warn' | 'bad' {
  if (Math.abs(pct) <= 3) return 'good'
  if (Math.abs(pct) <= 10) return 'warn'
  return 'bad'
}

function varianceColorClass(pct: number): string {
  const s = varianceStatus(pct)
  return s === 'good' ? 'text-green-600' : s === 'warn' ? 'text-yellow-600' : 'text-red-600'
}

function varianceText(pct: number): string {
  if (pct > 0) return `+${pct.toFixed(2)}%`
  return `${pct.toFixed(2)}%`
}

export function DistributionReconciliationPage() {
  const [month, setMonth] = useState('2026-04')

  const { data, isLoading } = useQuery({
    queryKey: ['distribution-reconciliation', month],
    queryFn: async () => {
      const res = await api.get(`/distribution/reconciliation?month=${month}`)
      return res.data
    },
  })

  if (isLoading) return <LoadingSpinner />
  if (!data) return <div className="p-4 text-muted-foreground">暂无数据</div>

  const { summary, storeReconciliation, topVariances, unmatchedItems, categoryReconciliation } = data

  // 倒挤公式瀑布数据
  const waterfallData = [
    { name: '期初库存', value: summary.total_opening_amt, type: 'base' },
    { name: '配送入库', value: summary.total_dist_amt, type: 'add' },
    { name: '应耗用(倒挤)', value: summary.reverse_consumption_amt, type: 'calc' },
    { name: '实际耗用', value: summary.total_consumption_amt, type: 'actual' },
    { name: '期末库存', value: summary.total_ending_amt, type: 'base' },
    { name: '差异金额', value: summary.variance_amt, type: 'variance' },
  ]

  // 品类对账柱状图
  const categoryChartData = categoryReconciliation.slice(0, 15).map((c: any) => ({
    name: c.minor_category,
    配送金额: c.dist_amt,
    耗用金额: c.consumption_amt,
    期末库存: c.ending_amt,
  }))

  // 门店散点图：配送金额 vs 差异率
  const storeScatterData = storeReconciliation
    .filter((s: any) => s.dist_amt > 0 && s.consumption_amt > 0)
    .map((s: any) => ({
      name: s.store_name || s.store_code,
      x: s.dist_amt,
      y: s.variance_pct,
      store_code: s.store_code,
    }))

  return (
    <div className="space-y-4 p-4">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Truck className="h-6 w-6 text-blue-600" />
          <h1 className="text-xl font-bold">配送—倒挤成本对账</h1>
        </div>
        <MonthPicker month={month} onChange={setMonth} />
      </div>

      {/* 公式说明 */}
      <div className="rounded-lg border bg-blue-50/40 p-3 text-sm text-blue-800">
        <strong>倒挤公式：</strong> 应耗用成本 = 期初库存 + 配送入库 - 期末库存 ｜ 差异 = 实际耗用 - 应耗用(倒挤) ｜ 差异率 = 差异 / 实际耗用 × 100%
      </div>

      {/* 核心指标 */}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4 lg:grid-cols-7">
        <MetricCard title="对账品项行" value={summary.total_lines} unit="行" description="配送+库存合并去重后的品项行数" />
        <MetricCard title="匹配行数" value={summary.matched_lines} unit="行" status="good" description="配送和库存都有数据的行数" />
        <MetricCard title="配送总额" value={summary.total_dist_amt} format="currency" />
        <MetricCard title="实际耗用" value={summary.total_consumption_amt} format="currency" />
        <MetricCard title="倒挤应耗用" value={summary.reverse_consumption_amt} format="currency" description="期初+配送-期末" />
        <MetricCard title="差异金额" value={summary.variance_amt} format="currency" status={summary.variance_amt >= 0 ? 'warn' : 'bad'} />
        <MetricCard title="差异率" value={varianceText(summary.variance_pct)} status={varianceStatus(summary.variance_pct)} />
      </div>

      {/* 倒挤对账瀑布 */}
      <CollapsibleSection title="倒挤成本对账瀑布" subtitle="期初库存 + 配送入库 - 期末库存 = 应耗用 vs 实际耗用">
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={waterfallData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="name" tick={{ fontSize: 11 }} />
            <YAxis tickFormatter={(v) => `${(v / 10000).toFixed(0)}万`} tick={{ fontSize: 11 }} />
            <Tooltip formatter={(v: any) => [formatCurrency(v), '金额']} />
            <Bar dataKey="value" name="金额" radius={[4, 4, 0, 0]}>
              {waterfallData.map((entry, idx) => (
                <Cell key={idx} fill={
                  entry.type === 'add' ? '#52c41a' :
                  entry.type === 'calc' ? '#1677ff' :
                  entry.type === 'actual' ? '#722ed1' :
                  entry.type === 'variance' ? (entry.value >= 0 ? '#faad14' : '#f5222d') :
                  '#8ec6ff'
                } />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </CollapsibleSection>

      {/* 品类维度对账 */}
      <CollapsibleSection title="品类维度对账" subtitle="按小类汇总配送金额与耗用金额">
        <ResponsiveContainer width="100%" height={350}>
          <BarChart data={categoryChartData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="name" tick={{ fontSize: 10 }} angle={-20} textAnchor="end" height={60} />
            <YAxis tickFormatter={(v) => `${(v / 10000).toFixed(0)}万`} tick={{ fontSize: 11 }} />
            <Tooltip formatter={(v: any) => formatCurrency(v)} />
            <Bar dataKey="配送金额" fill="#1677ff" />
            <Bar dataKey="耗用金额" fill="#722ed1" />
            <Bar dataKey="期末库存" fill="#faad14" />
          </BarChart>
        </ResponsiveContainer>
        <div className="mt-3">
          <FilterableTable
            data={categoryReconciliation}
            filterKey="minor_category"
            filterLabel="全部分类"
            sortOptions={[
              { key: 'dist_amt', label: '配送金额' },
              { key: 'consumption_amt', label: '耗用金额' },
              { key: 'ending_amt', label: '期末库存' },
              { key: 'variance_amt', label: '差异金额' },
              { key: 'variance_pct', label: '差异率' },
            ]}
            columns={[
              { key: 'minor_category', label: '品类' },
              { key: 'item_count', label: '品项数', align: 'right' },
              { key: 'dist_qty', label: '配送量', align: 'right', render: (c) => formatNumber(c.dist_qty) },
              { key: 'dist_amt', label: '配送金额', align: 'right', render: (c) => formatCurrency(c.dist_amt) },
              { key: 'dist_cost_excl_tax', label: '不含税成本', align: 'right', render: (c) => formatCurrency(c.dist_cost_excl_tax) },
              { key: 'consumption_amt', label: '耗用金额', align: 'right', render: (c) => formatCurrency(c.consumption_amt) },
              { key: 'ending_amt', label: '期末库存', align: 'right', render: (c) => formatCurrency(c.ending_amt) },
              { key: 'variance_amt', label: '差异金额', align: 'right', render: (c) => <span className={c.variance_amt >= 0 ? 'text-yellow-600' : 'text-red-600'}>{formatCurrency(c.variance_amt)}</span> },
              { key: 'variance_pct', label: '差异率', align: 'right', render: (c) => <span className={`font-medium ${varianceColorClass(c.variance_pct)}`}>{varianceText(c.variance_pct)}</span> },
            ]}
          />
        </div>
      </CollapsibleSection>

      {/* 门店差异散点图 */}
      <CollapsibleSection title="门店差异散点图" subtitle="X=配送金额，Y=差异率%" defaultOpen={false}>
        <ResponsiveContainer width="100%" height={350}>
          <ScatterChart margin={{ top: 20, right: 30, left: 20, bottom: 10 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis type="number" dataKey="x" name="配送金额" tickFormatter={(v) => `${(v / 10000).toFixed(0)}万`} tick={{ fontSize: 11 }} label={{ value: '配送金额', position: 'insideBottom', offset: -5, fontSize: 11 }} />
            <YAxis type="number" dataKey="y" name="差异率%" tickFormatter={(v) => `${v.toFixed(0)}%`} tick={{ fontSize: 11 }} label={{ value: '差异率%', angle: -90, position: 'insideLeft', fontSize: 11 }} />
            <Tooltip cursor={{ strokeDasharray: '3 3' }} content={({ active, payload }: any) => {
              if (!active || !payload?.length) return null
              const p = payload[0].payload
              return (
                <div className="rounded border bg-white px-3 py-2 text-xs shadow">
                  <div className="font-medium">{p.name} ({p.store_code})</div>
                  <div>配送金额: {formatCurrency(p.x)}</div>
                  <div>差异率: {p.y.toFixed(2)}%</div>
                </div>
              )
            }} />
            <Scatter data={storeScatterData}>
              {storeScatterData.map((entry: any, idx: number) => (
                <Cell key={idx} fill={
                  Math.abs(entry.y) <= 3 ? '#52c41a' :
                  Math.abs(entry.y) <= 10 ? '#faad14' :
                  '#f5222d'
                } />
              ))}
            </Scatter>
          </ScatterChart>
        </ResponsiveContainer>
        <div className="mt-2 flex gap-4 text-xs text-muted-foreground">
          <span className="flex items-center gap-1"><span className="inline-block h-3 w-3 rounded-full bg-green-500" /> 正常(±3%)</span>
          <span className="flex items-center gap-1"><span className="inline-block h-3 w-3 rounded-full bg-yellow-500" /> 关注(3~10%)</span>
          <span className="flex items-center gap-1"><span className="inline-block h-3 w-3 rounded-full bg-red-500" /> 异常(&gt;10%)</span>
        </div>
      </CollapsibleSection>

      {/* 门店对账明细 */}
      <CollapsibleSection
        title="门店对账明细"
        subtitle={`${storeReconciliation.length}家门店`}
      >
        <FilterableTable
          data={storeReconciliation}
          searchKeys={['store_code', 'store_name']}
          searchPlaceholder="搜索门店编码/名称..."
          sortOptions={[
            { key: 'dist_amt', label: '配送金额' },
            { key: 'dist_cost_excl_tax', label: '不含税成本' },
            { key: 'opening_amt', label: '期初库存' },
            { key: 'consumption_amt', label: '实际耗用' },
            { key: 'ending_amt', label: '期末库存' },
            { key: 'reverse_consumption_amt', label: '倒挤应耗用' },
            { key: 'variance_amt', label: '差异金额' },
            { key: 'variance_pct', label: '差异率' },
            { key: 'neg_inventory_count', label: '负库存' },
          ]}
          columns={[
            { key: 'store_code', label: '门店编码' },
            { key: 'store_name', label: '门店名称', render: (s) => s.store_name || '-' },
            { key: 'dist_amt', label: '配送金额', align: 'right', render: (s) => formatCurrency(s.dist_amt) },
            { key: 'dist_cost_excl_tax', label: '不含税成本', align: 'right', render: (s) => formatCurrency(s.dist_cost_excl_tax) },
            { key: 'opening_amt', label: '期初库存', align: 'right', render: (s) => formatCurrency(s.opening_amt) },
            { key: 'consumption_amt', label: '实际耗用', align: 'right', render: (s) => formatCurrency(s.consumption_amt) },
            { key: 'ending_amt', label: '期末库存', align: 'right', render: (s) => formatCurrency(s.ending_amt) },
            { key: 'reverse_consumption_amt', label: '倒挤应耗用', align: 'right', render: (s) => formatCurrency(s.reverse_consumption_amt) },
            { key: 'variance_amt', label: '差异金额', align: 'right', render: (s) => <span className={s.variance_amt >= 0 ? 'text-yellow-600' : 'text-red-600'}>{formatCurrency(s.variance_amt)}</span> },
            { key: 'variance_pct', label: '差异率', align: 'right', render: (s) => <span className={`font-medium ${varianceColorClass(s.variance_pct)}`}>{varianceText(s.variance_pct)}</span> },
            { key: 'neg_inventory_count', label: '负库存', align: 'right', render: (s) => <span className={s.neg_inventory_count > 0 ? 'text-red-600 font-medium' : ''}>{s.neg_inventory_count > 0 ? s.neg_inventory_count : '-'}</span> },
          ]}
        />
      </CollapsibleSection>

      {/* Top差异品项 */}
      <CollapsibleSection title="Top30差异品项" subtitle="按差异金额绝对值排序" defaultOpen={false}>
        <FilterableTable
          data={topVariances}
          filterKey="item_name"
          filterLabel="全部品项"
          sortOptions={[
            { key: 'dist_amt', label: '配送金额' },
            { key: 'consumption_amt', label: '实际耗用' },
            { key: 'variance_amt', label: '差异金额' },
            { key: 'variance_pct', label: '差异率' },
          ]}
          columns={[
            { key: 'store_code', label: '门店' },
            { key: 'item_code', label: '品项编码' },
            { key: 'item_name', label: '品项名称' },
            { key: 'minor_category', label: '品类' },
            { key: 'dist_qty', label: '配送量', align: 'right', render: (v) => formatNumber(v.dist_qty) },
            { key: 'dist_amt', label: '配送金额', align: 'right', render: (v) => formatCurrency(v.dist_amt) },
            { key: 'opening_amt', label: '期初', align: 'right', render: (v) => formatCurrency(v.opening_amt) },
            { key: 'consumption_amt', label: '实际耗用', align: 'right', render: (v) => formatCurrency(v.consumption_amt) },
            { key: 'ending_amt', label: '期末', align: 'right', render: (v) => formatCurrency(v.ending_amt) },
            { key: 'reverse_consumption_amt', label: '倒挤应耗用', align: 'right', render: (v) => formatCurrency(v.reverse_consumption_amt) },
            { key: 'variance_amt', label: '差异金额', align: 'right', render: (v) => <span className={`font-medium ${v.variance_amt >= 0 ? 'text-yellow-600' : 'text-red-600'}`}>{formatCurrency(v.variance_amt)}</span> },
            { key: 'variance_pct', label: '差异率', align: 'right', render: (v) => <span className={varianceColorClass(v.variance_pct)}>{varianceText(v.variance_pct)}</span> },
          ]}
        />
      </CollapsibleSection>

      {/* 未匹配品项 */}
      <CollapsibleSection title="未匹配品项（有配送无库存耗用）" subtitle="配送系统有发货但库存系统无耗用记录" defaultOpen={false}>
        <FilterableTable
          data={unmatchedItems}
          filterKey="item_name"
          filterLabel="全部品项"
          sortOptions={[
            { key: 'dist_amt', label: '配送金额' },
            { key: 'dist_qty', label: '配送量' },
            { key: 'store_count', label: '涉及门店数' },
          ]}
          columns={[
            { key: 'item_code', label: '品项编码' },
            { key: 'item_name', label: '品项名称' },
            { key: 'minor_category', label: '品类' },
            { key: 'dist_qty', label: '配送量', align: 'right', render: (u) => formatNumber(u.dist_qty) },
            { key: 'dist_amt', label: '配送金额', align: 'right', render: (u) => formatCurrency(u.dist_amt) },
            { key: 'store_count', label: '涉及门店数', align: 'right' },
          ]}
        />
        <div className="mt-3 flex items-center gap-2 rounded-md bg-yellow-50 p-3 text-xs text-yellow-800">
          <AlertTriangle className="h-4 w-4 flex-shrink-0" />
          <span>这些品项在配送系统有发货记录，但在库存系统中无对应的耗用数据，可能存在编码不一致、未入库或数据缺失等问题。</span>
        </div>
      </CollapsibleSection>
    </div>
  )
}
