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, 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({ month }: { month: string }) {
  const [page, setPage] = useState(1)
  const [sort, setSort] = useState('gross_pay')
  const [order, setOrder] = useState<'asc' | 'desc'>('desc')
  const [storeFilter, setStoreFilter] = useState('')

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

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

  const { data: turnoverData } = useQuery({
    queryKey: ['ss/turnover', month],
    queryFn: () => api.get('/smart-scheduling/turnover-stats', { 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 || []
  const turnoverRows = (turnoverData as any)?.data || []
  const storeNames = [...new Set(turnoverRows.map((r: any) => r.store_name))].sort() as string[]

  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}
          filter={storeFilter}
          onFilterChange={setStoreFilter}
          filterKey="store_name"
          filterLabel="全部门店"
          filterOptions={storeNames}
          sortOptions={[
            { key: 'gross_pay', label: '应发工资' },
            { key: 'net_pay', label: '实发工资' },
            { key: 'actual_hours', label: '工时' },
            { key: 'perf_amount', label: '绩效' },
            { key: 'overtime_pay', label: '加班费' },
            { key: 'hourly_rate', label: '时薪' },
          ]}
          defaultSort="gross_pay"
          defaultOrder="desc"
          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> },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="岗位薪资对比" subtitle="相同岗位在不同门店的薪资水平差异">
        <FilterableTable
          data={posRows}
          filterKey="position"
          filterLabel="全部岗位"
          sortOptions={[
            { key: 'avg_gross', label: '均应发' },
            { key: 'emp_count', label: '人数' },
            { key: 'store_count', label: '门店数' },
            { key: 'avg_hourly_rate', label: '均时薪' },
            { key: 'avg_hours', label: '均工时' },
          ]}
          defaultSort="avg_gross"
          defaultOrder="desc"
          pageSize={PAGE_SIZE}
          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) },
          ]}
        />
      </CollapsibleSection>

      <CollapsibleSection title="离职率统计" subtitle="各门店离职率、新员工占比">
        <FilterableTable
          data={turnoverRows}
          sortOptions={[
            { key: 'turnover_rate', label: '离职率' },
            { key: 'left_count', label: '离职人数' },
            { key: 'new_hire_rate', label: '新员工占比' },
            { key: 'total_emp', label: '总人数' },
          ]}
          defaultSort="turnover_rate"
          defaultOrder="desc"
          filterKey="store_name"
          filterLabel="全部门店"
          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> },
          ]}
        />
      </CollapsibleSection>
    </div>
  )
}
