import { useState, useMemo, Fragment } from 'react'
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 { formatNumber } from '@/lib/utils'

export function TrafficHeatmapTab({ month }: { month: string }) {
  const [storeName, setStoreName] = useState('')

  const { data: overview } = useQuery({
    queryKey: ['ss/traffic-overview', month],
    queryFn: () => api.get('/smart-scheduling/traffic-overview', { params: { month } }),
  })

  const { data: heatmap, isLoading } = useQuery({
    queryKey: ['ss/traffic-heatmap', storeName, month],
    queryFn: () => api.get('/smart-scheduling/traffic-heatmap', { params: { store: storeName || undefined, month } }),
  })

  const { data: staffing } = useQuery({
    queryKey: ['ss/traffic-heatmap-staffing', storeName, month],
    queryFn: () => api.get('/smart-scheduling/traffic-heatmap-staffing', { params: { store: storeName || undefined, month } }),
  })

  const { data: mealPeriod } = useQuery({
    queryKey: ['ss/meal-period-traffic', storeName, month],
    queryFn: () => api.get('/smart-scheduling/meal-period-traffic', { params: { store: storeName || undefined, month } }),
  })

  const stores = (overview as any)?.data || []
  const heatRows = (heatmap as any)?.data || []
  const mealRows = (mealPeriod as any)?.data || []
  const staffingRows = (staffing as any)?.data || []

  const storeNames = Array.from(new Set(stores.map((s: any) => s.store_name as string))) as string[]

  const hours = Array.from({ length: 24 }, (_, i) => i)
  const heatMap: Record<string, Record<number, number>> = {}
  heatRows.forEach((r: any) => {
    if (!heatMap[r.store_name]) heatMap[r.store_name] = {}
    heatMap[r.store_name][r.hour] = r.bills
  })

  // 人员分布: store -> hour -> { front, kitchen, management, other, total }
  const staffingMap: Record<string, Record<number, { front: number; kitchen: number; management: number; other: number; total: number }>> = {}
  staffingRows.forEach((r: any) => {
    if (!staffingMap[r.store_name]) staffingMap[r.store_name] = {}
    staffingMap[r.store_name][r.hour] = { front: r.front, kitchen: r.kitchen, management: r.management, other: r.other, total: r.total }
  })

  function heatColor(bills: number, max: number): string {
    if (!bills) return ''
    const ratio = bills / max
    if (ratio > 0.8) return 'bg-red-500 text-white'
    if (ratio > 0.6) return 'bg-orange-400 text-white'
    if (ratio > 0.4) return 'bg-yellow-400'
    if (ratio > 0.2) return 'bg-green-300'
    if (ratio > 0) return 'bg-blue-200'
    return ''
  }

  const maxBills = Math.max(...heatRows.map((r: any) => r.bills), 1)

  const mealMap: Record<string, Record<string, number>> = {}
  mealRows.forEach((r: any) => {
    if (!mealMap[r.store_name]) mealMap[r.store_name] = {}
    mealMap[r.store_name][r.meal_period] = r.bills
  })

  const mealStores = useMemo(() => {
    return Object.keys(mealMap).map(s => ({
      store_name: s,
      早市: mealMap[s]?.['早市'] || 0,
      午市: mealMap[s]?.['午市'] || 0,
      下午茶: mealMap[s]?.['下午茶'] || 0,
      晚市: mealMap[s]?.['晚市'] || 0,
      夜宵: mealMap[s]?.['夜宵'] || 0,
      total: Object.values(mealMap[s] || {}).reduce((a: number, b: number) => a + b, 0),
    }))
  }, [mealMap])

  return (
    <div className="space-y-4">
      <CollapsibleSection title="小时客流热力图" subtitle="门店×小时账单量分布，红色为高峰时段">
        <div className="mb-3 flex gap-2 items-center">
          <SearchSelect
            value={storeName}
            onChange={setStoreName}
            options={storeNames}
            emptyLabel="全部门店"
            className="min-w-[140px]"
          />
          <span className="text-xs text-muted-foreground">颜色越深客流越大</span>
          <span className="text-xs text-muted-foreground ml-2">在岗: <span className="text-blue-600">前厅</span>/<span className="text-orange-600">后厨</span>/<span className="text-purple-600">管理</span>/<span className="text-gray-500">其他</span></span>
        </div>
        {isLoading ? <LoadingSpinner text="加载客流热力图..." /> : (
          <div className="overflow-x-auto -mx-4 px-4 heatmap-scroll">
            <table className="text-xs whitespace-nowrap">
              <thead>
                <tr>
                  <th className="px-2 py-1 text-left sticky left-0 bg-card">门店</th>
                  {hours.map(h => <th key={h} className="px-1 py-1 text-center min-w-[32px]">{h}</th>)}
                </tr>
              </thead>
              <tbody>
                {Object.keys(heatMap).map(store => (
                  <Fragment key={store}>
                    <tr>
                      <td className="px-2 py-1 whitespace-nowrap sticky left-0 bg-card font-medium">{store}</td>
                      {hours.map(h => {
                        const bills = heatMap[store]?.[h] || 0
                        return <td key={h} className={`px-1 py-1 text-center ${heatColor(bills, maxBills)}`}>{bills > 0 ? bills : ''}</td>
                      })}
                    </tr>
                    <tr key={store + '-staff'} className="border-b">
                      <td className="px-2 py-0.5 whitespace-nowrap sticky left-0 bg-card text-xs text-muted-foreground">在岗</td>
                      {hours.map(h => {
                        const s = staffingMap[store]?.[h]
                        if (!s || s.total === 0) return <td key={h} className="px-1 py-0.5 text-center text-xs text-muted-foreground/40 min-w-[42px]">-</td>
                        return (
                          <td key={h} className="px-1 py-0.5 text-center text-xs min-w-[42px]">
                            <span className="text-blue-600">{s.front}</span><span className="text-muted-foreground">/</span><span className="text-orange-600">{s.kitchen}</span><span className="text-muted-foreground">/</span><span className="text-purple-600">{s.management}</span><span className="text-muted-foreground">/</span><span className="text-gray-500">{s.other}</span>
                          </td>
                        )
                      })}
                    </tr>
                  </Fragment>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </CollapsibleSection>

      <CollapsibleSection title="门店客流概览" subtitle="各门店月度账单量、峰谷比、客流集中度">
        <FilterableTable
          data={stores}
          sortOptions={[
            { key: 'total_bills', label: '月账单量' },
            { key: 'peak_bills', label: '峰值' },
            { key: 'peak_valley_ratio', label: '峰谷比' },
            { key: 'peak_concentration_pct', label: '集中度' },
          ]}
          defaultSort="total_bills"
          defaultOrder="desc"
          filterKey="store_name"
          filterLabel="全部门店"
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'total_bills', label: '月账单量', align: 'right', render: (r) => formatNumber(r.total_bills) },
            { key: 'peak_bills', label: '峰值(小时)', align: 'right', render: (r) => formatNumber(r.peak_bills) },
            { key: 'min_bills', label: '谷值(小时)', align: 'right', render: (r) => formatNumber(r.min_bills) },
            { key: 'peak_valley_ratio', label: '峰谷比', align: 'right', render: (r) => <span className={parseFloat(r.peak_valley_ratio) > 10 ? 'text-red-600 font-medium' : ''}>{r.peak_valley_ratio}</span> },
            { key: 'peak_concentration_pct', label: '高峰集中度%', align: 'right', render: (r) => <span className={parseFloat(r.peak_concentration_pct) > 60 ? 'text-orange-600 font-medium' : ''}>{r.peak_concentration_pct}%</span> },
            { key: 'volatility_level', label: '波动等级', render: (r) => <span className={r.volatility_level === '波动极大' ? 'text-red-600' : r.volatility_level === '波动较大' ? 'text-orange-600' : ''}>{r.volatility_level}</span> },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="餐段客流分布" subtitle="各门店早市/午市/下午茶/晚市/夜宵账单占比">
        <FilterableTable
          data={mealStores}
          sortOptions={[
            { key: 'total', label: '总账单' },
            { key: '午市', label: '午市' },
            { key: '晚市', label: '晚市' },
            { key: '早市', label: '早市' },
            { key: '夜宵', label: '夜宵' },
          ]}
          defaultSort="total"
          defaultOrder="desc"
          filterKey="store_name"
          filterLabel="全部门店"
          columns={[
            { key: 'store_name', label: '门店' },
            { key: '早市', label: '早市', align: 'right', render: (r) => formatNumber(r['早市']) },
            { key: '午市', label: '午市', align: 'right', render: (r) => formatNumber(r['午市']) },
            { key: '下午茶', label: '下午茶', align: 'right', render: (r) => formatNumber(r['下午茶']) },
            { key: '晚市', label: '晚市', align: 'right', render: (r) => formatNumber(r['晚市']) },
            { key: '夜宵', label: '夜宵', align: 'right', render: (r) => formatNumber(r['夜宵']) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
