import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { toast } from 'sonner'
import { Calendar, Clock, Plus } from 'lucide-react'
import { attendanceApi } from '../lib/api-services'
import { usePageSize } from '../hooks/usePageSize'
import Card from '../components/ui/Card'
import Button from '../components/ui/Button'
import { Input, Label, Select } from '../components/ui/Input'
import Modal from '../components/ui/Modal'
import Pagination from '../components/ui/Pagination'
import EmptyState from '../components/ui/EmptyState'
import PageGuide from '../components/ui/PageGuide'
import { useConfirm } from '../hooks/useConfirm'

const TABS = [
  { key: 'shifts', label: '班次管理', icon: Clock },
  { key: 'schedule', label: '排班', icon: Calendar },
]

export default function Schedule() {
  const [activeTab, setActiveTab] = useState('shifts')

  return (
    <div className="space-y-4">
      <PageGuide>
        排班管理，支持班次设定和员工排班。流程：①创建班次 → ②为员工设置长期/临时班次。长期班次为员工默认工作班次，临时排班可按天覆盖。
      </PageGuide>
      <div>
        <div className="flex items-center gap-2">
          <Calendar className="h-5 w-5 text-primary" />
          <h1 className="text-base font-semibold">排班管理</h1>
        </div>
        <p className="mt-1 text-sm text-gray-500">班次设定、员工排班</p>
      </div>

      {/* Tab 导航 */}
      <div className="flex flex-wrap gap-1 border-b border-gray-200">
        {TABS.map(tab => {
          const Icon = tab.icon
          return (
            <button
              key={tab.key}
              onClick={() => setActiveTab(tab.key)}
              className={`flex items-center gap-1.5 px-3 py-2 text-sm font-medium border-b-2 transition-colors ${
                activeTab === tab.key
                  ? 'border-primary text-primary'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              }`}
            >
              <Icon className="w-4 h-4" />
              {tab.label}
            </button>
          )
        })}
      </div>

      {activeTab === 'shifts' && <ShiftsTab />}
      {activeTab === 'schedule' && <ScheduleTab />}
    </div>
  )
}

// ========== 班次管理 Tab ==========
function ShiftsTab() {
  const queryClient = useQueryClient()
  const confirm = useConfirm()
  const [showAdd, setShowAdd] = useState(false)
  const [editShift, setEditShift] = useState<any>(null)
  const [form, setForm] = useState({ name: '', startTime: '09:00', endTime: '18:00', flexibleMinutes: 0, restMinutes: 60, color: '#3b82f6' })

  const { data: shifts, isLoading } = useQuery<any>({
    queryKey: ['shifts'],
    queryFn: async () => {
      return await attendanceApi.shifts()
    },
  })

  const saveMutation = useMutation({
    mutationFn: async (data: any) => {
      if (editShift) {
        return attendanceApi.saveShift(data, editShift.id)
      }
      return attendanceApi.saveShift(data)
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['shifts'] })
      setShowAdd(false)
      setEditShift(null)
      setForm({ name: '', startTime: '09:00', endTime: '18:00', flexibleMinutes: 0, restMinutes: 60, color: '#3b82f6' })
    },
  })

  const deleteMutation = useMutation({
    mutationFn: (id: string) => attendanceApi.removeShift(id),
    onSuccess: () => queryClient.invalidateQueries({ queryKey: ['shifts'] }),
  })

  const handleSubmit = () => {
    if (!form.name.trim()) return toast.error('请输入班次名称')
    saveMutation.mutate(form)
  }

  return (
    <div className="space-y-3">
      <div className="flex justify-end">
        <Button onClick={() => { setEditShift(null); setForm({ name: '', startTime: '09:00', endTime: '18:00', flexibleMinutes: 0, restMinutes: 60, color: '#3b82f6' }); setShowAdd(true) }}>
          <Plus className="w-4 h-4 mr-1" />新增班次
        </Button>
      </div>

      {isLoading ? (
        <div className="text-center py-8 text-gray-500">加载中...</div>
      ) : !shifts || shifts.length === 0 ? (
        <EmptyState title="暂无班次" description="请先创建班次" />
      ) : (
        <div className="grid sm:grid-cols-2 lg:grid-cols-3 gap-3">
          {shifts.map((s: any) => (
            <Card key={s.id}>
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <div className="w-3 h-3 rounded-full" style={{ background: s.color }} />
                  <span className="font-medium text-sm">{s.name}</span>
                </div>
                <div className="flex gap-1">
                  <button className="text-xs text-gray-400 hover:text-primary px-1" onClick={() => { setEditShift(s); setForm(s); setShowAdd(true) }}>编辑</button>
                  <button className="text-xs text-gray-400 hover:text-red-500 px-1" onClick={async () => { if (await confirm({ title: '删除班次', message: '确认删除？' })) deleteMutation.mutate(s.id) }}>删除</button>
                </div>
              </div>
              <div className="mt-2 text-xs text-gray-500 space-y-0.5">
                <div>上班时间：{s.startTime} — 下班时间：{s.endTime}</div>
                <div>弹性时长：{s.flexibleMinutes} 分钟 — 休息时长：{s.restMinutes} 分钟</div>
              </div>
            </Card>
          ))}
        </div>
      )}

      <Modal open={showAdd} onClose={() => setShowAdd(false)} title={editShift ? '编辑班次' : '新增班次'}>
        <div className="space-y-3">
          <div>
            <Label>班次名称</Label>
            <Input value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} placeholder="如：早班、白班、夜班" />
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <Label>上班时间</Label>
              <Input type="time" value={form.startTime} onChange={e => setForm({ ...form, startTime: e.target.value })} />
            </div>
            <div>
              <Label>下班时间</Label>
              <Input type="time" value={form.endTime} onChange={e => setForm({ ...form, endTime: e.target.value })} />
            </div>
          </div>
          <div className="grid grid-cols-2 gap-3">
            <div>
              <Label>弹性时长（分钟）</Label>
              <Input type="number" value={form.flexibleMinutes} onChange={e => setForm({ ...form, flexibleMinutes: Number(e.target.value) })} />
            </div>
            <div>
              <Label>休息时长（分钟）</Label>
              <Input type="number" value={form.restMinutes} onChange={e => setForm({ ...form, restMinutes: Number(e.target.value) })} />
            </div>
          </div>
          <div>
            <Label>显示颜色</Label>
            <input type="color" value={form.color} onChange={e => setForm({ ...form, color: e.target.value })} className="h-9 w-16 rounded border border-gray-200" />
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <Button variant="secondary" onClick={() => setShowAdd(false)}>取消</Button>
            <Button onClick={handleSubmit} disabled={saveMutation.isPending}>{saveMutation.isPending ? '保存中...' : '保存'}</Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}

// ========== 排班 Tab ==========
function ScheduleTab() {
  const queryClient = useQueryClient()
  const [date, setDate] = useState(new Date().toISOString().slice(0, 10))
  const [showAssign, setShowAssign] = useState(false)
  const [selectedShiftId, setSelectedShiftId] = useState('')
  const [selectedEmployeeIds, setSelectedEmployeeIds] = useState<Set<string>>(new Set())
  const [searchQuery, setSearchQuery] = useState('')
  const [filterDept, setFilterDept] = useState('')
  const pageSize = usePageSize()
  const [page, setPage] = useState(1)
  const [inlineShiftId, setInlineShiftId] = useState<Record<string, string>>({})

  const { data: shifts } = useQuery<any>({
    queryKey: ['shifts'],
    queryFn: async () => {
      return await attendanceApi.shifts()
    },
  })

  const { data: assignments, isLoading } = useQuery<any>({
    queryKey: ['shift-assignments', date],
    queryFn: async () => {
      return await attendanceApi.shiftAssignments(date)
    },
  })

  const { data: dailyData } = useQuery<any>({
    queryKey: ['daily-attendance', date],
    queryFn: async () => {
      return await attendanceApi.daily(date)
    },
  })

  const batchAssignMutation = useMutation({
    mutationFn: (items: any[]) => attendanceApi.batchAssign(items),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['shift-assignments'] })
      queryClient.invalidateQueries({ queryKey: ['daily-attendance'] })
      setShowAssign(false)
      setSelectedEmployeeIds(new Set())
      setSelectedShiftId('')
      toast.success('排班成功')
    },
  })

  const deleteAssignmentMutation = useMutation({
    mutationFn: (id: string) => attendanceApi.removeAssignment(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['shift-assignments'] })
      queryClient.invalidateQueries({ queryKey: ['daily-attendance'] })
    },
  })

  // 设置默认班次（长期排班）
  const setDefaultShiftMutation = useMutation({
    mutationFn: ({ employeeId, shiftId }: { employeeId: string; shiftId: string | null }) =>
      attendanceApi.setDefaultShift(employeeId, shiftId),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['shift-assignments'] })
      queryClient.invalidateQueries({ queryKey: ['daily-attendance'] })
      toast.success('默认班次已更新')
    },
    onError: () => toast.error('设置失败'),
  })

  const handleBatchAssign = () => {
    if (!selectedShiftId) return toast.error('请选择班次')
    if (selectedEmployeeIds.size === 0) return toast.error('请选择员工')
    const items = Array.from(selectedEmployeeIds).map(empId => ({ employeeId: empId, shiftId: selectedShiftId, date }))
    batchAssignMutation.mutate(items)
  }

  const allEmployees = dailyData || []
  const assignmentMap: Map<string, any> = new Map((assignments || []).map((a: any) => [a.employeeId, a]))

  const filteredEmployees = allEmployees.filter((emp: any) => {
    if (filterDept && emp.department !== filterDept) return false
    if (searchQuery.trim()) {
      const q = searchQuery.trim().toLowerCase()
      if (!emp.name?.toLowerCase().includes(q) && !emp.department?.toLowerCase().includes(q)) return false
    }
    return true
  })
  const total = filteredEmployees.length
  const employees = filteredEmployees.slice((page - 1) * pageSize, page * pageSize)

  const toggleEmployee = (id: string) => {
    const next = new Set(selectedEmployeeIds)
    if (next.has(id)) next.delete(id)
    else next.add(id)
    setSelectedEmployeeIds(next)
  }

  const handleInlineAssign = (employeeId: string) => {
    const shiftId = inlineShiftId[employeeId]
    if (!shiftId) return toast.error('请先选择班次')
    batchAssignMutation.mutate([{ employeeId, shiftId, date }])
  }

  return (
    <div className="space-y-3">
      <div className="flex flex-wrap items-center justify-between gap-2">
        <div className="flex items-center gap-2">
          <input
            type="date"
            value={date}
            onChange={e => { setDate(e.target.value); setPage(1) }}
            className="px-3 py-1.5 text-sm border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <input
            type="text"
            placeholder="搜索姓名或部门"
            value={searchQuery}
            onChange={e => { setSearchQuery(e.target.value); setPage(1) }}
            className="px-3 py-1.5 text-sm border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary w-44"
          />
          <select
            value={filterDept}
            onChange={e => { setFilterDept(e.target.value); setPage(1) }}
            className="h-9 rounded-md border border-gray-200 bg-white px-3 text-sm"
          >
            <option value="">全部部门</option>
            {Array.from(new Set(allEmployees.map((e: any) => e.department).filter(Boolean) as string[])).map(d => (
              <option key={d} value={d}>{d}</option>
            ))}
          </select>
        </div>
        <Button onClick={() => setShowAssign(true)}>
          <Plus className="w-4 h-4 mr-1" />批量排班
        </Button>
      </div>

      {isLoading ? (
        <div className="text-center py-8 text-gray-500">加载中...</div>
      ) : total === 0 ? (
        <EmptyState title="暂无员工" description="没有可排班的员工" />
      ) : (
        <>
        <Card className="overflow-hidden p-0">
          <table className="w-full text-sm">
            <thead className="bg-gray-50/90">
              <tr className="border-b border-gray-200 text-xs font-medium text-gray-500">
                <th className="px-4 py-3 text-left">姓名</th>
                <th className="px-4 py-3 text-left">身份证号</th>
                <th className="px-4 py-3 text-left">部门</th>
                <th className="px-4 py-3 text-left">班次</th>
                <th className="px-4 py-3 text-center w-48">操作</th>
              </tr>
            </thead>
            <tbody>
              {employees.map((emp: any) => {
                const assignment = assignmentMap.get(emp.employeeId)
                const isDefault = assignment?.isDefault === true
                const hasShift = assignment && assignment.shift
                return (
                  <tr key={emp.employeeId} className="border-b border-gray-100 last:border-0">
                    <td className="px-4 py-3 font-medium">{emp.name}</td>
                    <td className="px-4 py-3 text-gray-500 font-mono text-xs">{emp.idCardNumber || '-'}</td>
                    <td className="px-4 py-3 text-gray-500">{emp.department || '未分配'}</td>
                    <td className="px-4 py-3">
                      {hasShift ? (
                        <span className="inline-flex items-center gap-1.5 px-2 py-0.5 rounded text-xs" style={{ background: (assignment.shift as any)?.color + '20', color: (assignment.shift as any)?.color }}>
                          <div className="w-2 h-2 rounded-full" style={{ background: (assignment.shift as any)?.color }} />
                          {(assignment.shift as any)?.name} {(assignment.shift as any)?.startTime}-{(assignment.shift as any)?.endTime}
                          {isDefault && <span className="ml-1 px-1 py-px rounded bg-gray-100 text-gray-500 text-[10px]">长期</span>}
                        </span>
                      ) : (
                        <span className="text-xs text-gray-400">未排班</span>
                      )}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-1">
                        {hasShift && !isDefault ? (
                          // 临时换班：移除后回退到默认班次
                          <button className="text-xs text-gray-400 hover:text-red-500" onClick={() => deleteAssignmentMutation.mutate(assignment.id)}>移除</button>
                        ) : isDefault ? (
                          // 长期排班：改班次 + 移除（清除默认班次）
                          <>
                            <select
                              value={inlineShiftId[emp.employeeId] || ''}
                              onChange={e => setInlineShiftId(prev => ({ ...prev, [emp.employeeId]: e.target.value }))}
                              className="h-7 rounded border border-gray-200 text-xs px-1 max-w-[100px]"
                            >
                              <option value="">选班次</option>
                              {(shifts || []).map((s: any) => (
                                <option key={s.id} value={s.id}>{s.name}</option>
                              ))}
                            </select>
                            <button
                              className="text-xs text-primary hover:underline whitespace-nowrap"
                              onClick={() => {
                                const shiftId = inlineShiftId[emp.employeeId]
                                if (shiftId) setDefaultShiftMutation.mutate({ employeeId: emp.employeeId, shiftId })
                              }}
                            >改班次</button>
                            <button
                              className="text-xs text-gray-400 hover:text-red-500 whitespace-nowrap"
                              onClick={() => setDefaultShiftMutation.mutate({ employeeId: emp.employeeId, shiftId: null })}
                            >移除</button>
                          </>
                        ) : (
                          // 无排班：选班次 + 排班（设为长期默认班次）
                          <>
                            <select
                              value={inlineShiftId[emp.employeeId] || ''}
                              onChange={e => setInlineShiftId(prev => ({ ...prev, [emp.employeeId]: e.target.value }))}
                              className="h-7 rounded border border-gray-200 text-xs px-1 max-w-[100px]"
                            >
                              <option value="">选班次</option>
                              {(shifts || []).map((s: any) => (
                                <option key={s.id} value={s.id}>{s.name}</option>
                              ))}
                            </select>
                            <button
                              className="text-xs text-primary hover:underline whitespace-nowrap"
                              onClick={() => {
                                const shiftId = inlineShiftId[emp.employeeId]
                                if (!shiftId) return toast.error('请选择班次')
                                setDefaultShiftMutation.mutate({ employeeId: emp.employeeId, shiftId })
                              }}
                            >排班</button>
                          </>
                        )}
                      </div>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>
        </Card>
        <Pagination page={page} pageSize={pageSize} total={total} onPageChange={setPage} onPageSizeChange={() => setPage(1)} />
        </>
      )}

      <Modal open={showAssign} onClose={() => setShowAssign(false)} title="批量排班">
        <div className="space-y-3">
          <div>
            <Label>选择班次</Label>
            <Select value={selectedShiftId} onChange={e => setSelectedShiftId(e.target.value)}>
              <option value="">请选择班次</option>
              {(shifts || []).map((s: any) => (
                <option key={s.id} value={s.id}>{s.name} ({s.startTime}-{s.endTime})</option>
              ))}
            </Select>
          </div>
          <div>
            <Label>选择员工（{selectedEmployeeIds.size} 人已选）</Label>
            <input
              type="text"
              placeholder="搜索员工姓名或部门..."
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              className="w-full px-3 py-2 mb-2 text-sm border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary"
            />
            <div className="max-h-60 overflow-y-auto border rounded-lg divide-y">
              {filteredEmployees.map((emp: any) => (
                <label key={emp.employeeId} className="flex items-center gap-2 px-3 py-2 hover:bg-gray-50 cursor-pointer">
                  <input type="checkbox" checked={selectedEmployeeIds.has(emp.employeeId)} onChange={() => toggleEmployee(emp.employeeId)} />
                  <span className="text-sm">{emp.name}</span>
                  <span className="text-xs text-gray-400">{emp.department}</span>
                </label>
              ))}
            </div>
          </div>
          <div className="flex justify-end gap-2 pt-2">
            <Button variant="secondary" onClick={() => setShowAssign(false)}>取消</Button>
            <Button onClick={handleBatchAssign} disabled={batchAssignMutation.isPending}>{batchAssignMutation.isPending ? '排班中...' : '确认排班'}</Button>
          </div>
        </div>
      </Modal>
    </div>
  )
}
