import { useQuery } from '@tanstack/react-query'
import { useState } from 'react'
import api from '@/lib/api'
import { FilterableTable } from '@/components/FilterableTable'
import { LoadingSpinner } from '@/components/LoadingSpinner'
import { CollapsibleSection } from '@/components/CollapsibleSection'
import { MetricCard } from '@/components/MetricCard'
import { formatCurrency, formatNumber, formatPercent } from '@/lib/utils'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts'

const PIE_COLORS = ['#3b82f6', '#22c55e', '#eab308', '#ef4444', '#a855f7', '#64748b', '#ec4899', '#14b8a6', '#f97316', '#6366f1']

export function EmployeePerformancePage() {
  const [positionFilter, setPositionFilter] = useState('')
  const [statusFilter, setStatusFilter] = useState('')
  const [page, setPage] = useState(1)

  const { data, isLoading } = useQuery({
    queryKey: ['analytics-enhanced/employee/performance', positionFilter, statusFilter, page],
    queryFn: () => api.get('/analytics-enhanced/employee/performance', {
      params: { position: positionFilter, status: statusFilter, page, page_size: 50 },
    }),
  })

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

  const positionSummary = (data as any)?.data?.position_summary || []
  const employees = (data as any)?.data?.employees || []
  const meta = (data as any)?.meta || {}

  const totalHeadcount = positionSummary.reduce((s: number, r: any) => s + Number(r.headcount || 0), 0)
  const totalActive = positionSummary.reduce((s: number, r: any) => s + Number(r.active_count || 0), 0)
  const avgPerf = positionSummary.length > 0
    ? positionSummary.reduce((s: number, r: any) => s + Number(r.avg_perf_score || 0), 0) / positionSummary.length
    : 0
  const avgSalary = positionSummary.length > 0
    ? positionSummary.reduce((s: number, r: any) => s + Number(r.avg_gross_pay || 0), 0) / positionSummary.length
    : 0

  const positionChartData = positionSummary.slice(0, 10).map((r: any) => ({
    name: r.position,
    人数: Number(r.headcount || 0),
    在职: Number(r.active_count || 0),
  }))

  const positionPieData = positionSummary.slice(0, 8).map((r: any) => ({
    name: r.position,
    value: Number(r.headcount || 0),
  }))

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-xl font-bold">员工绩效分析</h1>
          <p className="mt-0.5 text-xs text-muted-foreground">岗位分布 · 薪资绩效 · 出勤率</p>
        </div>
      </div>

      {/* 概览指标 */}
      <CollapsibleSection title="员工总览" subtitle="全员汇总">
        <div className="grid grid-cols-2 gap-3 md:grid-cols-4">
          <MetricCard title="总人数" value={totalHeadcount} format="number" description="全部员工（含离职）" />
          <MetricCard title="在职人数" value={totalActive} format="number" description="当前在职员工" status="good" />
          <MetricCard title="平均绩效分" value={avgPerf} format="number" description="全员平均绩效评分" />
          <MetricCard title="平均月薪" value={avgSalary} format="currency" description="全员平均应发工资" />
        </div>
      </CollapsibleSection>

      {/* 图表 */}
      <div className="grid gap-4 lg:grid-cols-2">
        <CollapsibleSection title="岗位人数分布" subtitle="TOP10岗位人数与在职数">
          <ResponsiveContainer width="100%" height={280}>
            <BarChart data={positionChartData} margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="name" tick={{ fontSize: 10 }} angle={-20} textAnchor="end" height={60} />
              <YAxis tick={{ fontSize: 10 }} />
              <Tooltip />
              <Legend />
              <Bar dataKey="人数" fill="#3b82f6" />
              <Bar dataKey="在职" fill="#22c55e" />
            </BarChart>
          </ResponsiveContainer>
        </CollapsibleSection>

        <CollapsibleSection title="岗位占比" subtitle="各岗位人数占比">
          <ResponsiveContainer width="100%" height={280}>
            <PieChart>
              <Pie data={positionPieData} cx="50%" cy="50%" outerRadius={80} dataKey="value"
                labelLine={false} label={({ name, value }: any) => <tspan fontSize={11}>{`${name}: ${formatNumber(value)}`}</tspan>}>
                {positionPieData.map((_: any, i: number) => <Cell key={i} fill={PIE_COLORS[i % PIE_COLORS.length]} />)}
              </Pie>
              <Tooltip formatter={(v: any) => [formatNumber(v), '人数']} />
              <Legend />
            </PieChart>
          </ResponsiveContainer>
        </CollapsibleSection>
      </div>

      {/* 岗位汇总 */}
      <CollapsibleSection title="岗位绩效汇总" subtitle="各岗位人数、薪资、绩效、出勤率">
        <FilterableTable
          data={positionSummary}
          filterKey="position"
          filterLabel="全部岗位"
          sortOptions={[
            { key: 'headcount', label: '人数' },
            { key: 'avg_gross_pay', label: '平均工资' },
            { key: 'avg_perf_score', label: '绩效分' },
            { key: 'avg_attendance_rate', label: '出勤率' },
          ]}
          defaultSort="headcount"
          defaultOrder="desc"
          columns={[
            { key: 'position', label: '岗位' },
            { key: 'headcount', label: '总人数', align: 'right', render: (r) => formatNumber(r.headcount) },
            { key: 'active_count', label: '在职', align: 'right', render: (r) => formatNumber(r.active_count) },
            { key: 'avg_gross_pay', label: '平均应发', align: 'right', render: (r) => formatCurrency(r.avg_gross_pay) },
            { key: 'avg_perf_score', label: '绩效分', align: 'right', render: (r) => Number(r.avg_perf_score || 0).toFixed(2) },
            { key: 'avg_attendance_rate', label: '出勤率', align: 'right', render: (r) => {
              const v = Number(r.avg_attendance_rate || 0)
              return <span className={v >= 95 ? 'text-green-600' : v >= 80 ? 'text-yellow-600' : 'text-red-600'}>{v.toFixed(1)}%</span>
            }},
          ]}
        />
      </CollapsibleSection>

      {/* 筛选器 */}
      <div className="flex items-center gap-3">
        <select
          value={positionFilter}
          onChange={(e) => { setPositionFilter(e.target.value); setPage(1) }}
          className="rounded-md border px-3 py-1.5 text-sm"
        >
          <option value="">全部岗位</option>
          {positionSummary.map((r: any) => (
            <option key={r.position} value={r.position}>{r.position}</option>
          ))}
        </select>
        <select
          value={statusFilter}
          onChange={(e) => { setStatusFilter(e.target.value); setPage(1) }}
          className="rounded-md border px-3 py-1.5 text-sm"
        >
          <option value="">全部状态</option>
          <option value="在职">在职</option>
          <option value="离职">离职</option>
        </select>
        <span className="text-xs text-muted-foreground">共 {meta.total || 0} 条</span>
      </div>

      {/* 员工明细 */}
      <CollapsibleSection title="员工明细" subtitle="按应发工资降序">
        <FilterableTable
          data={employees}
          filterKey="employee_id"
          filterLabel="全部员工"
          sortOptions={[
            { key: 'gross_pay', label: '应发工资' },
            { key: 'perf_score', label: '绩效分' },
            { key: 'actual_attend', label: '出勤天数' },
          ]}
          defaultSort="gross_pay"
          defaultOrder="desc"
          columns={[
            { key: 'employee_id', label: '工号' },
            { key: 'position', label: '岗位' },
            { key: 'status', label: '状态', render: (r) => {
              const color = r.status === '在职' ? 'text-green-600' : 'text-red-600'
              return <span className={color}>{r.status}</span>
            }},
            { key: 'org_level2', label: '所属机构' },
            { key: 'org_level3', label: '部门/区域' },
            { key: 'gross_pay', label: '应发工资', align: 'right', render: (r) => formatCurrency(r.gross_pay) },
            { key: 'net_pay', label: '实发工资', align: 'right', render: (r) => formatCurrency(r.net_pay) },
            { key: 'perf_score', label: '绩效分', align: 'right', render: (r) => Number(r.perf_score || 0).toFixed(2) },
            { key: 'actual_attend', label: '出勤', align: 'right', render: (r) => `${r.actual_attend || 0}/${r.expected_attend || 0}` },
            { key: 'overtime_pay', label: '加班费', align: 'right', render: (r) => formatCurrency(r.overtime_pay) },
            { key: 'bonus', label: '奖金', align: 'right', render: (r) => formatCurrency(r.bonus) },
            { key: 'hire_date', label: '入职日期', render: (r) => r.hire_date ? String(r.hire_date).slice(0, 10) : '' },
          ]}
        />
      </CollapsibleSection>

      {/* 分页 */}
      {meta.total > 50 && (
        <div className="flex items-center justify-center gap-2">
          <button
            onClick={() => setPage(p => Math.max(1, p - 1))}
            disabled={page <= 1}
            className="rounded-md border px-3 py-1 text-sm disabled:opacity-50"
          >上一页</button>
          <span className="text-sm text-muted-foreground">第 {page} 页 / 共 {Math.ceil(meta.total / 50)} 页</span>
          <button
            onClick={() => setPage(p => p + 1)}
            disabled={page >= Math.ceil(meta.total / 50)}
            className="rounded-md border px-3 py-1 text-sm disabled:opacity-50"
          >下一页</button>
        </div>
      )}
    </div>
  )
}
