import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import api from '@/lib/api'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { DataTable } from '@/components/DataTable'
import { Pagination } from '@/components/Pagination'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { formatCurrency, formatPercent, formatNumber } from '@/lib/utils'

const PAGE_SIZE = 20

export function EfficiencyBenchmarkTab() {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('revenue_per_emp')
  const [order, setOrder] = useState('desc')
  const [posPage, setPosPage] = useState(1)
  const [posFilter, setPosFilter] = useState('')
  const [posSort, setPosSort] = useState('total_emp')
  const [posOrder, setPosOrder] = useState('desc')

  const { data, isLoading } = useQuery({
    queryKey: ['ss/efficiency', page, sort, order],
    queryFn: () => api.get(`/smart-scheduling/efficiency-ranking?page=${page}&page_size=${PAGE_SIZE}&sort=${sort}&order=${order}`),
  })

  const { data: posData } = useQuery({
    queryKey: ['ss/position-distribution'],
    queryFn: () => api.get('/smart-scheduling/position-distribution'),
  })

  const rows = (data as any)?.data || []
  const meta = (data as any)?.meta || { page, pageSize: PAGE_SIZE, total: 0 }
  const posRows = (posData as any)?.data || []
  const posStoreNames = [...new Set(posRows.map((r: any) => r.store_name))].sort() as string[]

  const posSorts = [
    { key: 'total_emp', label: '总人数' },
    { key: 'manager_pct', label: '管理占比' },
    { key: 'kitchen_pct', label: '后厨占比' },
    { key: 'front_pct', label: '前厅占比' },
    { key: 'part_time_count', label: '兼职数' },
  ]

  const posFiltered = useMemo(() => {
    let r = posRows
    if (posFilter) r = r.filter((s: any) => s.store_name === posFilter)
    return [...r].sort((a: any, b: any) => {
      const av = parseFloat(a[posSort]) || 0
      const bv = parseFloat(b[posSort]) || 0
      return posOrder === 'desc' ? bv - av : av - bv
    })
  }, [posRows, posFilter, posSort, posOrder])

  const posTotal = posFiltered.length
  const posPaged = posFiltered.slice((posPage - 1) * PAGE_SIZE, posPage * PAGE_SIZE)

  if (isLoading) return <LoadingSpinner text="加载人效数据..." />

  const sorts = [
    { key: 'revenue_per_emp', label: '人均创收' },
    { key: 'emp_count', label: '人数' },
    { key: 'gross_pay', label: '应发工资' },
    { key: 'wage_rate', label: '人力成本率' },
    { key: 'avg_hours', label: '人均工时' },
  ]

  return (
    <div className="space-y-4">
      <CollapsibleSection title="门店人效排名" subtitle="人均创收、人力成本率、人均工时、加班占比">
        <div className="flex gap-2 mb-3 flex-wrap">
          {sorts.map(s => (
            <button key={s.key} onClick={() => { setSort(s.key); setPage(1) }} className={`px-3 py-1 rounded text-xs ${sort === s.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>按{s.label}</button>
          ))}
          <span className="mx-2 text-muted-foreground">|</span>
          <button onClick={() => { setOrder(order === 'asc' ? 'desc' : 'asc'); setPage(1) }} className="px-3 py-1 rounded text-xs bg-muted">
            {order === 'asc' ? '↑ 升序' : '↓ 降序'}
          </button>
        </div>
        <DataTable
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'emp_count', label: '人数', align: 'right', render: (r) => formatNumber(r.emp_count) },
            { key: 'revenue', label: '营收', align: 'right', render: (r) => formatCurrency(r.revenue) },
            { key: 'revenue_per_emp', label: '人均创收', align: 'right', render: (r) => <span className={parseFloat(r.revenue_per_emp) > 50000 ? 'text-green-600 font-medium' : parseFloat(r.revenue_per_emp) < 20000 ? 'text-red-600' : ''}>{formatCurrency(r.revenue_per_emp)}</span> },
            { key: 'gross_pay', label: '应发工资', align: 'right', render: (r) => formatCurrency(r.gross_pay) },
            { key: 'cost_per_emp', label: '人均成本', align: 'right', render: (r) => formatCurrency(r.cost_per_emp) },
            { key: 'wage_rate', label: '人力成本率', align: 'right', render: (r) => <span className={parseFloat(r.wage_rate) > 25 ? 'text-red-600 font-medium' : parseFloat(r.wage_rate) < 15 ? 'text-green-600' : ''}>{formatPercent(r.wage_rate)}</span> },
            { key: 'avg_hours', label: '人均工时', align: 'right', render: (r) => formatNumber(r.avg_hours) },
            { key: 'revenue_per_hour', label: '时均创收', align: 'right', render: (r) => formatCurrency(r.revenue_per_hour) },
            { key: 'overtime_rate', label: '加班占比%', align: 'right', render: (r) => <span className={parseFloat(r.overtime_rate) > 5 ? 'text-orange-600' : ''}>{formatPercent(r.overtime_rate)}</span> },
          ]}
          data={rows}
        />
        <Pagination page={page} pageSize={meta.pageSize} total={meta.total} onPageChange={setPage} />
      </CollapsibleSection>

      <CollapsibleSection title="岗位配比分析" subtitle="各门店前厅/后厨/管理岗位人数及占比">
        <div className="flex gap-2 mb-3 flex-wrap">
          <select value={posFilter} onChange={(e) => { setPosFilter(e.target.value); setPosPage(1) }} className="border rounded px-2 py-1 text-sm">
            <option value="">全部门店</option>
            {posStoreNames.map((s) => <option key={s} value={s}>{s}</option>)}
          </select>
          <span className="mx-2 text-muted-foreground">|</span>
          {posSorts.map(s => (
            <button key={s.key} onClick={() => { setPosSort(s.key); setPosPage(1) }} className={`px-3 py-1 rounded text-xs ${posSort === s.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>按{s.label}</button>
          ))}
          <span className="mx-2 text-muted-foreground">|</span>
          <button onClick={() => { setPosOrder(posOrder === 'asc' ? 'desc' : 'asc'); setPosPage(1) }} className="px-3 py-1 rounded text-xs bg-muted">
            {posOrder === 'asc' ? '↑ 升序' : '↓ 降序'}
          </button>
        </div>
        <DataTable
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'total_emp', label: '总人数', align: 'right', render: (r) => formatNumber(r.total_emp) },
            { key: 'manager_count', label: '管理岗', align: 'right', render: (r) => formatNumber(r.manager_count) },
            { key: 'manager_pct', label: '管理占比%', align: 'right', render: (r) => <span className={parseFloat(r.manager_pct) > 20 ? 'text-orange-600' : ''}>{r.manager_pct}%</span> },
            { key: 'kitchen_count', label: '后厨', align: 'right', render: (r) => formatNumber(r.kitchen_count) },
            { key: 'kitchen_pct', label: '后厨占比%', align: 'right', render: (r) => `${r.kitchen_pct}%` },
            { key: 'front_count', label: '前厅', align: 'right', render: (r) => formatNumber(r.front_count) },
            { key: 'front_pct', label: '前厅占比%', align: 'right', render: (r) => `${r.front_pct}%` },
            { key: 'part_time_count', label: '兼职', align: 'right', render: (r) => formatNumber(r.part_time_count) },
          ]}
          data={posPaged}
        />
        <Pagination page={posPage} pageSize={PAGE_SIZE} total={posTotal} onPageChange={setPosPage} />
      </CollapsibleSection>
    </div>
  )
}
