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

const PIE_COLORS = ['#22c55e', '#3b82f6', '#eab308', '#ef4444']

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

  const { data, isLoading } = useQuery({
    queryKey: ['analytics-enhanced/menu-engineering/actions', month],
    queryFn: () => api.get('/analytics-enhanced/menu-engineering/actions', { params: { month } }),
  })

  if (isLoading) {
    return <LoadingSpinner text="加载菜单工程数据..." />
  }

  const summary = (data as any)?.data?.summary || {}
  const actions = (data as any)?.data?.actions || []

  const actionCounts = [
    { name: '保留并推广', value: actions.filter((r: any) => r.action === '保留并推广').length },
    { name: '优化提升', value: actions.filter((r: any) => r.action === '优化提升').length },
    { name: '降本或提价', value: actions.filter((r: any) => r.action === '降本或提价').length },
    { name: '考虑淘汰', value: actions.filter((r: any) => r.action === '考虑淘汰').length },
  ]

  const abcPieData = [
    { name: 'A类(核心)', value: summary.class_a || 0 },
    { name: 'B类(成长)', value: summary.class_b || 0 },
    { name: 'C类(长尾)', value: summary.class_c || 0 },
  ]

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">菜单工程行动清单</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">ABC分类 · 行动建议 · 淘汰/保留/提价/降本</p>
        </div>
        <MonthPicker month={month} onChange={setMonth} />
      </div>

      {/* 概览指标 */}
      <CollapsibleSection title="SKU概览" subtitle="ABC分类分布与行动汇总">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="总SKU数" value={Number(summary.total_skus || 0)} format="number" description="当月有销售的菜品总数" />
          <MetricCard title="A类(高收入)" value={Number(summary.class_a || 0)} format="number" description="收入贡献TOP20%" status="good" />
          <MetricCard title="C类(低收入)" value={Number(summary.class_c || 0)} format="number" description="收入贡献较低的菜品" status="bad" />
          <MetricCard title="建议淘汰" value={Number(summary.recommend_eliminate || 0)} format="number" description="月收入<¥1000的C类SKU" status="bad" />
        </div>
      </CollapsibleSection>

      {/* 图表 */}
      <div className="grid gap-4 lg:grid-cols-2">
        <CollapsibleSection title="ABC分类分布" subtitle="A/B/C类SKU数量占比">
          <ResponsiveContainer width="100%" height={250}>
            <PieChart>
              <Pie data={abcPieData} cx="50%" cy="50%" outerRadius={80} dataKey="value"
                labelLine={false} label={({ name, value }: any) => <tspan fontSize={11}>{`${name}: ${formatNumber(value)}`}</tspan>}>
                {abcPieData.map((_: any, i: number) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
              </Pie>
              <Tooltip formatter={(v: any) => [formatNumber(v), '数量']} />
              <Legend />
            </PieChart>
          </ResponsiveContainer>
        </CollapsibleSection>

        <CollapsibleSection title="行动建议分布" subtitle="各类行动建议的SKU数量">
          <ResponsiveContainer width="100%" height={250}>
            <BarChart data={actionCounts} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" tick={{ fontSize: 11 }} />
              <YAxis tick={{ fontSize: 10 }} />
              <Tooltip formatter={(v: any) => [formatNumber(v), 'SKU数']} />
              <Legend />
              <Bar dataKey="value" fill="#3b82f6" />
            </BarChart>
          </ResponsiveContainer>
        </CollapsibleSection>
      </div>

      {/* 行动清单 */}
      <CollapsibleSection title="行动清单明细" subtitle="按ABC分类和收入排序">
        <FilterableTable
          data={actions}
          filterKey="dish_name"
          filterLabel="全部菜品"
          sortOptions={[
            { key: 'revenue', label: '收入' },
            { key: 'order_count', label: '订单数' },
            { key: 'avg_price', label: '均价' },
            { key: 'abc_class', label: 'ABC分类' },
          ]}
          defaultSort="revenue"
          defaultOrder="desc"
          columns={[
            { key: 'dish_name', label: '菜品名称' },
            { key: 'abc_class', label: 'ABC', render: (r) => {
              const color = r.abc_class?.startsWith('A') ? 'text-green-600 font-medium' : r.abc_class?.startsWith('B') ? 'text-blue-600' : 'text-yellow-600'
              return <span className={color}>{r.abc_class}</span>
            }},
            { key: 'category_l1', label: '一级分类' },
            { key: 'category_l2', label: '二级分类' },
            { key: 'revenue', label: '月收入', align: 'right', render: (r) => formatCurrency(r.revenue) },
            { key: 'order_count', label: '订单数', align: 'right', render: (r) => formatNumber(r.order_count) },
            { key: 'avg_price', label: '均价', align: 'right', render: (r) => formatCurrency(r.avg_price) },
            { key: 'action', label: '建议行动', render: (r) => {
              const color = r.action === '保留并推广' ? 'text-green-600' : r.action === '考虑淘汰' ? 'text-red-600' : r.action === '优化提升' ? 'text-blue-600' : 'text-yellow-600'
              return <span className={color}>{r.action}</span>
            }},
            { key: 'suggestion', label: '详细建议' },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
