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, formatNumber } from '@/lib/utils'
import { useState } from 'react'
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from 'recharts'

const PAGE_SIZE = 15
const LEVEL_COLORS: Record<string, string> = {
  '红色-严重超耗': '#ef4444',
  '橙色-明显超耗': '#f97316',
  '绿色-基本正常': '#22c55e',
  '灰色-口径异常': '#a3a3a3',
}

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

  const { data: ov, isLoading: l1 } = useQuery({ queryKey: ['ca/store-overview', month], queryFn: () => api.get('/cost-analysis/store-overview', { params: { month } }) })
  const { data: ranking, isLoading: l2 } = useQuery({ queryKey: ['ca/store-ranking', month, page, sort, order, filter], queryFn: () => api.get(`/cost-analysis/store-ranking`, { params: { month, page, page_size: PAGE_SIZE, sort, order, filter } }) })

  if (l1 || l2) return <LoadingSpinner text="加载门店成本数据..." />

  const ovData = (ov as any)?.data || {}
  const rankData = (ranking as any)?.data || []
  const meta = (ranking as any)?.meta || { total: 0 }

  const pieData = [
    { name: '红色-严重超耗', value: Number(ovData.red_count || 0) },
    { name: '橙色-明显超耗', value: Number(ovData.orange_count || 0) },
    { name: '绿色-基本正常', value: Number(ovData.green_count || 0) },
    { name: '灰色-口径异常', value: Number(ovData.gray_count || 0) },
  ].filter(d => d.value > 0)

  const levelColor = (level: string) => {
    if (level === '红色-严重超耗') return 'bg-red-100 text-red-700'
    if (level === '橙色-明显超耗') return 'bg-orange-100 text-orange-700'
    if (level === '绿色-基本正常') return 'bg-green-100 text-green-700'
    return 'bg-gray-100 text-gray-700'
  }

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-2 gap-3 md:grid-cols-3">
        <MetricCard title="门店总数" value={ovData.total_stores} format="number" />
        <MetricCard title="红色-严重超耗" value={ovData.red_count} format="number" />
        <MetricCard title="橙色-明显超耗" value={ovData.orange_count} format="number" />
        <MetricCard title="绿色-基本正常" value={ovData.green_count} format="number" />
        <MetricCard title="灰色-口径异常" value={ovData.gray_count} format="number" />
        <MetricCard title="总超耗金额" value={ovData.total_variance} format="currency" />
      </div>

      <CollapsibleSection title="门店成本差异分布" subtitle="按红橙绿灰分级">
        <ResponsiveContainer width="100%" height={250}>
          <PieChart>
            <Pie data={pieData} dataKey="value" nameKey="name" cx="50%" cy="50%" outerRadius={80} label={(e: any) => `${e.name}: ${e.value}`}>
              {pieData.map((d, i) => <Cell key={i} fill={LEVEL_COLORS[d.name]} />)}
            </Pie>
            <Tooltip formatter={(v: any) => [v, '门店数']} />
            <Legend wrapperStyle={{ fontSize: 10 }} />
          </PieChart>
        </ResponsiveContainer>
      </CollapsibleSection>

      <CollapsibleSection title="门店超耗排名" subtitle="支持筛选和排序">
        <FilterableTable
          data={rankData}
          serverSide
          page={page}
          onPageChange={setPage}
          sort={sort}
          onSortChange={setSort}
          order={order}
          onOrderChange={setOrder}
          filter={filter}
          onFilterChange={setFilter}
          pageSize={PAGE_SIZE}
          total={meta.total}
          filterButtons={[
            { key: '', label: '全部' },
            { key: 'red', label: '红色-严重超耗' },
            { key: 'orange', label: '橙色-明显超耗' },
            { key: 'green', label: '绿色-基本正常' },
            { key: 'gray', label: '灰色-口径异常' },
          ]}
          sortOptions={[
            { key: 'food_cost_variance', label: '超耗金额' },
            { key: 'variance_to_theoretical_pct', label: '偏差率' },
            { key: 'actual_food_cost_rate_pct', label: '实际成本率' },
            { key: 'negative_item_lines', label: '负库存项' },
          ]}
          defaultSort="food_cost_variance"
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'theo_cost_rate', label: '理论成本率', align: 'right', render: (r) => formatPercent(r.theo_cost_rate) },
            { key: 'actual_cost_rate', label: '实际成本率', align: 'right', render: (r) => formatPercent(r.actual_cost_rate) },
            { key: 'variance_pct', label: '偏差', align: 'right', render: (r) => {
              const v = Number(r.variance_pct || 0)
              return <span className={v > 20 ? 'text-red-600' : v > 10 ? 'text-yellow-600' : 'text-green-600'}>{v > 0 ? '+' : ''}{formatPercent(v)}</span>
            }},
            { key: 'variance_amount', label: '超耗金额', align: 'right', render: (r) => {
              const v = Number(r.variance_amount || 0)
              return <span className={v > 0 ? 'text-red-600' : 'text-green-600'}>{formatCurrency(v)}</span>
            }},
            { key: 'negative_item_lines', label: '负库存项', align: 'center', render: (r) => {
              const n = Number(r.negative_item_lines || 0)
              return n > 0 ? <span className="text-red-600">{n}</span> : <span className="text-muted-foreground">0</span>
            }},
            { key: 'variance_level', label: '分级', render: (r) => (
              <span className={`rounded px-2 py-0.5 text-xs font-medium ${levelColor(r.variance_level)}`}>{r.variance_level}</span>
            )},
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
