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 { ChefHat, TrendingDown, TrendingUp, AlertTriangle, Package, Factory } from 'lucide-react'
import { MonthPicker } from '@/components/MonthPicker'

const CATEGORY_COLORS = ['#1677ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96', '#fa8c16', '#a0d911', '#2f54eb']

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

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

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

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

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

  const { summary, reconciliation, products, categoryCost, recipeEfficiency, mfgPool, yieldAnalysis } = data

  // 成本对账瀑布数据
  const waterfallData = [
    { name: '理论成本', value: reconciliation.theoretical_cost, type: 'base' },
    { name: '标准成本', value: reconciliation.standard_cost, type: 'base' },
    { name: '实际材料', value: reconciliation.material_actual_cost, type: 'base' },
    { name: '制造费用', value: reconciliation.allocated_manufacturing_cost, type: 'add' },
    { name: '全制造成本', value: reconciliation.full_manufacturing_cost, type: 'total' },
    { name: '入库价值', value: reconciliation.calculated_inbound_value, type: 'base' },
    { name: '制造毛利', value: reconciliation.manufacturing_margin, type: 'margin' },
  ]

  // 品类成本堆叠数据
  const categoryStackData = categoryCost.map((c: any) => ({
    name: c.category_minor,
    材料成本: c.material_actual_cost,
    制造费用: c.allocated_mfg_cost,
  }))

  // 产品成本偏差散点图
  const scatterData = products.map((p: any) => ({
    name: p.product_name,
    x: p.theoretical_cost,
    y: p.material_actual_cost,
    z: p.efficiency_variance_pct,
    category: p.category_minor,
  })).filter((d: any) => d.x > 0 && d.y > 0)

  return (
    <div className="space-y-4 p-4">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <ChefHat className="h-6 w-6 text-blue-600" />
          <h1 className="text-xl font-bold">中央厨房成本驾驶舱</h1>
        </div>
        <MonthPicker month={month} onChange={setMonth} />
      </div>

      {/* 核心指标卡片 */}
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4 lg:grid-cols-4">
        <MetricCard title="产品数" value={summary.product_count} unit="个" status="good" />
        <MetricCard title="完工入库量" value={summary.total_inbound_qty} unit={products[0]?.unit || ''} format="number" />
        <MetricCard title="理论材料成本" value={summary.theoretical_cost} format="currency" />
        <MetricCard title="实际材料成本" value={summary.material_actual_cost} format="currency" status={varianceColor(summary.efficiency_variance_pct)} />
        <MetricCard title="完整制造成本" value={summary.full_manufacturing_cost} format="currency" />
        <MetricCard title="材料效率差异" value={varianceText(summary.efficiency_variance_pct)} status={varianceColor(summary.efficiency_variance_pct)} description="(实际-理论)/理论×100%" />
        <MetricCard title="制造费用率" value={summary.mfg_cost_rate} unit="%" status={summary.mfg_cost_rate <= 5 ? 'good' : 'warn'} description="制造费用/实际材料成本" />
      </div>

      {/* 成本对账瀑布 */}
      <CollapsibleSection title="成本对账瀑布" subtitle="理论→标准→实际→+制造费用→全成本→入库价值→制造毛利">
        <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-3 lg:grid-cols-3">
          <MetricCard title="理论成本" value={reconciliation.theoretical_cost} format="currency" />
          <MetricCard title="标准成本" value={reconciliation.standard_cost} format="currency" />
          <MetricCard title="实际材料" value={reconciliation.material_actual_cost} format="currency" status={varianceColor(summary.efficiency_variance_pct)} />
          <MetricCard title="制造费用池" value={reconciliation.manufacturing_cost_pool} format="currency" />
          <MetricCard title="全制造成本" value={reconciliation.full_manufacturing_cost} format="currency" />
          <MetricCard title="制造毛利" value={reconciliation.manufacturing_margin} format="currency" status={reconciliation.manufacturing_margin >= 0 ? 'good' : 'bad'} description="入库价值-全制造成本" />
        </div>
        <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" radius={[4, 4, 0, 0]}>
              {waterfallData.map((entry, idx) => (
                <Cell key={idx} fill={
                  entry.type === 'total' ? '#1677ff' :
                  entry.type === 'add' ? '#faad14' :
                  entry.type === 'margin' ? (entry.value >= 0 ? '#52c41a' : '#f5222d') :
                  '#8ec6ff'
                } />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
      </CollapsibleSection>

      {/* 品类成本结构 */}
      <CollapsibleSection title="品类成本结构" subtitle="按品类展示材料成本与制造费用分布">
        <ResponsiveContainer width="100%" height={350}>
          <BarChart data={categoryStackData} 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="材料成本" stackId="a" fill="#1677ff" />
            <Bar dataKey="制造费用" stackId="a" fill="#faad14" />
          </BarChart>
        </ResponsiveContainer>
        <div className="mt-3">
          <FilterableTable
            data={categoryCost}
            filterKey="category_minor"
            filterLabel="全部品类"
            sortOptions={[
              { key: 'theoretical_cost', label: '理论成本' },
              { key: 'material_actual_cost', label: '实际材料' },
              { key: 'allocated_mfg_cost', label: '制造费用' },
              { key: 'full_cost', label: '全成本' },
              { key: 'efficiency_var_pct', label: '效率差异' },
            ]}
            columns={[
              { key: 'category_minor', label: '品类' },
              { key: 'product_count', label: '产品数', align: 'right' },
              { key: 'total_qty', label: '入库量', align: 'right', render: (c) => formatNumber(c.total_qty) },
              { key: 'theoretical_cost', label: '理论成本', align: 'right', render: (c) => formatCurrency(c.theoretical_cost) },
              { key: 'material_actual_cost', label: '实际材料', align: 'right', render: (c) => formatCurrency(c.material_actual_cost) },
              { key: 'allocated_mfg_cost', label: '制造费用', align: 'right', render: (c) => formatCurrency(c.allocated_mfg_cost) },
              { key: 'full_cost', label: '全成本', align: 'right', render: (c) => <span className="font-medium">{formatCurrency(c.full_cost)}</span> },
              { key: 'efficiency_var_pct', label: '效率差异', align: 'right', render: (c) => <span className={`font-medium ${varianceColor(c.efficiency_var_pct) === 'good' ? 'text-green-600' : varianceColor(c.efficiency_var_pct) === 'warn' ? 'text-yellow-600' : 'text-red-600'}`}>{varianceText(c.efficiency_var_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 / 10000).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}</div>
                  <div>品类: {p.category}</div>
                  <div>理论成本: {formatCurrency(p.x)}</div>
                  <div>实际成本: {formatCurrency(p.y)}</div>
                  <div>偏差率: {p.z.toFixed(2)}%</div>
                </div>
              )
            }} />
            <Scatter data={scatterData}>
              {scatterData.map((entry: any, idx: number) => (
                <Cell key={idx} fill={
                  entry.z <= -5 ? '#52c41a' :
                  entry.z >= 5 ? '#f5222d' :
                  entry.z >= 0 ? '#faad14' : '#1677ff'
                } />
              ))}
            </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" /> 节约(≤-5%)</span>
          <span className="flex items-center gap-1"><span className="inline-block h-3 w-3 rounded-full bg-blue-500" /> 正常(-5%~0%)</span>
          <span className="flex items-center gap-1"><span className="inline-block h-3 w-3 rounded-full bg-yellow-500" /> 轻微超耗(0~5%)</span>
          <span className="flex items-center gap-1"><span className="inline-block h-3 w-3 rounded-full bg-red-500" /> 严重超耗(≥5%)</span>
        </div>
      </CollapsibleSection>

      {/* 产品明细表 */}
      <CollapsibleSection
        title="产品成本明细"
        subtitle={`${products.length}个产品`}
      >
        <FilterableTable
          data={products}
          searchKeys={['product_code', 'product_name', 'category_minor']}
          searchPlaceholder="搜索产品名/编码/品类..."
          sortOptions={[
            { key: 'theoretical_cost', label: '理论成本' },
            { key: 'standard_cost', label: '标准成本' },
            { key: 'material_actual_cost', label: '实际材料' },
            { key: 'full_manufacturing_cost', label: '全成本' },
            { key: 'efficiency_variance_pct', label: '效率差异' },
            { key: 'standard_variance_pct', label: '标准差异' },
            { key: 'product_margin', label: '产品毛利' },
            { key: 'inbound_quantity', label: '入库量' },
          ]}
          columns={[
            { key: 'product_code', label: '编码' },
            { key: 'product_name', label: '产品名', render: (p) => <span className="font-medium">{p.product_name}</span> },
            { key: 'category_minor', label: '品类' },
            { key: 'inbound_quantity', label: '入库量', align: 'right', render: (p) => formatNumber(p.inbound_quantity) },
            { key: 'theoretical_cost', label: '理论成本', align: 'right', render: (p) => formatCurrency(p.theoretical_cost) },
            { key: 'standard_cost', label: '标准成本', align: 'right', render: (p) => formatCurrency(p.standard_cost) },
            { key: 'material_actual_cost', label: '实际材料', align: 'right', render: (p) => formatCurrency(p.material_actual_cost) },
            { key: 'allocated_manufacturing_cost', label: '制造费用', align: 'right', render: (p) => formatCurrency(p.allocated_manufacturing_cost) },
            { key: 'full_manufacturing_cost', label: '全成本', align: 'right', render: (p) => <span className="font-medium">{formatCurrency(p.full_manufacturing_cost)}</span> },
            { key: 'full_unit_cost', label: '单位成本', align: 'right', render: (p) => formatNumber(p.full_unit_cost) },
            { key: 'efficiency_variance_pct', label: '效率差异', align: 'right', render: (p) => <span className={`text-xs ${varianceColor(p.efficiency_variance_pct) === 'good' ? 'text-green-600' : varianceColor(p.efficiency_variance_pct) === 'warn' ? 'text-yellow-600' : 'text-red-600'}`}>{varianceText(p.efficiency_variance_pct)}</span> },
            { key: 'standard_variance_pct', label: '标准差异', align: 'right', render: (p) => <span className={`text-xs ${varianceColor(p.standard_variance_pct) === 'good' ? 'text-green-600' : varianceColor(p.standard_variance_pct) === 'warn' ? 'text-yellow-600' : 'text-red-600'}`}>{varianceText(p.standard_variance_pct)}</span> },
            { key: 'inbound_value', label: '入库价值', align: 'right', render: (p) => formatCurrency(p.inbound_value) },
            { key: 'product_margin', label: '产品毛利', align: 'right', render: (p) => <span className={p.product_margin >= 0 ? 'text-green-600' : 'text-red-600'}>{formatCurrency(p.product_margin)}</span> },
          ]}
        />
      </CollapsibleSection>

      {/* 配方效率分析 */}
      <CollapsibleSection title="配方效率分析 TOP20" subtitle="按材料效率差异绝对值排序，识别超耗最严重的配方" defaultOpen={false}>
        <FilterableTable
          data={recipeEfficiency}
          searchKeys={['recipe_name', 'item_name']}
          searchPlaceholder="搜索配方/物料..."
          sortOptions={[
            { key: 'theoretical_amt', label: '理论金额' },
            { key: 'actual_amt', label: '实际金额' },
            { key: 'variance_pct', label: '金额差异率' },
            { key: 'yield_diff', label: '出成差异' },
          ]}
          columns={[
            { key: 'recipe_name', label: '配方', render: (r) => <span className="font-medium">{r.recipe_name}</span> },
            { key: 'item_name', label: '物料' },
            { key: 'specification', label: '规格' },
            { key: 'theoretical_qty', label: '理论用量', align: 'right', render: (r) => formatNumber(r.theoretical_qty) },
            { key: 'actual_qty', label: '实际用量', align: 'right', render: (r) => formatNumber(r.actual_qty) },
            { key: 'theoretical_amt', label: '理论金额', align: 'right', render: (r) => formatCurrency(r.theoretical_amt) },
            { key: 'actual_amt', label: '实际金额', align: 'right', render: (r) => formatCurrency(r.actual_amt) },
            { key: 'variance_pct', label: '金额差异率', align: 'right', render: (r) => <span className={`font-medium ${varianceColor(r.variance_pct) === 'good' ? 'text-green-600' : varianceColor(r.variance_pct) === 'warn' ? 'text-yellow-600' : 'text-red-600'}`}>{varianceText(r.variance_pct)}</span> },
            { key: 'avg_actual_yield', label: '实际出成率', align: 'right', render: (r) => r.avg_actual_yield ? `${(r.avg_actual_yield * 100).toFixed(2)}%` : '-' },
            { key: 'avg_recipe_yield', label: '标准出成率', align: 'right', render: (r) => r.avg_recipe_yield ? `${(r.avg_recipe_yield * 100).toFixed(2)}%` : '-' },
            { key: 'yield_diff', label: '出成差异', align: 'right', render: (r) => <span className={`text-xs ${r.yield_diff < -0.03 ? 'text-red-600' : r.yield_diff > 0.03 ? 'text-green-600' : ''}`}>{r.yield_diff ? `${(r.yield_diff * 100).toFixed(2)}pct` : '-'}</span> },
          ]}
        />
      </CollapsibleSection>

      {/* 出成率分析 */}
      <CollapsibleSection title="出成率分析 TOP20" subtitle="按预期偏差率排序，识别产出异常产品" defaultOpen={false}>
        <FilterableTable
          data={yieldAnalysis}
          searchKeys={['recipe_name', 'product_name']}
          searchPlaceholder="搜索配方/产品..."
          sortOptions={[
            { key: 'theoretical_inbound_qty', label: '理论入库量' },
            { key: 'actual_inbound_qty', label: '实际入库量' },
            { key: 'avg_achievement_rate', label: '达成率' },
            { key: 'avg_expected_var_rate', label: '预期偏差率' },
            { key: 'total_inbound_amt', label: '入库金额' },
            { key: 'return_rate', label: '退库率' },
          ]}
          columns={[
            { key: 'recipe_name', label: '配方', render: (y) => <span className="font-medium">{y.recipe_name}</span> },
            { key: 'product_name', label: '产品名' },
            { key: 'theoretical_inbound_qty', label: '理论入库量', align: 'right', render: (y) => formatNumber(y.theoretical_inbound_qty) },
            { key: 'actual_inbound_qty', label: '实际入库量', align: 'right', render: (y) => formatNumber(y.actual_inbound_qty) },
            { key: 'avg_achievement_rate', label: '达成率', align: 'right', render: (y) => <span className={y.avg_achievement_rate >= 0.95 ? 'text-green-600' : y.avg_achievement_rate >= 0.9 ? 'text-yellow-600' : 'text-red-600'}>{y.avg_achievement_rate ? `${(y.avg_achievement_rate * 100).toFixed(2)}%` : '-'}</span> },
            { key: 'avg_expected_var_rate', label: '预期偏差率', align: 'right', render: (y) => <span className={`text-xs ${y.avg_expected_var_rate < -0.03 ? 'text-red-600' : y.avg_expected_var_rate > 0.03 ? 'text-green-600' : ''}`}>{y.avg_expected_var_rate ? `${(y.avg_expected_var_rate * 100).toFixed(2)}%` : '-'}</span> },
            { key: 'total_inbound_amt', label: '入库金额', align: 'right', render: (y) => formatCurrency(y.total_inbound_amt) },
            { key: 'total_return_qty', label: '退库量', align: 'right', render: (y) => formatNumber(y.total_return_qty) },
            { key: 'return_rate', label: '退库率', align: 'right', render: (y) => <span className={y.return_rate > 1 ? 'text-red-600' : ''}>{y.return_rate ? `${y.return_rate.toFixed(2)}%` : '-'}</span> },
          ]}
        />
      </CollapsibleSection>

      {/* 制造费用池 */}
      <CollapsibleSection title="制造费用池明细" subtitle="制造费用归集与分摊方法" defaultOpen={false}>
        <FilterableTable
          data={mfgPool}
          searchKeys={['cost_type', 'cost_subtype', 'source_type']}
          searchPlaceholder="搜索费用类型/子类/来源..."
          sortOptions={[
            { key: 'source_amount', label: '原始金额' },
            { key: 'allocated_amount', label: '分摊金额' },
          ]}
          columns={[
            { key: 'cost_type', label: '费用类型', render: (m) => <span className="font-medium">{m.cost_type}</span> },
            { key: 'cost_subtype', label: '费用子类' },
            { key: 'source_type', label: '来源' },
            { key: 'source_amount', label: '原始金额', align: 'right', render: (m) => formatCurrency(m.source_amount) },
            { key: 'share_pct', label: '分摊比例', align: 'right', render: (m) => m.share_pct ? `${(m.share_pct * 100).toFixed(2)}%` : '-' },
            { key: 'allocated_amount', label: '分摊金额', align: 'right', render: (m) => <span className="font-medium">{formatCurrency(m.allocated_amount)}</span> },
            { key: 'allocation_method', label: '分摊方法' },
            { key: 'include_in_rebuilt_cost', label: '计入重建', align: 'center', render: (m) => m.include_in_rebuilt_cost ? '✅' : '❌' },
            { key: 'is_provisional', label: '临时', align: 'center', render: (m) => m.is_provisional ? <AlertTriangle className="inline h-4 w-4 text-yellow-500" /> : '' },
            { key: 'note', label: '备注' },
          ]}
        />
        <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>
  )
}
