import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { formatCurrency, formatNumber } from '@/lib/utils'
import { ScatterChart, Scatter, XAxis, YAxis, CartesianGrid, Tooltip, ZAxis, ResponsiveContainer, ReferenceLine } from 'recharts'

const CATEGORY_COLORS = ['#3b82f6', '#ef4444', '#22c55e', '#f97316', '#eab308', '#8b5cf6', '#06b6d4', '#ec4899', '#84cc16', '#a3a3a3', '#f43f5e', '#6366f1', '#14b8a6', '#facc15', '#7c3aed', '#10b981', '#fb923c', '#64748b', '#d946ef']

export function ExploreTab({ month }: { month: string }) {
  const { data: scatter, isLoading } = useQuery({ queryKey: ['ca/scatter', month], queryFn: () => api.get('/cost-analysis/scatter', { params: { month } }) })

  if (isLoading) return <LoadingSpinner text="加载散点图数据..." />

  const scatterData = (scatter as any)?.data || []
  const categories: string[] = [...new Set(scatterData.map((r: any) => r.category_level1).filter(Boolean))] as string[]

  return (
    <div className="space-y-4">
      <CollapsibleSection title="成本差异 vs 销量散点图" subtitle="右上角=高销量高差异(优先整改)，左上角=低销量高差异(考虑下架)">
        <ResponsiveContainer width="100%" height={500}>
          <ScatterChart margin={{ top: 20, right: 20, bottom: 30, left: 20 }}>
            <CartesianGrid strokeDasharray="3 3" />
            <XAxis type="number" dataKey="x" name="销量" tick={{ fontSize: 10 }} label={{ value: '销量', position: 'bottom', offset: 15, fontSize: 12 }} />
            <YAxis type="number" dataKey="y" name="成本差异" tick={{ fontSize: 10 }} label={{ value: '成本差异(元)', angle: -90, position: 'insideLeft', offset: 10, fontSize: 12 }} />
            <ZAxis type="number" dataKey="size" range={[10, 200]} name="销售额" />
            <ReferenceLine y={0} stroke="#666" strokeDasharray="3 3" />
            <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>品类: {d.category_level1}</p>
                  <p>销量: {formatNumber(d.x)}</p>
                  <p>成本差异: {formatCurrency(d.y)}</p>
                  <p>销售额: {formatCurrency(d.size)}</p>
                </div>
              }
              return null
            }} />
            {categories.map((cat, i) => (
              <Scatter key={cat as string} name={cat as string} data={scatterData.filter((d: any) => d.category_level1 === cat)} fill={CATEGORY_COLORS[i % CATEGORY_COLORS.length]} fillOpacity={0.6} />
            ))}
          </ScatterChart>
        </ResponsiveContainer>
        <div className="mt-2 flex flex-wrap gap-2">
          {categories.map((cat, i) => (
            <span key={cat as string} className="flex items-center gap-1 text-xs">
              <span className="h-3 w-3 rounded-full" style={{ background: CATEGORY_COLORS[i % CATEGORY_COLORS.length] }} />{cat as string}
            </span>
          ))}
        </div>
      </CollapsibleSection>
    </div>
  )
}
