import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { SearchSelect } from '@/components/SearchSelect'
import { formatNumber } from '@/lib/utils'

const STATUS_COLORS: Record<string, string> = {
  '严重不足': 'text-red-600 font-bold',
  '偏紧': 'text-orange-600 font-medium',
  '合理': 'text-green-600',
  '偏松': 'text-blue-500',
  '过剩': 'text-gray-400',
}

export function StaffingMatchTab({ month }: { month: string }) {
  const { data: storesData } = useQuery({
    queryKey: ['ss/stores'],
    queryFn: () => api.get('/smart-scheduling/stores'),
  })
  const stores = (storesData as any)?.data || []
  const [storeName, setStoreName] = useState('七里庄店')

  const { data, isLoading } = useQuery({
    queryKey: ['ss/staffing-match', storeName, month],
    queryFn: () => api.get('/smart-scheduling/staffing-match', { params: { store: storeName, month } }),
    enabled: !!storeName,
  })

  const rows = (data as any)?.data || []

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

  return (
    <div className="space-y-4">
      <CollapsibleSection title="排班匹配度分析" subtitle="各时段在岗人数 vs 客流账单量，识别排班错配">
        <div className="mb-3 flex gap-2 items-center">
          <label className="text-sm text-muted-foreground">选择门店：</label>
          <SearchSelect
            value={storeName}
            onChange={setStoreName}
            options={stores.map((s: any) => s.store_name)}
            emptyLabel="选择门店"
            className="min-w-[140px]"
          />
        </div>

        {isLoading ? <LoadingSpinner text="加载排班匹配数据..." /> : (
          <>
            <div className="mb-4 flex gap-4 flex-wrap">
              {Object.entries(STATUS_COLORS).map(([status, color]) => (
                <div key={status} className="flex items-center gap-1">
                  <span className={`text-xs ${color}`}>●</span>
                  <span className="text-xs text-muted-foreground">{status}</span>
                </div>
              ))}
            </div>

            <div className="mb-4 overflow-x-auto">
              <table className="w-full text-sm">
                <thead className="bg-muted/50">
                  <tr>
                    <th className="px-3 py-2 text-left">时段</th>
                    <th className="px-3 py-2 text-right">在岗人数</th>
                    <th className="px-3 py-2 text-right">账单量</th>
                    <th className="px-3 py-2 text-right">人均接待</th>
                    <th className="px-3 py-2 text-center">客流条</th>
                    <th className="px-3 py-2 text-center">人力条</th>
                    <th className="px-3 py-2 text-center">匹配状态</th>
                  </tr>
                </thead>
                <tbody>
                  {rows.map((r: any) => (
                    <tr key={r.hour} className="border-t">
                      <td className="px-3 py-2">{r.hour}:00 - {r.hour + 1}:00</td>
                      <td className="px-3 py-2 text-right">{r.avg_staff}</td>
                      <td className="px-3 py-2 text-right">{formatNumber(r.bills)}</td>
                      <td className="px-3 py-2 text-right">{r.bills_per_staff || '-'}</td>
                      <td className="px-3 py-2">
                        <div className="w-24 h-3 bg-muted rounded overflow-hidden">
                          <div className="h-full bg-red-400" style={{ width: `${(r.bills / maxBills) * 100}%` }} />
                        </div>
                      </td>
                      <td className="px-3 py-2">
                        <div className="w-24 h-3 bg-muted rounded overflow-hidden">
                          <div className="h-full bg-blue-400" style={{ width: `${(r.avg_staff / maxStaff) * 100}%` }} />
                        </div>
                      </td>
                      <td className="px-3 py-2 text-center">
                        <span className={STATUS_COLORS[r.match_status] || ''}>{r.match_status}</span>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
              <div className="rounded-lg border p-3">
                <p className="text-xs text-muted-foreground">严重不足时段</p>
                <p className="text-xl font-bold text-red-600">{rows.filter((r: any) => r.match_status === '严重不足').length}</p>
              </div>
              <div className="rounded-lg border p-3">
                <p className="text-xs text-muted-foreground">偏紧时段</p>
                <p className="text-xl font-bold text-orange-600">{rows.filter((r: any) => r.match_status === '偏紧').length}</p>
              </div>
              <div className="rounded-lg border p-3">
                <p className="text-xs text-muted-foreground">过剩/偏松时段</p>
                <p className="text-xl font-bold text-blue-500">{rows.filter((r: any) => r.match_status === '过剩' || r.match_status === '偏松').length}</p>
              </div>
              <div className="rounded-lg border p-3">
                <p className="text-xs text-muted-foreground">合理时段</p>
                <p className="text-xl font-bold text-green-600">{rows.filter((r: any) => r.match_status === '合理').length}</p>
              </div>
            </div>
          </>
        )}
      </CollapsibleSection>
    </div>
  )
}
