'use client'

import { useEffect, useState } from 'react'
import { portalAPI, type PortalOvertimeRequest } from '@/lib/api/portal'
import Modal from '@/components/Modal'
import LoadingSpinner from '@/components/LoadingSpinner'
import { toast } from 'react-hot-toast'
import { Plus, Clock3 } from 'lucide-react'

const STATUS_MAP: Record<string, { label: string; color: string }> = {
  PENDING: { label: 'قيد المراجعة', color: 'bg-amber-100 text-amber-800' },
  APPROVED: { label: 'مقبول', color: 'bg-green-100 text-green-800' },
  REJECTED: { label: 'مرفوض', color: 'bg-red-100 text-red-800' },
}

export default function PortalOvertimePage() {
  const [items, setItems] = useState<PortalOvertimeRequest[]>([])
  const [loading, setLoading] = useState(true)
  const [submitting, setSubmitting] = useState(false)
  const [open, setOpen] = useState(false)
  const [editingId, setEditingId] = useState<string | null>(null)

  const [form, setForm] = useState({
    date: '',
    hours: '',
    reason: '',
  })

  const loadData = async () => {
    try {
      setLoading(true)
      const data = await portalAPI.getOvertimeRequests()
      setItems(data)
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'فشل تحميل الطلبات')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadData()
  }, [])

  const resetForm = () => {
    setForm({ date: '', hours: '', reason: '' })
    setEditingId(null)
  }

  const openEdit = (item: PortalOvertimeRequest) => {
    setEditingId(item.attendanceId || item.id)
    setForm({
      date: String(item.date).split('T')[0],
      hours: String(item.hours ?? ''),
      reason: item.reason || '',
    })
    setOpen(true)
  }

  const handleDelete = async (id: string) => {
    if (!confirm('حذف طلب الساعات الإضافية؟')) return
    try {
      await portalAPI.deleteOvertimeRequest(id)
      toast.success('تم الحذف')
      loadData()
    } catch (err: any) {
      toast.error(err?.response?.data?.message || 'فشل الحذف')
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    const hours = parseFloat(form.hours)

    if (!form.date) {
      toast.error('اختر التاريخ')
      return
    }

    if (!hours || hours <= 0) {
      toast.error('أدخل عدد ساعات صالح')
      return
    }

    if (!form.reason.trim()) {
      toast.error('سبب الساعات الإضافية مطلوب')
      return
    }

    try {
      setSubmitting(true)
      if (editingId) {
        await portalAPI.updateOvertimeRequest(editingId, {
          hours,
          reason: form.reason.trim(),
        })
        toast.success('تم تعديل الطلب')
      } else {
        await portalAPI.submitOvertimeRequest({
          date: form.date,
          hours,
          reason: form.reason.trim(),
        })
        toast.success('تم إرسال الطلب')
      }
      setOpen(false)
      resetForm()
      loadData()
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'فشل إرسال الطلب')
    } finally {
      setSubmitting(false)
    }
  }

  if (loading) return <LoadingSpinner />

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">الساعات الإضافية</h1>
          <p className="text-gray-600 mt-1">إرسال ومتابعة طلبات الساعات الإضافية</p>
        </div>

        <button
          onClick={() => { resetForm(); setOpen(true) }}
          className="inline-flex items-center gap-2 px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700"
        >
          <Plus className="h-4 w-4" />
          إضافة طلب
        </button>
      </div>

      <div className="bg-white rounded-xl shadow border border-gray-100 overflow-hidden">
        {items.length === 0 ? (
          <div className="p-10 text-center text-gray-500">لا توجد طلبات حتى الآن</div>
        ) : (
          <div className="divide-y divide-gray-200">
            {items.map((item) => {
              const meta = STATUS_MAP[item.status] || STATUS_MAP.PENDING
              return (
                <div key={item.id} className="p-6 flex items-start justify-between">
                  <div className="space-y-2">
                    <div className="flex items-center gap-2">
                      <Clock3 className="h-4 w-4 text-gray-500" />
                      <p className="font-semibold text-gray-900">
                        {new Date(item.date).toLocaleDateString()}
                      </p>
                    </div>
                    <p className="text-sm text-gray-600">عدد الساعات: {item.hours}</p>
                    <p className="text-sm text-gray-600">السبب: {item.reason}</p>
                    {item.rejectedReason ? (
                      <p className="text-sm text-red-600">سبب الرفض: {item.rejectedReason}</p>
                    ) : null}
                  </div>

                  <div className="flex flex-col items-end gap-2">
                    <span className={`px-3 py-1 rounded-full text-xs font-medium ${meta.color}`}>
                      {meta.label}
                    </span>
                    {item.status === 'PENDING' && (
                      <div className="flex gap-2">
                        <button type="button" onClick={() => openEdit(item)} className="text-xs text-teal-600 hover:underline">تعديل</button>
                        <button type="button" onClick={() => handleDelete(item.attendanceId || item.id)} className="text-xs text-red-600 hover:underline">حذف</button>
                      </div>
                    )}
                  </div>
                </div>
              )
            })}
          </div>
        )}
      </div>

      <Modal
        isOpen={open}
        onClose={() => { setOpen(false); resetForm() }}
        title={editingId ? 'تعديل طلب الساعات الإضافية' : 'طلب ساعات إضافية'}
      >
        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block mb-1 text-sm font-medium text-gray-700">التاريخ</label>
            <input
              type="date"
              value={form.date}
              onChange={(e) => setForm((p) => ({ ...p, date: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              disabled={!!editingId}
              required
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium text-gray-700">عدد الساعات</label>
            <input
              type="number"
              min="0.5"
              step="0.5"
              value={form.hours}
              onChange={(e) => setForm((p) => ({ ...p, hours: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              required
            />
          </div>

          <div>
            <label className="block mb-1 text-sm font-medium text-gray-700">السبب</label>
            <textarea
              value={form.reason}
              onChange={(e) => setForm((p) => ({ ...p, reason: e.target.value }))}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg"
              rows={4}
              required
            />
          </div>

          <div className="flex justify-end gap-2 pt-2">
            <button
              type="button"
              onClick={() => { setOpen(false); resetForm() }}
              className="px-4 py-2 border border-gray-300 rounded-lg"
            >
              إلغاء
            </button>
            <button
              type="submit"
              disabled={submitting}
              className="px-4 py-2 bg-teal-600 text-white rounded-lg hover:bg-teal-700 disabled:opacity-50"
            >
              {submitting ? 'جارٍ الإرسال...' : (editingId ? 'حفظ التعديل' : 'إرسال')}
            </button>
          </div>
        </form>
      </Modal>
    </div>
  )
}