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

const PAGE_SIZE = 15

export function SupplyTab({ month }: { month: string }) {
  const [riskPage, setRiskPage] = useState(1)
  const [demandPage, setDemandPage] = useState(1)
  const [skuInput, setSkuInput] = useState('')
  const [simResult, setSimResult] = useState<any>(null)
  const [simLoading, setSimLoading] = useState(false)
  const [riskSort, setRiskSort] = useState('sales_amount')
  const [riskOrder, setRiskOrder] = useState<'asc' | 'desc'>('asc')
  const [riskFilter, setRiskFilter] = useState('')
  const [demandSort, setDemandSort] = useState('estimated_demand')
  const [demandOrder, setDemandOrder] = useState<'asc' | 'desc'>('desc')

  const { data: sharing, isLoading: l1 } = useQuery({ queryKey: ['ca/material-sharing', month], queryFn: () => api.get('/cost-analysis/material-sharing', { params: { month, limit: 30 } }) })
  const { data: risk, isLoading: l2 } = useQuery({ queryKey: ['ca/unique-material-risk', month, riskPage, riskSort, riskOrder, riskFilter], queryFn: () => api.get(`/cost-analysis/unique-material-risk`, { params: { month, page: riskPage, page_size: PAGE_SIZE, sort: riskSort, order: riskOrder, filter: riskFilter } }) })
  const { data: demand, isLoading: l3 } = useQuery({ queryKey: ['ca/material-demand', month], queryFn: () => api.get('/cost-analysis/material-demand', { params: { month, limit: 100 } }) })

  if (l1 || l2 || l3) return <LoadingSpinner text="加载供应链数据..." />

  const sharingData = (sharing as any)?.data || []
  const riskData = (risk as any)?.data || []
  const riskMeta = (risk as any)?.meta || { total: 0 }
  const rawDemandData = (demand as any)?.data || []

  const sharingColor = (type: string) => {
    if (type === '核心原料') return 'bg-red-100 text-red-700'
    if (type === '独有原料') return 'bg-gray-100 text-gray-700'
    return 'bg-blue-100 text-blue-700'
  }

  const riskLevelColor = (level: string) => {
    if (level === '高') return 'bg-red-100 text-red-700'
    if (level === '中') return 'bg-orange-100 text-orange-700'
    return 'bg-green-100 text-green-700'
  }

  const handleSimulate = async () => {
    const codes = skuInput.split(/[,\n\s]+/).filter(Boolean)
    if (codes.length === 0) return
    setSimLoading(true)
    try {
      const res: any = await api.post('/cost-analysis/sku-simplify-simulate', { sku_codes: codes })
      setSimResult(res.data)
    } catch (e) {
      setSimResult({ error: '模拟失败' })
    }
    setSimLoading(false)
  }

  return (
    <div className="space-y-4">
      <CollapsibleSection title="原料共用度" subtitle="被大量SKU共用的核心原料 vs 独有原料">
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={sharingData} layout="vertical" margin={{ left: 80 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis type="number" tick={{ fontSize: 10 }} />
            <YAxis type="category" dataKey="material_name" tick={{ fontSize: 9 }} width={80} />
            <Tooltip content={({ active, payload }: any) => {
              if (active && payload?.length) {
                const d = payload[0].payload
                return <div className="rounded border bg-card p-2 text-xs shadow-sm">
                  <p className="font-medium">{d.material_name}</p>
                  <p>被 {d.sku_count} 个SKU使用</p>
                  <p>类型: {d.sharing_type}</p>
                </div>
              }
              return null
            }} />
            <Bar dataKey="sku_count" name="被引用SKU数">
              {sharingData.map((d: any, i: number) => (
                <Cell key={i} fill={d.sharing_type === '核心原料' ? '#ef4444' : d.sharing_type === '独有原料' ? '#a3a3a3' : '#3b82f6'} />
              ))}
            </Bar>
          </BarChart>
        </ResponsiveContainer>
        <div className="mt-3">
          <FilterableTable
            data={sharingData}
            sortOptions={[
              { key: 'sku_count', label: '被引用SKU数' },
              { key: 'material_name', label: '物料名' },
            ]}
            defaultSort="sku_count"
            defaultOrder="desc"
            filterKey="sharing_type"
            filterLabel="全部分类"
            columns={[
              { key: 'material_name', label: '物料' },
              { key: 'major_category', label: '类型', align: 'center' },
              { key: 'sku_count', label: '被引用SKU数', align: 'right', render: (r) => formatNumber(r.sku_count) },
              { key: 'sharing_type', label: '分类', render: (r) => (
                <span className={`rounded px-2 py-0.5 text-xs font-medium ${sharingColor(r.sharing_type)}`}>{r.sharing_type}</span>
              )},
            ]}
          />
        </div>
      </CollapsibleSection>

      <CollapsibleSection title="独有原料风险" subtitle="低收入SKU占用专用原料">
        <FilterableTable
          data={riskData}
          serverSide
          page={riskPage}
          onPageChange={setRiskPage}
          sort={riskSort}
          onSortChange={setRiskSort}
          order={riskOrder}
          onOrderChange={setRiskOrder}
          filter={riskFilter}
          onFilterChange={setRiskFilter}
          pageSize={PAGE_SIZE}
          total={riskMeta.total}
          filterButtons={[
            { key: '', label: '全部' },
            { key: 'high_risk', label: '高风险' },
            { key: 'low_sales', label: '低销售额' },
          ]}
          sortOptions={[
            { key: 'sales_amount', label: '销售额' },
            { key: 'unique_material_count', label: '独有原料数' },
          ]}
          defaultSort="sales_amount"
          defaultOrder="asc"
          columns={[
            { key: 'sku_code', label: 'SKU编码' },
            { key: 'dish_name', label: '菜品名' },
            { key: 'category_l1', label: '品类' },
            { key: 'sales_amount', label: '销售额', align: 'right', render: (r) => formatCurrency(r.sales_amount) },
            { key: 'unique_material_count', label: '独有原料数', align: 'right', render: (r) => <span className={r.unique_material_count > 3 ? 'text-red-600' : ''}>{formatNumber(r.unique_material_count)}</span> },
            { key: 'risk_level', label: '风险等级', render: (r) => (
              <span className={`rounded px-2 py-0.5 text-xs font-medium ${riskLevelColor(r.risk_level)}`}>{r.risk_level}</span>
            )},
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="SKU精简模拟器" subtitle="输入SKU编码模拟下架影响" defaultOpen={false}>
        <div className="mb-3 flex flex-col gap-2">
          <textarea
            value={skuInput}
            onChange={(e) => setSkuInput(e.target.value)}
            placeholder="输入SKU编码，逗号或换行分隔，如: 66920, 12051, 51040"
            className="rounded border px-3 py-2 text-sm w-full h-20"
          />
          <button onClick={handleSimulate} disabled={simLoading} className="self-start rounded bg-primary px-4 py-2 text-sm text-primary-foreground disabled:opacity-50">
            {simLoading ? '模拟中...' : '模拟下架影响'}
          </button>
        </div>
        {simResult && !simResult.error && (
          <>
            <div className="grid grid-cols-2 gap-3 md:grid-cols-3 mb-3">
              <MetricCard title="收入影响" value={simResult.summary?.revenue_impact} format="currency" />
              <MetricCard title="毛利影响" value={simResult.summary?.profit_impact} format="currency" />
              <MetricCard title="可减少原料数" value={simResult.summary?.releasable_materials} format="number" />
              <MetricCard title="仍需采购的共用原料" value={simResult.summary?.shared_materials} format="number" />
              <MetricCard title="负毛利菜品数" value={simResult.summary?.negative_margin_count} format="number" />
            </div>
            {simResult.releasable_materials?.length > 0 && (
              <FilterableTable
                data={simResult.releasable_materials}
                sortOptions={[
                  { key: 'inventory_value', label: '库存金额' },
                  { key: 'material_name', label: '物料名' },
                ]}
                defaultSort="inventory_value"
                defaultOrder="desc"
                filterKey="major_category"
                filterLabel="全部类型"
                columns={[
                  { key: 'material_name', label: '可释放物料' },
                  { key: 'major_category', label: '类型', align: 'center' },
                  { key: 'inventory_value', label: '库存金额', align: 'right', render: (r) => formatCurrency(r.inventory_value) },
                ]}
              />
            )}
          </>
        )}
        {simResult?.error && <p className="text-sm text-red-600">{simResult.error}</p>}
      </CollapsibleSection>

      <CollapsibleSection title="BOM驱动物料需求预测" subtitle="按历史销量×标准用量估算" defaultOpen={false}>
        <FilterableTable
          data={rawDemandData}
          sortOptions={[
            { key: 'estimated_demand', label: '需求量' },
            { key: 'dish_count', label: '涉及菜品数' },
            { key: 'material_name', label: '物料名' },
          ]}
          defaultSort="estimated_demand"
          pageSize={PAGE_SIZE}
          columns={[
            { key: 'material_name', label: '物料' },
            { key: 'major_category', label: '类型', align: 'center' },
            { key: 'base_unit', label: '单位', align: 'center' },
            { key: 'estimated_demand', label: '预计需求量', align: 'right', render: (r) => formatNumber(r.estimated_demand) },
            { key: 'dish_count', label: '涉及菜品数', align: 'right', render: (r) => formatNumber(r.dish_count) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
