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

const PIE_COLORS = ['#ef4444', '#f97316', '#eab308', '#3b82f6', '#22c55e', '#a3a3a3', '#8b5cf6']

export function OverviewTab({ month }: { month: string }) {
  const { data: overview, isLoading: l1 } = useQuery({ queryKey: ['ca/overview', month], queryFn: () => api.get('/cost-analysis/overview', { params: { month } }) })
  const { data: categories, isLoading: l2 } = useQuery({ queryKey: ['ca/category-comparison', month], queryFn: () => api.get('/cost-analysis/category-comparison', { params: { month } }) })
  const { data: deviation, isLoading: l3 } = useQuery({ queryKey: ['ca/margin-deviation', month], queryFn: () => api.get('/cost-analysis/margin-deviation', { params: { month } }) })
  const { data: varianceTop, isLoading: l4 } = useQuery({ queryKey: ['ca/variance-top', month], queryFn: () => api.get('/cost-analysis/variance-top', { params: { month, limit: 50 } }) })

  if (l1 || l2 || l3 || l4) return <LoadingSpinner text="加载成本总览..." />

  const ov = (overview as any)?.data || {}
  const cats = (categories as any)?.data || []
  const devs = (deviation as any)?.data || []
  const tops = (varianceTop as any)?.data || []

  const tierColor = (tier: string) => {
    if (tier === '紧急' || tier === '数据异常') return 'bg-red-100 text-red-700'
    if (tier === '整改') return 'bg-orange-100 text-orange-700'
    if (tier === '关注') return 'bg-yellow-100 text-yellow-700'
    return 'bg-green-100 text-green-700'
  }

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <MetricCard title="总销售额" value={ov.total_sales} format="currency" />
        <MetricCard title="理论成本合计" value={ov.total_theo_cost} format="currency" />
        <MetricCard title="实际成本合计" value={ov.total_actual_cost} format="currency" />
        <MetricCard title="成本差异" value={ov.total_variance} format="currency" description="实际成本 - 理论成本" />
        <MetricCard title="平均理论毛利率" value={ov.avg_theo_margin} format="percent" />
        <MetricCard title="平均实际毛利率" value={ov.avg_actual_margin} format="percent" />
        <MetricCard title="低毛利菜品数" value={ov.low_margin_dishes} format="number" description="理论毛利率 < 50%" />
        <MetricCard title="超理论菜品数" value={ov.over_cost_dishes} format="number" description="实际成本超过理论成本" />
      </div>

      <CollapsibleSection title="品类成本对比" subtitle="按一级品类汇总理论vs实际毛利率">
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={cats.slice(0, 10)} margin={{ top: 10, right: 10, bottom: 10, left: 0 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis dataKey="category_level1" tick={{ fontSize: 10 }} angle={-30} textAnchor="end" height={60} />
            <YAxis tick={{ fontSize: 10 }} unit="%" />
            <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.category_level1}</p>
                  <p>理论毛利率: {Number(d.avg_theo_margin).toFixed(2)}%</p>
                  <p>实际毛利率: {Number(d.avg_actual_margin).toFixed(2)}%</p>
                  <p>销售额: {formatCurrency(d.total_sales)}</p>
                  <p>成本差异: {formatCurrency(d.total_variance)}</p>
                </div>
              }
              return null
            }} />
            <Bar dataKey="avg_theo_margin" name="理论毛利率" fill="#3b82f6" />
            <Bar dataKey="avg_actual_margin" name="实际毛利率" fill="#f97316" />
          </BarChart>
        </ResponsiveContainer>
        <div className="mt-3">
          <FilterableTable
            data={cats}
            sortOptions={[
              { key: 'total_variance', label: '成本差异' },
              { key: 'avg_actual_margin', label: '实际毛利率' },
              { key: 'avg_theo_margin', label: '理论毛利率' },
              { key: 'total_sales', label: '销售额' },
            ]}
            defaultSort="total_variance"
            defaultOrder="desc"
            filterKey="category_level1"
            filterLabel="全部品类"
            columns={[
              { key: 'category_level1', label: '品类' },
              { key: 'dishes', label: '菜品数', align: 'right' },
              { key: 'avg_theo_margin', label: '理论毛利率', align: 'right', render: (r) => formatPercent(r.avg_theo_margin) },
              { key: 'avg_actual_margin', label: '实际毛利率', align: 'right', render: (r) => formatPercent(r.avg_actual_margin) },
              { key: 'total_sales', label: '销售额', align: 'right', render: (r) => formatCurrency(r.total_sales) },
              { key: 'total_variance', label: '成本差异', align: 'right', render: (r) => {
                const v = Number(r.total_variance || 0)
                return <span className={v > 0 ? 'text-red-600' : 'text-green-600'}>{formatCurrency(v)}</span>
              }},
            ]}
          />
        </div>
      </CollapsibleSection>

      <CollapsibleSection title="毛利率偏差分布" subtitle="实际毛利率 vs 理论毛利率偏差" defaultOpen={false}>
        <div className="flex gap-4">
          <ResponsiveContainer width="40%" height={250}>
            <PieChart>
              <Pie data={devs} dataKey="cnt" nameKey="deviation_band" cx="50%" cy="50%" outerRadius={80} label={(e: any) => `${e.deviation_band}: ${e.cnt}`}>
                {devs.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={devs}
              sortOptions={[
                { key: 'cnt', label: '菜品数' },
                { key: 'deviation_band', label: '偏差区间' },
              ]}
              defaultSort="cnt"
              defaultOrder="desc"
              columns={[
                { key: 'deviation_band', label: '偏差区间' },
                { key: 'cnt', label: '菜品数', align: 'right' },
              ]}
            />
          </div>
        </div>
      </CollapsibleSection>

      <CollapsibleSection title="成本差异TOP榜" subtitle="实际成本超理论最严重的菜品">
        <FilterableTable
          data={tops}
          sortOptions={[
            { key: 'cost_variance', label: '成本差异' },
            { key: 'sales_amount', label: '销售额' },
            { key: 'actual_margin', label: '实际毛利率' },
            { key: 'theo_margin', label: '理论毛利率' },
          ]}
          defaultSort="cost_variance"
          filterKey="cost_tier"
          filterLabel="全部分层"
          columns={[
            { key: 'dish_name', label: '菜品' },
            { key: 'category_level1', label: '品类' },
            { key: 'theo_margin', label: '理论毛利率', align: 'right', render: (r) => formatPercent(r.theo_margin) },
            { key: 'actual_margin', label: '实际毛利率', align: 'right', render: (r) => formatPercent(r.actual_margin) },
            { key: 'cost_variance', label: '成本差异', align: 'right', render: (r) => {
              const v = Number(r.cost_variance || 0)
              return <span className={v > 0 ? 'text-red-600' : 'text-green-600'}>{formatCurrency(v)}</span>
            }},
            { key: 'sales_amount', label: '销售额', align: 'right', render: (r) => formatCurrency(r.sales_amount) },
            { key: 'cost_tier', label: '分层', render: (r) => (
              <span className={`rounded px-2 py-0.5 text-xs font-medium ${tierColor(r.cost_tier)}`}>{r.cost_tier}</span>
            )},
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
