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, formatNumber } from '@/lib/utils'

const PAGE_SIZE = 20

const STATUS_COLORS: Record<string, string> = {
  '离职': 'text-red-600',
  '新员工': 'text-blue-500',
  '在职': 'text-green-600',
}

export function EmployeeAnalysisTab() {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('gross_pay')
  const [order, setOrder] = useState('desc')
  const [storeFilter, setStoreFilter] = useState('')
  const [posPage, setPosPage] = useState(1)
  const [turnoverPage, setTurnoverPage] = useState(1)
  const [posSort, setPosSort] = useState('avg_gross')
  const [posOrder, setPosOrder] = useState('desc')
  const [turnoverSort, setTurnoverSort] = useState('turnover_rate')
  const [turnoverOrder, setTurnoverOrder] = useState('desc')

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

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

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

  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 turnoverRows = (turnoverData as any)?.data || []

  const posSorts = [
    { key: 'avg_gross', label: '均应发' },
    { key: 'emp_count', label: '人数' },
    { key: 'store_count', label: '门店数' },
    { key: 'avg_hourly_rate', label: '均时薪' },
    { key: 'avg_hours', label: '均工时' },
  ]

  const posFiltered = useMemo(() => {
    return [...posRows].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, posSort, posOrder])

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

  const turnoverSorts = [
    { key: 'turnover_rate', label: '离职率' },
    { key: 'left_count', label: '离职人数' },
    { key: 'new_hire_rate', label: '新员工占比' },
    { key: 'total_emp', label: '总人数' },
  ]

  const turnoverFiltered = useMemo(() => {
    return [...turnoverRows].sort((a: any, b: any) => {
      const av = parseFloat(a[turnoverSort]) || 0
      const bv = parseFloat(b[turnoverSort]) || 0
      return turnoverOrder === 'desc' ? bv - av : av - bv
    })
  }, [turnoverRows, turnoverSort, turnoverOrder])

  const turnoverTotal = turnoverFiltered.length
  const turnoverPaged = turnoverFiltered.slice((turnoverPage - 1) * PAGE_SIZE, turnoverPage * PAGE_SIZE)
  const storeNames = [...new Set(turnoverRows.map((r: any) => r.store_name))].sort() as string[]

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

  const sorts = [
    { key: 'gross_pay', label: '应发工资' },
    { key: 'net_pay', label: '实发工资' },
    { key: 'actual_hours', label: '工时' },
    { key: 'perf_amount', label: '绩效' },
    { key: 'overtime_pay', label: '加班费' },
    { key: 'hourly_rate', label: '时薪' },
  ]

  return (
    <div className="space-y-4">
      <CollapsibleSection title="员工薪资明细" subtitle="员工级薪资构成、工时、绩效、有效时薪">
        <div className="flex gap-2 mb-3 flex-wrap">
          <select value={storeFilter} onChange={(e) => { setStoreFilter(e.target.value); setPage(1) }} className="border rounded px-2 py-1 text-sm">
            <option value="">全部门店</option>
            {storeNames.map((s: any) => <option key={s} value={s}>{s}</option>)}
          </select>
          <span className="mx-2 text-muted-foreground">|</span>
          {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: 'employee_code', label: '工号' },
            { key: 'store_name', label: '门店' },
            { key: 'position', label: '岗位' },
            { key: 'emp_status', label: '状态', render: (r) => <span className={STATUS_COLORS[r.emp_status] || ''}>{r.emp_status}</span> },
            { key: 'attend_days', label: '出勤天', align: 'right', render: (r) => r.attend_days },
            { key: 'work_hours', label: '工时', align: 'right', render: (r) => formatNumber(r.work_hours) },
            { key: 'base_wage', label: '基本工资', align: 'right', render: (r) => formatCurrency(r.base_wage) },
            { key: 'overtime_pay', label: '加班费', align: 'right', render: (r) => formatCurrency(r.overtime_pay) },
            { key: 'perf_amount', label: '绩效', align: 'right', render: (r) => formatCurrency(r.perf_amount) },
            { key: 'gross_pay', label: '应发', align: 'right', render: (r) => formatCurrency(r.gross_pay) },
            { key: 'net_pay', label: '实发', align: 'right', render: (r) => <span className="font-medium">{formatCurrency(r.net_pay)}</span> },
            { key: 'effective_hourly_rate', label: '有效时薪', align: 'right', render: (r) => <span className={parseFloat(r.effective_hourly_rate) > 100 ? 'text-green-600' : parseFloat(r.effective_hourly_rate) < 50 ? 'text-red-600' : ''}>{formatCurrency(r.effective_hourly_rate)}</span> },
            { key: 'overtime_rate', label: '加班占比%', align: 'right', render: (r) => <span className={parseFloat(r.overtime_rate) > 5 ? 'text-orange-600' : ''}>{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">
          {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: 'position', label: '岗位' },
            { key: 'emp_count', label: '人数', align: 'right', render: (r) => formatNumber(r.emp_count) },
            { key: 'store_count', label: '门店数', align: 'right', render: (r) => formatNumber(r.store_count) },
            { key: 'avg_gross', label: '均应发', align: 'right', render: (r) => formatCurrency(r.avg_gross) },
            { key: 'min_gross', label: '最低应发', align: 'right', render: (r) => <span className="text-red-600">{formatCurrency(r.min_gross)}</span> },
            { key: 'max_gross', label: '最高应发', align: 'right', render: (r) => <span className="text-green-600">{formatCurrency(r.max_gross)}</span> },
            { key: 'avg_net', label: '均实发', align: 'right', render: (r) => formatCurrency(r.avg_net) },
            { key: 'avg_hours', label: '均工时', align: 'right', render: (r) => formatNumber(r.avg_hours) },
            { key: 'avg_perf_score', label: '均绩效分', align: 'right', render: (r) => r.avg_perf_score },
            { key: 'avg_hourly_rate', label: '均有效时薪', align: 'right', render: (r) => formatCurrency(r.avg_hourly_rate) },
          ]}
          data={posPaged}
        />
        <Pagination page={posPage} pageSize={PAGE_SIZE} total={posTotal} onPageChange={setPosPage} />
      </CollapsibleSection>

      <CollapsibleSection title="离职率统计" subtitle="各门店离职率、新员工占比">
        <div className="flex gap-2 mb-3 flex-wrap">
          {turnoverSorts.map(s => (
            <button key={s.key} onClick={() => { setTurnoverSort(s.key); setTurnoverPage(1) }} className={`px-3 py-1 rounded text-xs ${turnoverSort === s.key ? 'bg-primary text-primary-foreground' : 'bg-muted'}`}>按{s.label}</button>
          ))}
          <span className="mx-2 text-muted-foreground">|</span>
          <button onClick={() => { setTurnoverOrder(turnoverOrder === 'asc' ? 'desc' : 'asc'); setTurnoverPage(1) }} className="px-3 py-1 rounded text-xs bg-muted">
            {turnoverOrder === 'asc' ? '↑ 升序' : '↓ 降序'}
          </button>
        </div>
        <DataTable
          columns={[
            { key: 'store_name', label: '门店' },
            { key: 'total_emp', label: '总人数', align: 'right', render: (r) => formatNumber(r.total_emp) },
            { key: 'left_count', label: '离职人数', align: 'right', render: (r) => <span className={parseFloat(r.left_count) > 0 ? 'text-red-600' : ''}>{r.left_count}</span> },
            { key: 'turnover_rate', label: '离职率%', align: 'right', render: (r) => <span className={parseFloat(r.turnover_rate) > 15 ? 'text-red-600 font-medium' : parseFloat(r.turnover_rate) > 5 ? 'text-orange-600' : ''}>{r.turnover_rate ? r.turnover_rate + '%' : '0%'}</span> },
            { key: 'new_count', label: '新员工数', align: 'right', render: (r) => <span className="text-blue-500">{r.new_count}</span> },
            { key: 'new_hire_rate', label: '新员工占比%', align: 'right', render: (r) => <span className={parseFloat(r.new_hire_rate) > 20 ? 'text-orange-600' : ''}>{r.new_hire_rate ? r.new_hire_rate + '%' : '0%'}</span> },
          ]}
          data={turnoverPaged}
        />
        <Pagination page={turnoverPage} pageSize={PAGE_SIZE} total={turnoverTotal} onPageChange={setTurnoverPage} />
      </CollapsibleSection>
    </div>
  )
}
