import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { Search, CheckCircle, XCircle, ChevronLeft, ChevronRight } from 'lucide-react'
import { socialInsuranceApi, rosterApi } from '../../lib/api-services'
import { Input } from '../../components/ui/Input'
import { useDebouncedValue } from '../../hooks/useDebouncedValue'

const fmt = (n: number) => (n || 0).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })

export default function EmployeeEnrollmentTab() {
  const [keyword, setKeyword] = useState('')
  const debouncedSearch = useDebouncedValue(keyword, 300)
  const [department, setDepartment] = useState('')
  const [socialStatus, setSocialStatus] = useState('')
  const [housingStatus, setHousingStatus] = useState('')
  const [page, setPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)

  const params = useMemo(() => ({
    keyword: debouncedSearch || undefined,
    department: department || undefined,
    socialStatus: socialStatus || undefined,
    housingStatus: housingStatus || undefined,
    page,
    pageSize,
  }), [debouncedSearch, department, socialStatus, housingStatus, page, pageSize])

  const { data: result, isLoading } = useQuery<any>({
    queryKey: ['social-employee-enrollment', params],
    queryFn: () => socialInsuranceApi.employeeEnrollment(params),
    placeholderData: (prev: any) => prev,
  })

  const { data: departments = [] } = useQuery<string[]>({
    queryKey: ['roster-departments'],
    queryFn: () => rosterApi.departments(),
  })

  const list = result?.data || []
  const total = result?.total || 0
  const totalPages = Math.max(1, Math.ceil(total / pageSize))

  const insuredCount = list.filter((e: any) => e.socialInsStatus === 'INSURED').length
  const housingCount = list.filter((e: any) => e.housingFundStatus === 'INSURED').length

  // 筛选变化时重置到第一页
  const handleFilterChange = (setter: (v: string) => void) => (v: string) => {
    setter(v)
    setPage(1)
  }

  return (
    <div className="space-y-3">
      {/* 筛选栏 */}
      <div className="flex flex-wrap items-center gap-3">
        <div className="relative w-48">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <Input
            value={keyword}
            onChange={(e) => { setKeyword(e.target.value); setPage(1) }}
            placeholder="搜索员工姓名"
            className="pl-9"
          />
        </div>
        <select
          value={department}
          onChange={(e) => handleFilterChange(setDepartment)(e.target.value)}
          className="px-3 py-1.5 text-sm border rounded-md bg-white focus:outline-none focus:ring-1 focus:ring-primary"
        >
          <option value="">全部部门</option>
          {departments.map((d: string) => (
            <option key={d} value={d}>{d}</option>
          ))}
        </select>
        <select
          value={socialStatus}
          onChange={(e) => handleFilterChange(setSocialStatus)(e.target.value)}
          className="px-3 py-1.5 text-sm border rounded-md bg-white focus:outline-none focus:ring-1 focus:ring-primary"
        >
          <option value="">社保状态（全部）</option>
          <option value="INSURED">已参保</option>
          <option value="UNINSURED">未参保</option>
        </select>
        <select
          value={housingStatus}
          onChange={(e) => handleFilterChange(setHousingStatus)(e.target.value)}
          className="px-3 py-1.5 text-sm border rounded-md bg-white focus:outline-none focus:ring-1 focus:ring-primary"
        >
          <option value="">公积金状态（全部）</option>
          <option value="INSURED">已参保</option>
          <option value="UNINSURED">未参保</option>
        </select>
        <div className="ml-auto flex items-center gap-2 text-sm">
          <select
            value={pageSize}
            onChange={(e) => { setPageSize(Number(e.target.value)); setPage(1) }}
            className="px-2 py-1 text-sm border rounded-md bg-white focus:outline-none"
          >
            <option value={20}>20 条/页</option>
            <option value={50}>50 条/页</option>
            <option value={100}>100 条/页</option>
          </select>
        </div>
      </div>

      {/* 统计 */}
      <div className="flex items-center gap-4 text-sm">
        <span className="text-gray-500">共 <span className="font-medium text-gray-700">{total}</span> 人</span>
        <span className="text-gray-500">社保参保 <span className="font-medium text-primary">{insuredCount}</span></span>
        <span className="text-gray-500">公积金参保 <span className="font-medium text-primary">{housingCount}</span></span>
      </div>

      {/* 表格 */}
      <div className="overflow-x-auto">
        <table className="w-full text-sm">
          <thead>
            <tr className="border-b text-left text-xs text-gray-500">
              <th className="pb-2 pr-4 font-medium">姓名</th>
              <th className="pb-2 pr-4 font-medium">部门</th>
              <th className="pb-2 pr-4 font-medium">职务</th>
              <th className="pb-2 pr-4 font-medium">社保状态</th>
              <th className="pb-2 pr-4 font-medium">社保基数</th>
              <th className="pb-2 pr-4 font-medium">社保城市</th>
              <th className="pb-2 pr-4 font-medium">社保起缴</th>
              <th className="pb-2 pr-4 font-medium">公积金状态</th>
              <th className="pb-2 pr-4 font-medium">公积金基数</th>
              <th className="pb-2 pr-4 font-medium">公积金城市</th>
              <th className="pb-2 pr-4 font-medium">公积金起缴</th>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr><td colSpan={11} className="py-8 text-center text-gray-400">加载中...</td></tr>
            ) : list.length === 0 ? (
              <tr><td colSpan={11} className="py-8 text-center text-gray-400">暂无符合条件的员工</td></tr>
            ) : list.map((emp: any) => (
              <tr key={emp.id} className="border-b hover:bg-gray-50">
                <td className="py-2 pr-4 font-medium">{emp.name}</td>
                <td className="py-2 pr-4 text-gray-600">{emp.department || '-'}</td>
                <td className="py-2 pr-4 text-gray-600">{emp.position || '-'}</td>
                <td className="py-2 pr-4">
                  {emp.socialInsStatus === 'INSURED' ? (
                    <span className="inline-flex items-center gap-1 text-xs text-green-600">
                      <CheckCircle className="w-3.5 h-3.5" />已参保
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1 text-xs text-gray-400">
                      <XCircle className="w-3.5 h-3.5" />未参保
                    </span>
                  )}
                </td>
                <td className="py-2 pr-4">{emp.socialInsBase ? `¥${fmt(emp.socialInsBase)}` : '-'}</td>
                <td className="py-2 pr-4 text-gray-600">{emp.socialInsCity || '-'}</td>
                <td className="py-2 pr-4 text-gray-500 text-xs">{emp.socialInsStart || '-'}</td>
                <td className="py-2 pr-4">
                  {emp.housingFundStatus === 'INSURED' ? (
                    <span className="inline-flex items-center gap-1 text-xs text-green-600">
                      <CheckCircle className="w-3.5 h-3.5" />已参保
                    </span>
                  ) : (
                    <span className="inline-flex items-center gap-1 text-xs text-gray-400">
                      <XCircle className="w-3.5 h-3.5" />未参保
                    </span>
                  )}
                </td>
                <td className="py-2 pr-4">{emp.housingFundBase ? `¥${fmt(emp.housingFundBase)}` : '-'}</td>
                <td className="py-2 pr-4 text-gray-600">{emp.housingFundCity || '-'}</td>
                <td className="py-2 pr-4 text-gray-500 text-xs">{emp.housingFundStart || '-'}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* 分页 */}
      {total > 0 && (
        <div className="flex items-center justify-between pt-2">
          <span className="text-xs text-gray-500">
            第 {(page - 1) * pageSize + 1}-{Math.min(page * pageSize, total)} 条，共 {total} 条
          </span>
          <div className="flex items-center gap-2">
            <button
              onClick={() => setPage(p => Math.max(1, p - 1))}
              disabled={page <= 1}
              className="p-1.5 rounded border disabled:opacity-40 disabled:cursor-not-allowed hover:bg-gray-50"
            >
              <ChevronLeft className="w-4 h-4" />
            </button>
            <span className="text-sm text-gray-600">{page} / {totalPages}</span>
            <button
              onClick={() => setPage(p => Math.min(totalPages, p + 1))}
              disabled={page >= totalPages}
              className="p-1.5 rounded border disabled:opacity-40 disabled:cursor-not-allowed hover:bg-gray-50"
            >
              <ChevronRight className="w-4 h-4" />
            </button>
          </div>
        </div>
      )}
    </div>
  )
}
