"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Calendar, Plus, Search, Check, X, Clock, Trash2, ChevronDown, Download } from "lucide-react";
import { cn } from "@/lib/utils";
import jsPDF from "jspdf";
import autoTable from "jspdf-autotable";

interface Leave {
  id: string;
  type: string;
  startDate: string;
  endDate: string;
  reason: string;
  status: string;
  employee: {
    firstName: string;
    lastName: string;
    employeeId: string;
    department: string;
  };
}

export default function LeavePage() {
  const [activeTab, setActiveTab] = useState<"requests" | "summary">("requests");
  const [leaves, setLeaves] = useState<Leave[]>([]);
  const [leaveSummary, setLeaveSummary] = useState<any[]>([]);
  const [employees, setEmployees] = useState<any[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [filterDate, setFilterDate] = useState("");
  const [empSearch, setEmpSearch] = useState("");
  const [empDropOpen, setEmpDropOpen] = useState(false);
  const empDropRef = useRef<HTMLDivElement>(null);
  const [summaryPage, setSummaryPage] = useState(1);
  const summaryPerPage = 10;
  const [isExporting, setIsExporting] = useState(false);
  const [selectedEmployees, setSelectedEmployees] = useState<Set<string>>(new Set());
  const [selectAll, setSelectAll] = useState(false);

  const exportToPDF = async () => {
    if (selectedEmployees.size === 0) {
      alert("Please select at least one employee to export");
      return;
    }

    try {
      setIsExporting(true);
      const res = await authFetch(`${API}/dash/leave-details`);
      const data = await res.json();

      if (!res.ok || !Array.isArray(data)) {
        alert("Failed to fetch leave details for export");
        return;
      }

      // Filter data to only include selected employees
      const filteredData = data.filter((emp: any) => selectedEmployees.has(emp.employeeId));

      if (filteredData.length === 0) {
        alert("No selected employees found");
        return;
      }

      const doc = new jsPDF();
      const currentYear = new Date().getFullYear();

      // Title
      doc.setFontSize(18);
      doc.text(`Leave Summary - ${currentYear}`, 14, 22);
      doc.setFontSize(11);
      doc.text(`Generated on ${new Date().toLocaleDateString()}`, 14, 30);
      doc.text(`Selected Employees: ${filteredData.length}`, 14, 38);

      let yPos = 48;

      filteredData.forEach((emp) => {
        // Check if we need a new page
        if (yPos > 250) {
          doc.addPage();
          yPos = 20;
        }

        // Employee header
        doc.setFontSize(12);
        doc.setFont("helvetica", "bold");
        doc.text(
          `${emp.firstName} ${emp.lastName} (${emp.employeeId}) - ${emp.department}`,
          14,
          yPos
        );
        yPos += 7;

        doc.setFontSize(10);
        doc.setFont("helvetica", "normal");
        doc.text(`Total Leaves: ${emp.totalLeaves} / ${emp.totalAllowance} | Remaining: ${emp.remaining}`, 14, yPos);
        yPos += 5;

        if (emp.leaveDetails.length > 0) {
          // Create table for leave details
          const tableData = emp.leaveDetails.map((leave: any) => [
            leave.date,
            leave.type,
            leave.reason || "-"
          ]);

          autoTable(doc, {
            startY: yPos,
            head: [["Date", "Type", "Reason"]],
            body: tableData,
            theme: "grid",
            headStyles: { fillColor: [66, 139, 202] },
            styles: { fontSize: 9 },
            margin: { left: 14, right: 14 },
          });

          yPos = (doc as any).lastAutoTable.finalY + 10;
        } else {
          doc.text("No leaves taken this year", 14, yPos);
          yPos += 10;
        }

        yPos += 5;
      });

      doc.setProperties({
        title: `Leave-Summary-${currentYear}`,
        subject: `Leave-Summary-${currentYear}`,
      });
      const blobUrl = doc.output("bloburl");
      window.open(blobUrl, "_blank");
    } catch (error) {
      console.error("Error exporting PDF:", error);
      alert("Failed to export PDF");
    } finally {
      setIsExporting(false);
    }
  };

  const toggleEmployeeSelection = (employeeId: string) => {
    setSelectedEmployees((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(employeeId)) {
        newSet.delete(employeeId);
      } else {
        newSet.add(employeeId);
      }
      return newSet;
    });
  };

  useEffect(() => {
    const handler = (e: MouseEvent) => { if (empDropRef.current && !empDropRef.current.contains(e.target as Node)) setEmpDropOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const [formData, setFormData] = useState({
    employeeId: "",
    type: "ANNUAL",
    startDate: "",
    endDate: "",
    reason: "",
  });

  const fetchLeaves = async () => {
    try {
      setIsLoading(true);
      const res = await authFetch(`${API}/dash/leaves`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) setLeaves(data);
      else setLeaves([]);
    } catch (e) {
      setLeaves([]);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchLeaveSummary = async () => {
    try {
      setIsLoading(true);
      const res = await authFetch(`${API}/dash/leave-summary`);
      const data = await res.json();
      if (res.ok && Array.isArray(data)) setLeaveSummary(data);
      else setLeaveSummary([]);
    } catch (e) {
      setLeaveSummary([]);
    } finally {
      setIsLoading(false);
    }
  };

  const fetchEmployees = async () => {
    try {
      const res = await authFetch(`${API}/dash/employees?limit=1000`);
      const raw = await res.json();
      if (res.ok) setEmployees(Array.isArray(raw) ? raw : (raw.employees ?? []));
    } catch (e) {
      console.error(e);
    }
  };

  useEffect(() => {
    fetchEmployees();
    setFormData(prev => ({
      ...prev,
      startDate: new Date().toISOString().split("T")[0],
      endDate: new Date().toISOString().split("T")[0],
    }));
  }, []);

  useEffect(() => {
    if (activeTab === "requests") {
      fetchLeaves();
    } else {
      fetchLeaveSummary();
    }
  }, [activeTab]);

  // Reset page when search changes
  useEffect(() => {
    if (activeTab === "summary") {
      setSummaryPage(1);
    }
  }, [searchQuery, activeTab]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const res = await authFetch(`${API}/dash/leaves`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(formData),
      });

      if (!res.ok) {
        const error = await res.json();
        alert(`Error: ${error.message}`);
        return;
      }
      
      setIsSlideOverOpen(false);
      fetchLeaves();
    } catch (err) {
      console.error(err);
    }
  };

  const handleUpdateStatus = async (id: string, status: string) => {
    try {
      await authFetch(`${API}/dash/leaves/${id}/status`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status })
      });
      fetchLeaves();
    } catch (err) {
      console.error(err);
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Delete this leave request?")) return;
    try {
      await authFetch(`${API}/dash/leaves/${id}`, { method: "DELETE" });
      fetchLeaves();
    } catch (e) {
      console.error(e);
    }
  };

  const filteredLeaves = leaves.filter((l) => {
    const q = searchQuery.toLowerCase();
    const leaveDate = new Date(l.startDate);
    const dateStr = `${leaveDate.getFullYear()}-${String(leaveDate.getMonth() + 1).padStart(2, '0')}-${String(leaveDate.getDate()).padStart(2, '0')}`;

    return (
      (l.employee?.firstName.toLowerCase().includes(q) ||
      l.employee?.lastName.toLowerCase().includes(q) ||
      l.type.toLowerCase().includes(q)) &&
      (!filterDate || dateStr === filterDate)
    );
  });

  // Pagination for summary
  const filteredSummary = leaveSummary.filter((emp) => {
    const q = searchQuery.toLowerCase();
    return (
      emp.firstName.toLowerCase().includes(q) ||
      emp.lastName.toLowerCase().includes(q) ||
      (emp.department || "").toLowerCase().includes(q) ||
      (emp.employeeId || "").toLowerCase().includes(q)
    );
  });
  const summaryTotalPages = Math.ceil(filteredSummary.length / summaryPerPage);
  const summaryStartIndex = (summaryPage - 1) * summaryPerPage;
  const summaryEndIndex = summaryStartIndex + summaryPerPage;
  const paginatedSummary = filteredSummary.slice(summaryStartIndex, summaryEndIndex);

  const toggleSelectAll = () => {
    if (selectAll) {
      setSelectedEmployees(new Set());
    } else {
      const allIds = filteredSummary.map((emp) => emp.employeeId);
      setSelectedEmployees(new Set(allIds));
    }
    setSelectAll(!selectAll);
  };

  return (
    <div className="space-y-6 relative">
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-bold leading-7 text-gray-900 sm:truncate sm:text-3xl sm:tracking-tight">
            Leave Management
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            {activeTab === "requests" ? "Manage factory time-off and process requests." : "View employee-wise leave summary for the current year."}
          </p>
        </div>

        <div className="flex items-center gap-3">
          <div className="flex items-center bg-gray-100 rounded-lg p-1">
            <button
              onClick={() => setActiveTab("requests")}
              className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                activeTab === "requests"
                  ? "bg-white text-gray-900 shadow-sm"
                  : "text-gray-600 hover:text-gray-900"
              }`}
            >
              Requests
            </button>
            <button
              onClick={() => setActiveTab("summary")}
              className={`px-4 py-2 text-sm font-medium rounded-md transition-colors ${
                activeTab === "summary"
                  ? "bg-white text-gray-900 shadow-sm"
                  : "text-gray-600 hover:text-gray-900"
              }`}
            >
              Summary
            </button>
          </div>
          {activeTab === "requests" && (
            <button
              onClick={() => setIsSlideOverOpen(true)}
              className="inline-flex items-center justify-center rounded-lg border border-transparent bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors"
            >
              <Plus className="mr-2 h-4 w-4" />
              File Leave Request
            </button>
          )}
          {activeTab === "summary" && (
            <button
              onClick={exportToPDF}
              disabled={isExporting}
              className="inline-flex items-center justify-center rounded-lg border border-transparent bg-brand-600 px-4 py-2 text-sm font-medium text-white shadow-sm hover:bg-brand-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Download className="mr-2 h-4 w-4" />
              {isExporting ? "Exporting..." : "Export PDF"}
            </button>
          )}
        </div>
      </div>

      <div className="rounded-2xl bg-white shadow-sm border border-[#E2E8F0] overflow-hidden">
        <div className="p-6 border-b border-gray-200 bg-gray-50/50 flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div className="relative max-w-md w-full">
            <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
              <Search className="h-4 w-4 text-gray-400" />
            </div>
            <input
              type="text"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="block w-full rounded-lg border-0 py-2.5 pl-10 pr-3 text-gray-900 ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-brand-600 sm:text-sm sm:leading-6"
              placeholder="Search by Employee..."
            />
          </div>

          <div className="flex items-center gap-2">
            <label className="text-xs font-bold text-gray-400 uppercase">Start Date:</label>
            <input
              type="date"
              value={filterDate}
              onChange={(e) => setFilterDate(e.target.value)}
              className="rounded-lg border-0 py-2 px-3 text-gray-900 ring-1 ring-inset ring-gray-300 focus:ring-2 focus:ring-brand-600 sm:text-sm"
            />
            {filterDate && (
              <button 
                onClick={() => setFilterDate("")}
                className="text-xs text-brand-600 font-bold hover:underline"
              >
                Clear
              </button>
            )}
          </div>
        </div>

        {/* Table / Empty State */}
        {activeTab === "requests" ? (
          <>
            {isLoading ? (
              <div className="p-12 text-center text-sm text-gray-500">Loading leave requests...</div>
            ) : filteredLeaves.length === 0 ? (
              <div className="flex flex-col items-center justify-center p-16 text-center">
                <div className="flex h-16 w-16 items-center justify-center rounded-full bg-brand-50 mb-4">
                  <Calendar className="h-8 w-8 text-brand-600" />
                </div>
                <h3 className="text-lg font-medium text-gray-900">No leave requests</h3>
                <p className="mt-1 text-sm text-gray-500 max-w-sm">
                  All employees are present. Click 'File Leave Request' to create one.
                </p>
              </div>
            ) : (
              <div className="overflow-x-auto">
                <table className="min-w-full divide-y divide-gray-300">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="py-3.5 pl-6 pr-3 text-left text-sm font-semibold text-gray-900">Employee</th>
                      <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Leave Type</th>
                      <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Duration</th>
                      <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Status</th>
                      <th className="py-3.5 px-6 text-center text-sm font-semibold text-gray-900">Action</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-gray-200 bg-white">
                    {filteredLeaves.map((leave) => (
                      <motion.tr
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        key={leave.id}
                        className="hover:bg-gray-50 transition-colors group"
                      >
                        <td className="whitespace-nowrap py-4 pl-6 pr-3 text-sm">
                          <div className="flex items-center">
                            <div className="h-10 w-10 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 font-bold uppercase ring-2 ring-white">
                              {leave.employee?.firstName?.charAt(0)}{leave.employee?.lastName?.charAt(0)}
                            </div>
                            <div className="ml-4">
                              <div className="font-medium text-gray-900">{leave.employee?.firstName} {leave.employee?.lastName}</div>
                              <div className="mt-1 text-gray-500 text-xs font-mono">{leave.employee?.department}</div>
                            </div>
                          </div>
                        </td>
                        <td className="whitespace-nowrap px-3 py-4 text-sm font-medium text-gray-900">
                          {leave.type}
                        </td>
                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                          <div className="flex items-center">
                            <Clock className="mr-1.5 h-3.5 w-3.5 text-gray-400" />
                            {new Date(leave.startDate).toLocaleDateString()} &rarr; {new Date(leave.endDate).toLocaleDateString()}
                          </div>
                        </td>
                        <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                          <span className={cn(
                            "inline-flex items-center rounded-md px-2 py-1 text-xs font-medium ring-1 ring-inset",
                            leave.status === 'APPROVED' ? "bg-green-50 text-green-700 ring-green-600/20" :
                            leave.status === 'REJECTED' ? "bg-red-50 text-red-700 ring-red-600/20" :
                            "bg-yellow-50 text-yellow-800 ring-yellow-600/20"
                          )}>
                            {leave.status}
                          </span>
                        </td>
                        <td className="whitespace-nowrap py-4 px-6 text-center text-sm font-medium">
                          {leave.status === 'PENDING' && (
                            <div className="flex items-center justify-center gap-2">
                               <button onClick={() => handleUpdateStatus(leave.id, 'APPROVED')} className="text-green-600 hover:text-green-900 bg-green-50 p-1.5 rounded">
                                <Check className="h-4 w-4" />
                              </button>
                               <button onClick={() => handleUpdateStatus(leave.id, 'REJECTED')} className="text-red-600 hover:text-red-900 bg-red-50 p-1.5 rounded">
                                <X className="h-4 w-4" />
                              </button>
                            </div>
                          )}
                          {leave.status !== 'PENDING' && (
                             <button onClick={() => handleDelete(leave.id)} className="text-gray-400 hover:text-red-600">
                                <Trash2 className="h-4 w-4 mx-auto" />
                             </button>
                          )}
                        </td>
                      </motion.tr>
                    ))}
                  </tbody>
                </table>
              </div>
            )}
          </>
        ) : (
          <>
            {isLoading ? (
              <div className="p-12 text-center text-sm text-gray-500">Loading leave summary...</div>
            ) : leaveSummary.length === 0 ? (
              <div className="flex flex-col items-center justify-center p-16 text-center">
                <div className="flex h-16 w-16 items-center justify-center rounded-full bg-brand-50 mb-4">
                  <Calendar className="h-8 w-8 text-brand-600" />
                </div>
                <h3 className="text-lg font-medium text-gray-900">No leave data</h3>
                <p className="mt-1 text-sm text-gray-500 max-w-sm">
                  No leave records found for the current year.
                </p>
              </div>
            ) : (
              <>
                <div className="overflow-x-auto">
                  <table className="min-w-full divide-y divide-gray-300">
                    <thead className="bg-gray-50">
                      <tr>
                        <th className="py-3.5 pl-6 pr-3 text-center text-sm font-semibold text-gray-900 w-12">
                          <input
                            type="checkbox"
                            checked={selectAll}
                            onChange={toggleSelectAll}
                            className="w-4 h-4 text-brand-600 rounded border-gray-300 focus:ring-brand-500"
                          />
                        </th>
                        <th className="py-3.5 px-3 text-left text-sm font-semibold text-gray-900">Employee</th>
                        <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Department</th>
                        <th className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">Leaves Taken</th>
                        <th className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">Total Allowance</th>
                        <th className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">Remaining</th>
                        <th className="px-3 py-3.5 text-center text-sm font-semibold text-gray-900">Usage</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-gray-200 bg-white">
                      {paginatedSummary.map((emp) => (
                        <motion.tr
                          initial={{ opacity: 0 }}
                          animate={{ opacity: 1 }}
                          key={emp.employeeIdInternal}
                          className="hover:bg-gray-50 transition-colors"
                        >
                          <td className="whitespace-nowrap py-4 pl-6 pr-3 text-center">
                            <input
                              type="checkbox"
                              checked={selectedEmployees.has(emp.employeeId)}
                              onChange={() => toggleEmployeeSelection(emp.employeeId)}
                              className="w-4 h-4 text-brand-600 rounded border-gray-300 focus:ring-brand-500"
                            />
                          </td>
                          <td className="whitespace-nowrap py-4 pl-3 pr-3 text-sm">
                            <div className="flex items-center">
                              <div className="h-10 w-10 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 font-bold uppercase ring-2 ring-white">
                                {emp.firstName.charAt(0)}{emp.lastName.charAt(0)}
                              </div>
                              <div className="ml-4">
                                <div className="font-medium text-gray-900">{emp.firstName} {emp.lastName}</div>
                                <div className="mt-1 text-gray-500 text-xs font-mono">{emp.employeeId}</div>
                              </div>
                            </div>
                          </td>
                          <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                            {emp.department}
                          </td>
                          <td className="whitespace-nowrap px-3 py-4 text-center text-sm font-medium text-gray-900">
                            {emp.leavesTaken}
                          </td>
                          <td className="whitespace-nowrap px-3 py-4 text-center text-sm text-gray-500">
                            {emp.totalAllowance}
                          </td>
                          <td className="whitespace-nowrap px-3 py-4 text-center text-sm font-medium text-gray-900">
                            {emp.remaining}
                          </td>
                          <td className="whitespace-nowrap px-3 py-4 text-center text-sm">
                            <div className="flex items-center justify-center gap-2">
                              <div className="w-24 h-2 bg-gray-200 rounded-full overflow-hidden">
                                <div
                                  className={`h-full rounded-full ${
                                    emp.usedPercentage > 100 ? 'bg-red-500' :
                                    emp.usedPercentage > 75 ? 'bg-yellow-500' :
                                    'bg-green-500'
                                  }`}
                                  style={{ width: `${Math.min(emp.usedPercentage, 100)}%` }}
                                />
                              </div>
                              <span className="text-xs text-gray-500">{emp.usedPercentage}%</span>
                            </div>
                          </td>
                        </motion.tr>
                      ))}
                    </tbody>
                  </table>
                </div>

                {/* Pagination Controls */}
                <div className="flex items-center justify-between px-6 py-4 border-t border-gray-200 bg-gray-50">
                  <div className="text-sm text-gray-500">
                    Showing {summaryStartIndex + 1} to {Math.min(summaryEndIndex, filteredSummary.length)} of {filteredSummary.length} employees
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => setSummaryPage(p => Math.max(1, p - 1))}
                      disabled={summaryPage === 1}
                      className="px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Previous
                    </button>
                    {Array.from({ length: summaryTotalPages }, (_, i) => i + 1).map((page) => (
                      <button
                        key={page}
                        onClick={() => setSummaryPage(page)}
                        className={`px-3 py-1.5 text-sm font-medium rounded-md ${
                          summaryPage === page
                            ? "bg-brand-600 text-white"
                            : "bg-white text-gray-700 border border-gray-300 hover:bg-gray-50"
                        }`}
                      >
                        {page}
                      </button>
                    ))}
                    <button
                      onClick={() => setSummaryPage(p => Math.min(summaryTotalPages, p + 1))}
                      disabled={summaryPage === summaryTotalPages}
                      className="px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                      Next
                    </button>
                  </div>
                </div>
              </>
            )}
          </>
        )}
      </div>

      {/* Slide-over for Add Leave */}
      <AnimatePresence>
        {isSlideOverOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsSlideOverOpen(false)}
              className="fixed inset-0 bg-gray-900/40 backdrop-blur-sm z-40 transition-opacity"
            />
            <motion.div
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", bounce: 0, duration: 0.4 }}
              className="fixed inset-y-0 right-0 z-50 w-full max-w-md bg-white text-gray-900 shadow-2xl flex flex-col border-l border-gray-200"
            >
              <div className="flex items-center justify-between px-6 py-5 border-b border-gray-100 bg-white/50 backdrop-blur-md">
                <div className="flex items-center gap-3">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-brand-50 border border-brand-100">
                    <Calendar className="h-5 w-5 text-brand-600" />
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-gray-900">File Leave Request</h2>
                    <p className="text-xs text-gray-500 font-medium mt-0.5">Submit time-off details</p>
                  </div>
                </div>
                <button 
                  onClick={() => setIsSlideOverOpen(false)}
                  className="rounded-full p-2 text-gray-400 hover:bg-gray-100 hover:text-gray-600 transition-colors"
                >
                  <X className="h-5 w-5" />
                </button>
              </div>

              <div className="flex-1 overflow-y-auto px-6 py-6 custom-scrollbar bg-gray-50/30">
                <form id="leave-form" onSubmit={handleSubmit} className="space-y-6">
                  
                  <div className="space-y-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-900/5">
                    
                    <div>
                      <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Select Employee</label>
                      <div className="relative" ref={empDropRef}>
                        <div
                          onClick={() => setEmpDropOpen(o => !o)}
                          className={cn(
                            "flex items-center gap-2 w-full rounded-lg border px-3 py-2.5 bg-white cursor-pointer text-sm",
                            empDropOpen ? "border-brand-600 ring-2 ring-brand-600/20" : "border-gray-200 ring-1 ring-gray-200"
                          )}
                        >
                          <Search className="h-3.5 w-3.5 text-gray-400 flex-shrink-0" />
                          <input
                            type="text"
                            value={empSearch}
                            onChange={e => { setEmpSearch(e.target.value); setEmpDropOpen(true); }}
                            onClick={e => { e.stopPropagation(); setEmpDropOpen(true); }}
                            placeholder={
                              formData.employeeId
                                ? (() => { const f = employees.find(e => e.id === formData.employeeId); return f ? `${f.firstName} ${f.lastName}` : "Select employee…"; })()
                                : "Search employee…"
                            }
                            className="flex-1 bg-transparent outline-none text-gray-900 placeholder:text-gray-400 text-sm"
                          />
                          {formData.employeeId
                            ? <button type="button" onClick={e => { e.stopPropagation(); setFormData(f => ({...f, employeeId: ""})); setEmpSearch(""); }} className="text-gray-300 hover:text-gray-500"><X className="h-3.5 w-3.5" /></button>
                            : <ChevronDown className={cn("h-3.5 w-3.5 text-gray-400 flex-shrink-0 transition-transform", empDropOpen && "rotate-180")} />
                          }
                        </div>
                        {empDropOpen && (
                          <div className="absolute z-20 mt-1 w-full rounded-xl border border-gray-200 bg-white shadow-lg max-h-52 overflow-y-auto">
                            {employees
                              .filter(e => { const q = empSearch.toLowerCase(); return !q || `${e.firstName} ${e.lastName}`.toLowerCase().includes(q) || (e.employeeId ?? "").toLowerCase().includes(q) || (e.department ?? "").toLowerCase().includes(q); })
                              .map(emp => (
                                <button type="button" key={emp.id}
                                  onClick={() => { setFormData(f => ({...f, employeeId: emp.id})); setEmpSearch(""); setEmpDropOpen(false); }}
                                  className={cn("w-full flex items-center gap-3 px-3 py-2.5 text-left hover:bg-gray-50 transition-colors", formData.employeeId === emp.id && "bg-brand-50")}
                                >
                                  <div className="h-7 w-7 flex-shrink-0 rounded-full bg-brand-100 flex items-center justify-center text-brand-700 text-xs font-bold uppercase">
                                    {emp.firstName.charAt(0)}{emp.lastName.charAt(0)}
                                  </div>
                                  <div className="flex-1 min-w-0">
                                    <p className="text-sm font-semibold text-gray-900 truncate">{emp.firstName} {emp.lastName}</p>
                                    <p className="text-xs text-gray-400">{emp.department ?? ""}</p>
                                  </div>
                                  {formData.employeeId === emp.id && <Check className="h-4 w-4 text-brand-600 flex-shrink-0" />}
                                </button>
                              ))}
                            {employees.filter(e => { const q = empSearch.toLowerCase(); return !q || `${e.firstName} ${e.lastName}`.toLowerCase().includes(q) || (e.employeeId ?? "").toLowerCase().includes(q); }).length === 0 && (
                              <p className="px-3 py-4 text-sm text-gray-400 text-center">No employees found</p>
                            )}
                          </div>
                        )}
                      </div>
                      <input type="text" required readOnly value={formData.employeeId} className="sr-only" tabIndex={-1} />
                    </div>

                    <div>
                      <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Leave Type</label>
                      <select required value={formData.type} onChange={e => setFormData({...formData, type: e.target.value})} className="block w-full rounded-lg border-0 py-2.5 pl-3 pr-8 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-brand-600 sm:text-sm sm:leading-6 transition-colors shadow-sm appearance-none">
                        <option value="ANNUAL">Annual Leave</option>
                        <option value="CASUAL">Casual Leave</option>
                        <option value="SICK">Sick Form</option>
                        <option value="MATERNITY">Maternity Leave</option>
                        <option value="UNPAID">Unpaid / Short Leave</option>
                      </select>
                    </div>

                    <div className="grid grid-cols-2 gap-4">
                      <div>
                        <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Start Date</label>
                        <input required type="date" value={formData.startDate} onChange={e => setFormData({...formData, startDate: e.target.value})} className="block w-full rounded-lg border-0 py-2.5 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-inset focus:ring-brand-600 sm:text-sm sm:leading-6 transition-colors shadow-sm" />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">End Date</label>
                        <input required type="date" value={formData.endDate} onChange={e => setFormData({...formData, endDate: e.target.value})} className="block w-full rounded-lg border-0 py-2.5 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-inset focus:ring-brand-600 sm:text-sm sm:leading-6 transition-colors shadow-sm" />
                      </div>
                    </div>

                    <div>
                      <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Reason (Optional)</label>
                      <textarea rows={3} placeholder="Provide a brief explanation..." value={formData.reason} onChange={e => setFormData({...formData, reason: e.target.value})} className="block w-full rounded-lg border-0 py-2.5 px-3 text-gray-900 bg-gray-50 ring-1 ring-inset ring-gray-200 focus:bg-white focus:ring-2 focus:ring-inset focus:ring-brand-600 sm:text-sm sm:leading-6 transition-colors shadow-sm" />
                    </div>

                  </div>
                  
                </form>
              </div>

              <div className="border-t border-gray-100 px-6 py-4 bg-white flex items-center justify-between">
                <button type="button" onClick={() => setIsSlideOverOpen(false)} className="rounded-lg bg-white px-4 py-2 text-sm font-semibold text-gray-700 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-50 transition-colors">
                  Cancel
                </button>
                <button type="submit" form="leave-form" className="rounded-lg bg-brand-600 px-6 py-2 text-sm font-semibold text-white shadow-sm hover:bg-brand-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-brand-600 transition-colors">
                  Submit Request
                </button>
              </div>
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}




