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

const PAGE_SIZE = 20

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

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

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

  const rows = (data as any)?.data || []
  const meta = (data as any)?.meta || { page, pageSize: PAGE_SIZE, total: 0 }
  const posRows = (posData as any)?.data || []

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

  return (
    <div className="space-y-4">
      <CollapsibleSection title="门店人效排名" subtitle="人均创收、人力成本率、人均工时、加班占比">
        <FilterableTable
          data={rows}
          serverSide
          page={page}
          onPageChange={setPage}
          sort={sort}
          onSortChange={setSort}
          order={order}
          onOrderChange={setOrder}
          pageSize={PAGE_SIZE}
          total={meta.total}
          sortOptions={[
            { key: 'revenue_per_emp', label: '人均创收' },
            { key: 'emp_count', label: '人数' },
            { key: 'gross_pay', label: '应发工资' },
            { key: 'wage_rate', label: '人力成本率' },
            { key: 'avg_hours', label: '人均工时' },
          ]}
          defaultSort="revenue_per_emp"
          defaultOrder="desc"
          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> },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="岗位配比分析" subtitle="各门店前厅/后厨/管理岗位人数及占比">
        <FilterableTable
          data={posRows}
          sortOptions={[
            { key: 'total_emp', label: '总人数' },
            { key: 'manager_pct', label: '管理占比' },
            { key: 'kitchen_pct', label: '后厨占比' },
            { key: 'front_pct', label: '前厅占比' },
            { key: 'part_time_count', label: '兼职数' },
          ]}
          defaultSort="total_emp"
          defaultOrder="desc"
          filterKey="store_name"
          filterLabel="全部门店"
          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) },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
