import { useState } from 'react'
import { toast } from 'sonner'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { CalendarClock, Plus, X, Clock, CheckCircle2, XCircle, RotateCcw, Send } from 'lucide-react'
import { portalApi } from '../../lib/api-services'
import { useConfirm } from '../../hooks/useConfirm'

const LEAVE_TYPE_MAP: Record<string, string> = {
  SICK: '病假',
  PERSONAL: '事假',
  ANNUAL: '年假',
  MATERNITY: '产假',
  OTHER: '其他',
}

const STATUS_MAP: Record<string, { label: string; color: string; icon: React.ReactNode }> = {
  PENDING: { label: '待审批', color: 'bg-amber-50 text-amber-700', icon: <Clock className="w-3 h-3" /> },
  APPROVED: { label: '已批准', color: 'bg-green-50 text-green-700', icon: <CheckCircle2 className="w-3 h-3" /> },
  REJECTED: { label: '已驳回', color: 'bg-red-50 text-red-700', icon: <XCircle className="w-3 h-3" /> },
  CANCELLED: { label: '已撤回', color: 'bg-gray-100 text-gray-500', icon: <RotateCcw className="w-3 h-3" /> },
}

const fmtDate = (d: string) => new Date(d).toLocaleDateString('zh-CN')

export default function MyLeave() {
  const queryClient = useQueryClient()
  const confirm = useConfirm()
  const [showForm, setShowForm] = useState(false)
  const [formLeaveType, setFormLeaveType] = useState('PERSONAL')
  const [formStartDate, setFormStartDate] = useState('')
  const [formEndDate, setFormEndDate] = useState('')
  const [formDays, setFormDays] = useState(1)
  const [formReason, setFormReason] = useState('')

  const { data: list = [], isLoading } = useQuery<any[]>({
    queryKey: ['portal-leaves'],
    queryFn: () => portalApi.myLeaves(),
  })

  const submitMutation = useMutation({
    mutationFn: (data: any) => portalApi.submitLeave(data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['portal-leaves'] })
      toast.success('休假申请已提交，等待审批')
      setShowForm(false)
      setFormLeaveType('PERSONAL'); setFormStartDate(''); setFormEndDate(''); setFormDays(1); setFormReason('')
    },
    onError: (err: any) => toast.error(err?.response?.data?.error?.message || '提交失败'),
  })

  const cancelMutation = useMutation({
    mutationFn: (id: string) => portalApi.cancelLeave(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['portal-leaves'] })
      toast.success('已撤回')
    },
  })

  const pendingCount = list.filter((r: any) => r.status === 'PENDING').length

  return (
    <div className="space-y-4">
      <div className="flex items-center gap-2">
        <CalendarClock className="w-5 h-5 text-primary" />
        <h1 className="text-base font-bold">我的休假</h1>
      </div>

      {/* 发起申请按钮 */}
      <button
        onClick={() => setShowForm(true)}
        className="w-full bg-primary text-white rounded-lg py-3 flex items-center justify-center gap-2 text-sm font-medium active:opacity-80 transition-opacity"
      >
        <Plus className="w-4 h-4" />
        发起休假申请
      </button>

      {/* 待审批提醒 */}
      {pendingCount > 0 && (
        <div className="bg-amber-50 rounded-lg px-3 py-2 flex items-center gap-2">
          <Clock className="w-4 h-4 text-amber-600" />
          <span className="text-xs text-amber-700">有 {pendingCount} 条申请待审批</span>
        </div>
      )}

      {/* 申请列表 */}
      {isLoading ? (
        <div className="text-center py-12 text-gray-400 text-sm">加载中...</div>
      ) : list.length === 0 ? (
        <div className="bg-white rounded-lg p-8 text-center">
          <p className="text-sm text-gray-400">暂无休假申请</p>
        </div>
      ) : (
        <div className="space-y-2">
          {list.map((item: any) => {
            const st = STATUS_MAP[item.status] || STATUS_MAP.PENDING
            return (
              <div key={item.id} className="bg-white rounded-lg p-3 space-y-2">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <span className="text-sm font-medium">{LEAVE_TYPE_MAP[item.leaveType] || item.leaveType}</span>
                    <span className="text-xs text-gray-500">{item.days} 天</span>
                  </div>
                  <span className={`inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs ${st.color}`}>
                    {st.icon}{st.label}
                  </span>
                </div>
                <div className="text-xs text-gray-600">
                  {fmtDate(item.startDate)} ~ {fmtDate(item.endDate)}
                </div>
                {item.reason && (
                  <div className="text-xs text-gray-500">事由：{item.reason}</div>
                )}
                {item.approveRemark && (
                  <div className="text-xs text-gray-500 border-t pt-1 mt-1">
                    审批意见：{item.approveRemark}
                  </div>
                )}
                {item.status === 'PENDING' && (
                  <button
                    onClick={async () => {
                      if (await confirm({ title: '撤回申请', message: '确认撤回该申请？' })) cancelMutation.mutate(item.id)
                    }}
                    className="text-xs text-gray-400 hover:text-amber-600 flex items-center gap-1"
                  >
                    <RotateCcw className="w-3 h-3" />撤回
                  </button>
                )}
              </div>
            )
          })}
        </div>
      )}

      {/* 申请表单弹窗 */}
      {showForm && (
        <div className="fixed inset-0 bg-black/30 flex items-center justify-center z-50 p-4" onClick={() => setShowForm(false)}>
          <div className="bg-white rounded-xl max-w-md w-full p-5 space-y-4" onClick={(e) => e.stopPropagation()}>
            <div className="flex items-center justify-between">
              <h3 className="text-sm font-bold flex items-center gap-2">
                <Send className="w-4 h-4 text-primary" />休假申请
              </h3>
              <button onClick={() => setShowForm(false)} className="text-gray-400 hover:text-gray-600">
                <X className="w-4 h-4" />
              </button>
            </div>

            <div className="space-y-3">
              <div>
                <label className="text-xs text-gray-500 mb-1 block">休假类型</label>
                <select
                  value={formLeaveType}
                  onChange={(e) => setFormLeaveType(e.target.value)}
                  className="w-full h-10 rounded-lg border border-gray-200 bg-white px-3 text-sm"
                >
                  {Object.entries(LEAVE_TYPE_MAP).map(([k, v]) => (
                    <option key={k} value={k}>{v}</option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="text-xs text-gray-500 mb-1 block">开始日期</label>
                  <input
                    type="date"
                    value={formStartDate}
                    onChange={(e) => setFormStartDate(e.target.value)}
                    className="w-full h-10 rounded-lg border border-gray-200 px-3 text-sm"
                  />
                </div>
                <div>
                  <label className="text-xs text-gray-500 mb-1 block">结束日期</label>
                  <input
                    type="date"
                    value={formEndDate}
                    onChange={(e) => setFormEndDate(e.target.value)}
                    className="w-full h-10 rounded-lg border border-gray-200 px-3 text-sm"
                  />
                </div>
              </div>

              <div>
                <label className="text-xs text-gray-500 mb-1 block">请假天数</label>
                <input
                  type="number"
                  min={0.5}
                  step={0.5}
                  value={formDays}
                  onChange={(e) => setFormDays(Number(e.target.value))}
                  className="w-full h-10 rounded-lg border border-gray-200 px-3 text-sm"
                />
              </div>

              <div>
                <label className="text-xs text-gray-500 mb-1 block">事由</label>
                <textarea
                  value={formReason}
                  onChange={(e) => setFormReason(e.target.value)}
                  placeholder="请简要说明请假原因"
                  rows={3}
                  className="w-full rounded-lg border border-gray-200 px-3 py-2 text-sm resize-none"
                />
              </div>

              <button
                onClick={() => {
                  if (!formStartDate || !formEndDate) { toast.error('请选择日期'); return }
                  submitMutation.mutate({
                    leaveType: formLeaveType,
                    startDate: formStartDate,
                    endDate: formEndDate,
                    days: formDays,
                    reason: formReason,
                  })
                }}
                disabled={submitMutation.isPending}
                className="w-full bg-primary text-white rounded-lg py-2.5 text-sm font-medium disabled:opacity-50"
              >
                {submitMutation.isPending ? '提交中...' : '提交申请'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}
