'use client'

import { useAuth } from '@/contexts/AuthContext'
import { useEffect, useState } from 'react'
import { portalAPI, type PortalOvertimeRequest } from '@/lib/api/portal'
import LoadingSpinner from '@/components/LoadingSpinner'
import { toast } from 'react-hot-toast'
import { CheckCircle2, XCircle, User } from 'lucide-react'

export default function ManagedOvertimeRequestsPage() {
  const { hasPermission } = useAuth()
  const [items, setItems] = useState<PortalOvertimeRequest[]>([])
  const [loading, setLoading] = useState(true)
  const [processingId, setProcessingId] = useState<string | null>(null)

  const canView = hasPermission('department_overtime_requests', 'view')
  const canApprove = hasPermission('department_overtime_requests', 'approve')

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

  useEffect(() => {
    if (canView) {
      loadData()
    } else {
      setLoading(false)
    }
  }, [canView])

  const handleApprove = async (attendanceId: string) => {
    try {
      setProcessingId(attendanceId)
      await portalAPI.approveManagedOvertimeRequest(attendanceId)
      toast.success('تمت الموافقة')
      loadData()
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'فشل التنفيذ')
    } finally {
      setProcessingId(null)
    }
  }

  const handleReject = async (attendanceId: string) => {
    const rejectedReason = window.prompt('اكتب سبب الرفض')
    if (!rejectedReason || !rejectedReason.trim()) return

    try {
      setProcessingId(attendanceId)
      await portalAPI.rejectManagedOvertimeRequest(attendanceId, rejectedReason.trim())
      toast.success('تم الرفض')
      loadData()
    } catch (error: any) {
      toast.error(error?.response?.data?.message || 'فشل التنفيذ')
    } finally {
      setProcessingId(null)
    }
  }

  if (!canView) {
    return <div className="text-center py-12 text-gray-500">الوصول مرفوض</div>
  }

  if (loading) return <LoadingSpinner />

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">طلبات الساعات الإضافية</h1>
        <p className="text-gray-600 mt-1">طلبات موظفي القسم المباشرين</p>
      </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) => (
              <div key={item.id} className="p-6 flex items-start justify-between gap-6">
                <div className="space-y-2">
                  <div className="flex items-center gap-2">
                    <User className="h-4 w-4 text-gray-400" />
                    <p className="font-semibold text-gray-900">
                      {item.employee?.firstName} {item.employee?.lastName}
                    </p>
                    <span className="text-xs text-gray-500">{item.employee?.uniqueEmployeeId}</span>
                  </div>

                  <p className="text-sm text-gray-600">
                    التاريخ: {new Date(item.date).toLocaleDateString()}
                  </p>
                  <p className="text-sm text-gray-600">عدد الساعات: {item.hours}</p>
                  <p className="text-sm text-gray-600">السبب: {item.reason}</p>
                </div>

                {canApprove ? (
                  <div className="flex gap-2">
                    <button
                      onClick={() => handleApprove(item.attendanceId)}
                      disabled={processingId === item.attendanceId}
                      className="inline-flex items-center gap-2 px-3 py-2 bg-green-600 text-white rounded-lg disabled:opacity-50"
                    >
                      <CheckCircle2 className="h-4 w-4" />
                      قبول
                    </button>

                    <button
                      onClick={() => handleReject(item.attendanceId)}
                      disabled={processingId === item.attendanceId}
                      className="inline-flex items-center gap-2 px-3 py-2 bg-red-600 text-white rounded-lg disabled:opacity-50"
                    >
                      <XCircle className="h-4 w-4" />
                      رفض
                    </button>
                  </div>
                ) : (
                  <span className="text-sm text-gray-500">عرض فقط</span>
                )}
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}