import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Link } from 'react-router-dom'
import { Search, Plus, Edit2, Trash2, X, Bell, Users, Check } from 'lucide-react'
import { toast } from 'sonner'
import { rosterApi, employeeApi } from '../../lib/api-services'
import api from '../../lib/api'
import { usePageSize } from '../../hooks/usePageSize'
import { Input, Label, Select } from '../../components/ui/Input'
import Button from '../../components/ui/Button'
import Modal from '../../components/ui/Modal'
import PageGuide from '../../components/ui/PageGuide'

const ACK_LABELS: Record<string, string> = { PENDING: '待签收', SIGNED: '已签收', REFUSED: '拒绝签收' }
const ACK_COLORS: Record<string, string> = { PENDING: 'bg-amber-50 text-amber-700', SIGNED: 'bg-green-50 text-green-700', REFUSED: 'bg-red-50 text-red-700' }

function fmtDate(d: string | Date | null): string {
  if (!d) return '-'
  return new Date(d).toLocaleDateString('zh-CN')
}

export default function TrainingRecords() {
  const queryClient = useQueryClient()
  const pageSize = usePageSize()
  const [page, setPage] = useState(1)
  const [keyword, setKeyword] = useState('')
  const [filterAckStatus, setFilterAckStatus] = useState('')
  const [showCreate, setShowCreate] = useState(false)
  const [editRecord, setEditRecord] = useState<any>(null)

  const { data, isLoading } = useQuery({
    queryKey: ['training-list', page, pageSize, keyword, filterAckStatus],
    queryFn: () => rosterApi.trainingList({ page, pageSize, keyword, ackStatus: filterAckStatus }),
  })

  const { data: employees } = useQuery({
    queryKey: ['employees-active'],
    queryFn: () => employeeApi.list({ status: 'ACTIVE' }),
  })

  const createMut = useMutation({
    mutationFn: (data: any) => {
      const empId = data.employeeId
      delete data.employeeId
      return api.post(`/roster/${empId}/training`, data)
    },
    onSuccess: () => {
      toast.success('培训记录已添加')
      queryClient.invalidateQueries({ queryKey: ['training-list'] })
      setShowCreate(false)
    },
    onError: () => toast.error('添加失败'),
  })

  const batchCreateMut = useMutation({
    mutationFn: (data: any) => api.post('/roster/training/batch', data),
    onSuccess: (data: any) => {
      toast.success(`已为 ${data?.count || 0} 名员工添加培训记录`)
      queryClient.invalidateQueries({ queryKey: ['training-list'] })
      setShowCreate(false)
    },
    onError: () => toast.error('批量添加失败'),
  })

  const updateMut = useMutation({
    mutationFn: (data: any) => {
      const empId = data.employeeId
      const recordId = data.recordId
      delete data.employeeId
      delete data.recordId
      return api.put(`/roster/${empId}/training/${recordId}`, data)
    },
    onSuccess: () => {
      toast.success('培训记录已更新')
      queryClient.invalidateQueries({ queryKey: ['training-list'] })
      setEditRecord(null)
    },
    onError: () => toast.error('更新失败'),
  })

  const deleteMut = useMutation({
    mutationFn: ({ employeeId, recordId }: { employeeId: string; recordId: string }) =>
      api.delete(`/roster/${employeeId}/training/${recordId}`),
    onSuccess: () => {
      toast.success('记录已删除')
      queryClient.invalidateQueries({ queryKey: ['training-list'] })
    },
  })

  const remindMut = useMutation({
    mutationFn: (recordId: string) => rosterApi.trainingRemind(recordId),
    onSuccess: (data: any) => {
      toast.success(data?.message || '催办已发送')
    },
    onError: () => toast.error('催办失败'),
  })

  const records = data?.records || []
  const total = data?.total || 0
  const totalPages = Math.ceil(total / pageSize)

  return (
    <div className="space-y-4">
      <PageGuide>培训记录管理，记录员工参加的各类培训，包括入职培训、岗位培训、安全培训等。支持新增记录、上传证书、查询历史。关联：培训数据关联员工档案，可在花名册查看。</PageGuide>
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-base font-semibold">培训记录</h1>
          <p className="mt-1 text-sm text-gray-500">管理全员培训记录及签收状态</p>
        </div>
        <Button size="sm" onClick={() => setShowCreate(true)}>
          <Plus className="w-4 h-4 mr-1" /> 新增培训记录
        </Button>
      </div>

      <div className="flex items-center gap-2">
        <div className="relative flex-1 max-w-xs">
          <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={filterAckStatus}
          onChange={(e) => { setFilterAckStatus(e.target.value); setPage(1) }}
          className="w-32"
        >
          <option value="">全部状态</option>
          <option value="PENDING">待签收</option>
          <option value="SIGNED">已签收</option>
          <option value="REFUSED">拒绝签收</option>
        </Select>
      </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>
            </tr>
          </thead>
          <tbody>
            {isLoading ? (
              <tr><td colSpan={8} className="py-8 text-center text-gray-400">加载中...</td></tr>
            ) : records.length === 0 ? (
              <tr><td colSpan={8} className="py-8 text-center text-gray-400">暂无培训记录</td></tr>
            ) : records.map((r: any) => (
              <tr key={r.id} className="border-b hover:bg-gray-50">
                <td className="py-2 pr-4">
                  <div className="flex flex-col gap-0.5">
                    <Link to={`/roster?employeeId=${r.employeeId}`} className="text-primary hover:underline">{r.employee?.name}</Link>
                    {r.employee?.idCardNumber && <span className="text-gray-400 text-[11px] font-mono">{r.employee.idCardNumber}</span>}
                  </div>
                </td>
                <td className="py-2 pr-4 text-gray-600">{r.employee?.department || '-'}</td>
                <td className="py-2 pr-4">{fmtDate(r.trainingDate)}</td>
                <td className="py-2 pr-4">{r.topic}</td>
                <td className="py-2 pr-4 text-gray-600">{r.trainer || '-'}</td>
                <td className="py-2 pr-4">{r.duration}</td>
                <td className="py-2 pr-4">
                  <span className={`inline-block px-2 py-0.5 rounded text-xs ${ACK_COLORS[r.ackStatus] || 'bg-gray-50 text-gray-600'}`}>
                    {ACK_LABELS[r.ackStatus] || r.ackStatus}
                  </span>
                </td>
                <td className="py-2 pr-4">
                  <div className="flex gap-1">
                    {r.ackStatus === 'PENDING' && (
                      <button
                        onClick={() => remindMut.mutate(r.id)}
                        disabled={remindMut.isPending}
                        className="p-1 hover:bg-gray-100 rounded"
                        title="催办签收"
                      >
                        <Bell className="w-3.5 h-3.5 text-amber-500" />
                      </button>
                    )}
                    <button onClick={() => setEditRecord(r)} className="p-1 hover:bg-gray-100 rounded">
                      <Edit2 className="w-3.5 h-3.5 text-gray-500" />
                    </button>
                    <button
                      onClick={() => { if (confirm('确认删除？')) deleteMut.mutate({ employeeId: r.employeeId, recordId: r.id }) }}
                      className="p-1 hover:bg-gray-100 rounded"
                    >
                      <Trash2 className="w-3.5 h-3.5 text-red-400" />
                    </button>
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {totalPages > 1 && (
        <div className="flex items-center justify-between">
          <span className="text-xs text-gray-500">共 {total} 条</span>
          <div className="flex gap-1">
            <Button size="sm" variant="secondary" disabled={page <= 1} onClick={() => setPage(page - 1)}>上一页</Button>
            <span className="px-3 py-1 text-xs text-gray-500">{page} / {totalPages}</span>
            <Button size="sm" variant="secondary" disabled={page >= totalPages} onClick={() => setPage(page + 1)}>下一页</Button>
          </div>
        </div>
      )}

      {(showCreate || editRecord) && (
        <TrainingForm
          employees={employees || []}
          record={editRecord}
          onSubmit={(data) => {
            if (editRecord) {
              updateMut.mutate({ ...data, employeeId: editRecord.employeeId, recordId: editRecord.id })
            } else if (data.employeeIds) {
              batchCreateMut.mutate(data)
            } else {
              createMut.mutate(data)
            }
          }}
          onClose={() => { setShowCreate(false); setEditRecord(null) }}
        />
      )}
    </div>
  )
}

function TrainingForm({ employees, record, onSubmit, onClose }: {
  employees: any[]
  record: any
  onSubmit: (data: any) => void
  onClose: () => void
}) {
  const [batchMode, setBatchMode] = useState(false)
  const [selectedIds, setSelectedIds] = useState<string[]>([])
  const [batchSearch, setBatchSearch] = useState('')
  const [form, setForm] = useState({
    employeeId: record?.employeeId || '',
    trainingDate: record?.trainingDate ? new Date(record.trainingDate).toISOString().slice(0, 10) : new Date().toISOString().slice(0, 10),
    topic: record?.topic || '',
    content: record?.content || '',
    trainer: record?.trainer || '',
    duration: record?.duration || 0,
    remark: record?.remark || '',
  })

  const filteredEmployees = batchSearch
    ? employees.filter((e: any) => e.name.includes(batchSearch) || (e.department || '').includes(batchSearch))
    : employees

  const toggleEmployee = (id: string) => {
    setSelectedIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
  }

  const handleSubmit = () => {
    if (batchMode) {
      onSubmit({ ...form, employeeIds: selectedIds })
    } else {
      onSubmit(form)
    }
  }

  const canSubmit = batchMode ? selectedIds.length > 0 && form.topic : form.employeeId && form.topic

  return (
    <div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50" onClick={onClose}>
      <div className="bg-white rounded-lg p-6 w-full max-w-md max-h-[90vh] overflow-y-auto" onClick={e => e.stopPropagation()}>
        <div className="flex items-center justify-between mb-4">
          <h3 className="font-medium">{record ? '编辑培训记录' : '新增培训记录'}</h3>
          <button onClick={onClose}><X className="w-4 h-4 text-gray-400" /></button>
        </div>
        <div className="space-y-3">
          {!record && (
            <div>
              <div className="flex items-center justify-between mb-1">
                <Label>{batchMode ? '批量选择员工' : '员工'}</Label>
                <button
                  className="text-xs text-primary hover:underline flex items-center gap-1"
                  onClick={() => { setBatchMode(!batchMode); setSelectedIds([]) }}
                >
                  <Users className="w-3.5 h-3.5" />
                  {batchMode ? '切换为单选' : '切换为批量'}
                </button>
              </div>
              {batchMode ? (
                <div className="border border-gray-200 rounded-md">
                  <div className="p-2 border-b border-gray-100">
                    <input
                      type="text"
                      placeholder="搜索姓名/部门"
                      value={batchSearch}
                      onChange={(e) => setBatchSearch(e.target.value)}
                      className="w-full px-2 py-1 text-sm border border-gray-200 rounded focus:outline-none focus:ring-1 focus:ring-primary"
                    />
                  </div>
                  <div className="max-h-[180px] overflow-y-auto">
                    {filteredEmployees.length === 0 ? (
                      <div className="px-3 py-4 text-center text-xs text-gray-400">未找到匹配员工</div>
                    ) : filteredEmployees.map((emp: any) => (
                      <label
                        key={emp.id}
                        className="flex items-center gap-2 px-3 py-1.5 hover:bg-gray-50 cursor-pointer text-sm"
                      >
                        <input
                          type="checkbox"
                          checked={selectedIds.includes(emp.id)}
                          onChange={() => toggleEmployee(emp.id)}
                          className="rounded"
                        />
                        <span>{emp.name}</span>
                        <span className="text-gray-400 text-xs">{emp.department || ''}</span>
                      </label>
                    ))}
                  </div>
                  {selectedIds.length > 0 && (
                    <div className="px-3 py-1.5 border-t border-gray-100 text-xs text-primary">
                      已选择 {selectedIds.length} 名员工
                    </div>
                  )}
                </div>
              ) : (
                <Select value={form.employeeId} onChange={(e) => setForm({ ...form, employeeId: e.target.value })}>
                  <option value="">请选择员工</option>
                  {employees.map((emp: any) => (
                    <option key={emp.id} value={emp.id}>{emp.name} - {emp.department || ''}</option>
                  ))}
                </Select>
              )}
            </div>
          )}
          <div>
            <Label>培训日期</Label>
            <Input type="date" value={form.trainingDate} onChange={(e) => setForm({ ...form, trainingDate: e.target.value })} />
          </div>
          <div>
            <Label>培训主题</Label>
            <Input value={form.topic} onChange={(e) => setForm({ ...form, topic: e.target.value })} placeholder="培训主题" />
          </div>
          <div>
            <Label>培训内容</Label>
            <Input value={form.content} onChange={(e) => setForm({ ...form, content: e.target.value })} placeholder="培训内容" />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <Label>讲师</Label>
              <Input value={form.trainer} onChange={(e) => setForm({ ...form, trainer: e.target.value })} placeholder="讲师姓名" />
            </div>
            <div>
              <Label>时长(小时)</Label>
              <Input type="number" min={0} step={0.5} value={form.duration} onChange={(e) => setForm({ ...form, duration: Number(e.target.value) })} />
            </div>
          </div>
          {record && (
            <div>
              <Label>签收状态</Label>
              <div className="text-sm text-gray-600">
                <span className={`inline-block px-2 py-0.5 rounded text-xs ${ACK_COLORS[record.ackStatus] || 'bg-gray-50 text-gray-600'}`}>
                  {ACK_LABELS[record.ackStatus] || record.ackStatus}
                </span>
                <span className="ml-2 text-xs text-gray-400">由员工在员工端签收</span>
              </div>
            </div>
          )}
          <div>
            <Label>备注</Label>
            <Input value={form.remark} onChange={(e) => setForm({ ...form, remark: e.target.value })} placeholder="备注" />
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <Button variant="secondary" size="sm" onClick={onClose}>取消</Button>
            <Button size="sm" onClick={handleSubmit} disabled={!canSubmit}>保存</Button>
          </div>
        </div>
      </div>
    </div>
  )
}
