import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { FilterableTable } from '@/components/FilterableTable'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { formatCurrency, formatPercent, formatNumber } from '@/lib/utils'
import { useState } from 'react'
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, BarChart, Bar, XAxis, YAxis, CartesianGrid, Legend } from 'recharts'
const PIE_COLORS = ['#22c55e', '#3b82f6', '#eab308', '#f97316', '#ef4444', '#8b5cf6', '#a3a3a3']

export function MaterialTab({ month }: { month: string }) {
  const [dishCode, setDishCode] = useState('')
  const [searchInput, setSearchInput] = useState('')

  const { data: variance, isLoading: lv } = useQuery({
    queryKey: ['ca/material-variance', month, dishCode],
    queryFn: () => api.get(`/cost-analysis/material-variance`, { params: { month, dish_code: dishCode } }),
    enabled: !!dishCode,
  })
  const { data: lossDist, isLoading: ld } = useQuery({ queryKey: ['ca/loss-distribution', month], queryFn: () => api.get('/cost-analysis/loss-distribution', { params: { month } }) })
  const { data: lossTop, isLoading: lt } = useQuery({ queryKey: ['ca/material-loss-top', month], queryFn: () => api.get('/cost-analysis/material-loss-top', { params: { month, limit: 50 } }) })
  const { data: typeLoss, isLoading: ltl } = useQuery({ queryKey: ['ca/material-type-loss', month], queryFn: () => api.get('/cost-analysis/material-type-loss', { params: { month } }) })

  if (ld || lt || ltl) return <LoadingSpinner text="加载原料差异数据..." />

  const varianceData = (variance as any)?.data || []
  const distData = (lossDist as any)?.data || []
  const topData = (lossTop as any)?.data || []
  const typeData = (typeLoss as any)?.data || []

  const reasonColor = (reason: string) => {
    if (reason === '份量超标') return 'bg-red-100 text-red-700'
    if (reason === '分摊遗漏') return 'bg-orange-100 text-orange-700'
    if (reason === '未使用') return 'bg-gray-100 text-gray-700'
    return 'bg-green-100 text-green-700'
  }

  return (
    <div className="space-y-4">
      <CollapsibleSection title="菜品原料差异分解" subtitle="输入菜品编码查看原料级差异">
        <div className="mb-3 flex items-center gap-2">
          <input
            value={searchInput}
            onChange={(e) => setSearchInput(e.target.value)}
            onKeyDown={(e) => e.key === 'Enter' && setDishCode(searchInput)}
            placeholder="输入菜品编码（如 66920）"
            className="rounded border px-3 py-1.5 text-sm w-64"
          />
          <button onClick={() => setDishCode(searchInput)} className="rounded bg-primary px-3 py-1.5 text-sm text-primary-foreground">查询</button>
        </div>
        {dishCode && (
          varianceData.length === 0 && !lv ? (
            <p className="text-sm text-muted-foreground">未找到菜品编码 {dishCode} 的原料数据</p>
          ) : lv ? (
            <LoadingSpinner text="加载原料差异..." />
          ) : (
            <>
              <ResponsiveContainer width="100%" height={300}>
                <BarChart data={varianceData.slice(0, 15)} 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>金额差异: {formatCurrency(d.loss_amount)}</p>
                        <p>损耗率: {formatPercent(d.loss_rate)}</p>
                      </div>
                    }
                    return null
                  }} />
                  <Bar dataKey="loss_amount" name="金额差异">
                    {varianceData.slice(0, 15).map((d: any, i: number) => (
                      <Cell key={i} fill={Number(d.loss_amount) < 0 ? '#ef4444' : '#22c55e'} />
                    ))}
                  </Bar>
                </BarChart>
              </ResponsiveContainer>
              <div className="mt-3">
                <FilterableTable
                  data={varianceData}
                  sortOptions={[
                    { key: 'loss_amount', label: '金额差异' },
                    { key: 'loss_rate', label: '损耗率' },
                    { key: 'loss_qty', label: '数量差异' },
                  ]}
                  defaultSort="loss_amount"
                  defaultOrder="asc"
                  filterKey="reason"
                  filterLabel="全部原因"
                  columns={[
                    { key: 'material_name', label: '原料' },
                    { key: 'material_unit', label: '单位', align: 'center' },
                    { key: 'theo_qty', label: '理论用量', align: 'right', render: (r) => formatNumber(r.theo_qty) },
                    { key: 'actual_qty', label: '实际用量', align: 'right', render: (r) => formatNumber(r.actual_qty) },
                    { key: 'loss_qty', label: '数量差异', align: 'right', render: (r) => formatNumber(r.loss_qty) },
                    { key: 'loss_rate', label: '损耗率', align: 'right', render: (r) => {
                      const v = Number(r.loss_rate || 0)
                      return <span className={v < -20 ? 'text-red-600' : v < 0 ? 'text-yellow-600' : 'text-green-600'}>{formatPercent(v)}</span>
                    }},
                    { key: 'loss_amount', label: '金额差异', align: 'right', render: (r) => formatCurrency(r.loss_amount) },
                    { key: 'reason', label: '原因', render: (r) => (
                      <span className={`rounded px-2 py-0.5 text-xs font-medium ${reasonColor(r.reason)}`}>{r.reason}</span>
                    )},
                  ]}
                />
              </div>
            </>
          )
        )}
      </CollapsibleSection>

      <CollapsibleSection title="物料损耗率分布" subtitle="全部物料明细的损耗率分档统计" defaultOpen={false}>
        <div className="flex gap-4">
          <ResponsiveContainer width="40%" height={250}>
            <PieChart>
              <Pie data={distData} dataKey="cnt" nameKey="loss_band" cx="50%" cy="50%" outerRadius={80} label={(e: any) => `${e.cnt}`}>
                {distData.map((_: any, i: number) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
              </Pie>
              <Tooltip formatter={(v: any) => [v, '明细数']} />
              <Legend wrapperStyle={{ fontSize: 10 }} />
            </PieChart>
          </ResponsiveContainer>
          <div className="flex-1">
            <FilterableTable
              data={distData}
              sortOptions={[
                { key: 'cnt', label: '明细数' },
                { key: 'loss_band', label: '损耗区间' },
              ]}
              defaultSort="cnt"
              defaultOrder="desc"
              columns={[
                { key: 'loss_band', label: '损耗区间' },
                { key: 'cnt', label: '明细数', align: 'right' },
              ]}
            />
          </div>
        </div>
      </CollapsibleSection>

      <CollapsibleSection title="超耗物料TOP榜" subtitle="支持排序">
        <FilterableTable
          data={topData}
          sortOptions={[
            { key: 'total_loss_qty', label: '总损耗量' },
            { key: 'avg_loss_rate', label: '平均损耗率' },
            { key: 'total_loss_amount', label: '损耗金额' },
            { key: 'dish_count', label: '涉及菜品数' },
          ]}
          defaultSort="total_loss_qty"
          defaultOrder="asc"
          columns={[
            { key: 'material_name', label: '物料' },
            { key: 'material_type', label: '类型', align: 'center' },
            { key: 'dish_count', label: '涉及菜品数', align: 'right', render: (r) => formatNumber(r.dish_count) },
            { key: 'total_loss_qty', label: '总损耗量', align: 'right', render: (r) => formatNumber(r.total_loss_qty) },
            { key: 'avg_loss_rate', label: '平均损耗率', align: 'right', render: (r) => <span className="text-red-600">{formatPercent(r.avg_loss_rate)}</span> },
            { key: 'max_loss_rate', label: '最大损耗率', align: 'right', render: (r) => formatPercent(r.max_loss_rate) },
            { key: 'total_loss_amount', label: '损耗金额', align: 'right', render: (r) => formatCurrency(r.total_loss_amount) },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="物料类型损耗对比" subtitle="原材料 vs 半成品" defaultOpen={false}>
        <FilterableTable
          data={typeData}
          sortOptions={[
            { key: 'total_loss_amount', label: '损耗金额' },
            { key: 'avg_loss_rate', label: '平均损耗率' },
            { key: 'cnt', label: '明细数' },
          ]}
          defaultSort="total_loss_amount"
          defaultOrder="desc"
          columns={[
            { key: 'material_type', label: '物料类型' },
            { key: 'cnt', label: '明细数', align: 'right' },
            { key: 'unique_materials', label: '物料种类', align: 'right' },
            { key: 'avg_loss_rate', label: '平均损耗率', align: 'right', render: (r) => formatPercent(r.avg_loss_rate) },
            { key: 'total_loss_amount', label: '损耗金额', align: 'right', render: (r) => formatCurrency(r.total_loss_amount) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
