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 { SearchSelect } from '@/components/SearchSelect'
import { formatCurrency, formatPercent, formatNumber } from '@/lib/utils'
import { useState } from 'react'
import { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, ZAxis } from 'recharts'

const PAGE_SIZE = 15
const MENU_COLORS: Record<string, string> = {
  '明星盈利品': '#22c55e',
  '高销低利品': '#eab308',
  '低销高利品': '#3b82f6',
  '低销低利品': '#ef4444',
  '数据异常品': '#a3a3a3',
}

export function ProfitabilityTab({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [category, setCategory] = useState('')
  const [sort, setSort] = useState('sales_amount')
  const [order, setOrder] = useState<'asc' | 'desc'>('desc')
  const [filter, setFilter] = useState('')

  const { data: matrix, isLoading: l1 } = useQuery({ queryKey: ['ca/menu-engineering', month], queryFn: () => api.get('/cost-analysis/menu-engineering', { params: { month } }) })
  const { data: profit, isLoading: l2 } = useQuery({ queryKey: ['ca/profitability', month, page, category, sort, order, filter], queryFn: () => api.get(`/cost-analysis/profitability`, { params: { month, page, page_size: PAGE_SIZE, sort, order, filter, ...(category ? { category } : {}) } }) })
  const { data: pricing, isLoading: l3 } = useQuery({ queryKey: ['ca/pricing', month], queryFn: () => api.get('/cost-analysis/pricing', { params: { month, threshold: 50 } }) })

  if (l1 || l2 || l3) return <LoadingSpinner text="加载菜品盈利数据..." />

  const matrixData = ((matrix as any)?.data || []).filter((r: any) => r.actual_margin > -500)
  const profitData = (profit as any)?.data || []
  const profitMeta = (profit as any)?.meta || { page, pageSize: PAGE_SIZE, total: 0 }
  const pricingData = (pricing as any)?.data || []

  const categories: string[] = Array.from(new Set(matrixData.map((r: any) => r.category_level1 as string).filter(Boolean)))

  const menuTypeColor = (type: string) => {
    const c: Record<string, string> = {
      '明星盈利品': 'bg-green-100 text-green-700',
      '高销低利品': 'bg-yellow-100 text-yellow-700',
      '低销高利品': 'bg-blue-100 text-blue-700',
      '低销低利品': 'bg-red-100 text-red-700',
      '数据异常品': 'bg-gray-100 text-gray-700',
    }
    return c[type] || 'bg-gray-100 text-gray-700'
  }

  return (
    <div className="space-y-4">
      <CollapsibleSection title="菜单工程矩阵" subtitle="销量 × 实际毛利率四象限分析">
        <ResponsiveContainer width="100%" height={400}>
          <ScatterChart margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis type="number" dataKey="sales_quantity" name="销量" tick={{ fontSize: 10 }} />
            <YAxis type="number" dataKey="actual_margin" name="实际毛利率" unit="%" tick={{ fontSize: 10 }} domain={[-100, 100]} />
            <ZAxis type="number" dataKey="sales_amount" range={[20, 400]} name="销售额" />
            <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.dish_name}</p>
                  <p>销量: {formatNumber(d.sales_quantity)}</p>
                  <p>实际毛利率: {formatPercent(d.actual_margin)}</p>
                  <p>销售额: {formatCurrency(d.sales_amount)}</p>
                  <p>类型: {d.menu_type}</p>
                </div>
              }
              return null
            }} />
            {Object.entries(MENU_COLORS).map(([type, color]) => (
              <Scatter key={type} name={type} data={matrixData.filter((d: any) => d.menu_type === type)} fill={color} />
            ))}
          </ScatterChart>
        </ResponsiveContainer>
        <div className="mt-2 flex flex-wrap gap-3">
          {Object.entries(MENU_COLORS).map(([type, color]) => (
            <span key={type} className="flex items-center gap-1 text-xs">
              <span className="h-3 w-3 rounded-full" style={{ background: color }} />{type}
            </span>
          ))}
        </div>
      </CollapsibleSection>

      <CollapsibleSection title="菜品盈利明细" subtitle="支持筛选和排序">
        <div className="mb-3 flex items-center gap-2">
          <label className="text-xs text-muted-foreground">品类:</label>
          <SearchSelect
            value={category}
            onChange={(v) => { setCategory(v); setPage(1) }}
            options={categories}
            emptyLabel="全部"
            className="min-w-[100px]"
          />
        </div>
        <FilterableTable
          data={profitData}
          serverSide
          page={page}
          onPageChange={setPage}
          sort={sort}
          onSortChange={setSort}
          order={order}
          onOrderChange={setOrder}
          filter={filter}
          onFilterChange={setFilter}
          pageSize={PAGE_SIZE}
          total={profitMeta.total}
          filterButtons={[
            { key: '', label: '全部' },
            { key: 'profitable', label: '盈利菜品' },
            { key: 'loss', label: '亏损菜品' },
            { key: 'high_variance', label: '成本超耗' },
          ]}
          sortOptions={[
            { key: 'sales_amount', label: '销售额' },
            { key: 'sales_quantity', label: '销量' },
            { key: 'actual_margin_rate_pct', label: '实际毛利率' },
            { key: 'theoretical_margin_rate_pct', label: '理论毛利率' },
            { key: 'cost_variance_amount', label: '成本差异' },
          ]}
          defaultSort="sales_amount"
          columns={[
            { key: 'dish_name', label: '菜品' },
            { key: 'category_level1', label: '品类' },
            { key: 'sales_quantity', label: '销量', align: 'right', render: (r) => formatNumber(r.sales_quantity) },
            { key: 'sales_amount', label: '销售额', align: 'right', render: (r) => formatCurrency(r.sales_amount) },
            { key: 'theo_profit', label: '理论毛利', align: 'right', render: (r) => formatCurrency(r.theo_profit) },
            { key: 'actual_profit', label: '实际毛利', align: 'right', render: (r) => formatCurrency(r.actual_profit) },
            { 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: 'revenue_contribution', label: '收入贡献度', align: 'right', render: (r) => formatPercent(r.revenue_contribution) },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="低毛利菜品预警" subtitle="理论毛利率 < 50% 且销售额 > 1000" defaultOpen={false}>
        <FilterableTable
          data={pricingData}
          sortOptions={[
            { key: 'theo_margin', label: '理论毛利率' },
            { key: 'actual_margin', label: '实际毛利率' },
            { key: 'sales_amount', label: '销售额' },
            { key: 'price', label: '售价' },
          ]}
          defaultSort="theo_margin"
          defaultOrder="asc"
          filterKey="category_level1"
          filterLabel="全部分类"
          columns={[
            { key: 'dish_name', label: '菜品' },
            { key: 'category_level1', label: '品类' },
            { key: 'price', label: '售价', align: 'right', render: (r) => formatCurrency(r.price) },
            { key: 'theo_cost', label: '理论成本', align: 'right', render: (r) => formatCurrency(r.theo_cost) },
            { key: 'theo_cost_rate', label: '理论成本率', align: 'right', render: (r) => formatPercent(r.theo_cost_rate) },
            { key: 'theo_margin', label: '理论毛利率', align: 'right', render: (r) => <span className="text-red-600">{formatPercent(r.theo_margin)}</span> },
            { key: 'actual_margin', label: '实际毛利率', align: 'right', render: (r) => formatPercent(r.actual_margin) },
            { key: 'sales_amount', label: '销售额', align: 'right', render: (r) => formatCurrency(r.sales_amount) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
