"use client";
import { API, authFetch } from "@/lib/api";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { motion, AnimatePresence } from "framer-motion";
import { Users, Plus, Search, MapPin, X, Trash2, Camera, Download, Pencil, CreditCard, Fingerprint, Upload, FileSpreadsheet, ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { downloadEmployeeProfilePDF, downloadEmployeeCardPDF } from "@/lib/pdf";

// Define TypeScript Interfaces
interface Employee {
  id: string;
  employeeId: string;
  firstName: string;
  lastName: string;
  cnic: string;
  department: string;
  designation: string;
  joiningDate: string;
  contractType: string;
  basicSalary: number;
  profileImage?: string;
  email?: string;
  bankName?: string;
  accountNumber?: string;
  dateOfBirth?: string;
  emergencyContact?: string;
  emergencyContactPhone?: string;
  biometricId?: string;
  overtimeEnabled?: boolean;
  eobiNo?: string;
  pessiNo?: string;
  documents?: { id: string; title: string; type: string; fileUrl: string }[];
}

export default function EmployeesPage() {
  const router = useRouter();
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isSlideOverOpen, setIsSlideOverOpen] = useState(false);
  const [editingEmployee, setEditingEmployee] = useState<Employee | null>(null);
  const [searchQuery, setSearchQuery] = useState("");
  const [profileImageFile, setProfileImageFile] = useState<File | null>(null);
  const [profileImagePreview, setProfileImagePreview] = useState<string | null>(null);
  const imageInputRef = useRef<HTMLInputElement>(null);
  
  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [totalEmployees, setTotalEmployees] = useState(0);
  const pageSize = 10;

  // Form State
  const [formData, setFormData] = useState({
    employeeId: "",
    firstName: "",
    lastName: "",
    cnic: "",
    department: "",
    designation: "",
    joiningDate: "",
    dateOfBirth: "",
    contractType: "PERMANENT",
    basicSalary: 0,
    email: "",
    bankName: "",
    accountNumber: "",
    emergencyContact: "",
    emergencyContactPhone: "",
    biometricId: "",
    overtimeEnabled: true,
    eobiNo: "",
    pessiNo: "",
  });

  const [documentFile, setDocumentFile] = useState<File | null>(null);
  const [documentType, setDocumentType] = useState<string>("ID_CARD");
  
  // Import state
  const [importFile, setImportFile] = useState<File | null>(null);
  const [isImporting, setIsImporting] = useState(false);
  const [importResult, setImportResult] = useState<any>(null);
  const importInputRef = useRef<HTMLInputElement>(null);

  const fetchEmployees = async (page = currentPage, search = searchQuery) => {
    try {
      setIsLoading(true);
      const params = new URLSearchParams({
        page: page.toString(),
        limit: pageSize.toString(),
        search: search,
      });
      const res = await authFetch(`${API}/dash/employees?${params}`);
      const data = await res.json();
      if (res.ok && data.employees) {
        setEmployees(data.employees);
        setTotalPages(data.pagination.pages);
        setTotalEmployees(data.pagination.total);
        setCurrentPage(data.pagination.page);
      } else {
        setEmployees([]);
        setTotalPages(1);
        setTotalEmployees(0);
      }
    } catch (error) {
      console.error("Failed to fetch employees", error);
      setEmployees([]);
      setTotalPages(1);
      setTotalEmployees(0);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    fetchEmployees();
    setFormData(prev => ({
      ...prev,
      joiningDate: new Date().toISOString().split("T")[0]
    }));
  }, []);

  const handleSaveEmployee = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const payload = {
        ...formData,
        basicSalary: Number(formData.basicSalary),
      };

      const url = editingEmployee
        ? `${API}/dash/employees/${editingEmployee.id}`
        : `${API}/dash/employees`;

      const method = editingEmployee ? "PATCH" : "POST";

      const res = await authFetch(url, {
        method,
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });

      if (!res.ok) {
        const error = await res.json();
        alert(`Error: ${error.message}`);
        return;
      }

      const employeeId = editingEmployee ? editingEmployee.id : (await res.json()).id;

      if (profileImageFile) {
        const imgForm = new FormData();
        imgForm.append("image", profileImageFile);
        await authFetch(`${API}/dash/employees/${employeeId}/profile-image`, { method: "POST", body: imgForm });
      }

      if (documentFile) {
        const form = new FormData();
        form.append("type", documentType);
        form.append("file", documentFile);
        await authFetch(`${API}/dash/employees/${employeeId}/documents`, { method: "POST", body: form });
      }

      setDocumentFile(null);
      setProfileImageFile(null);
      setProfileImagePreview(null);
      setEditingEmployee(null);
      setIsSlideOverOpen(false);
      fetchEmployees(); // refetch after success
    } catch (err) {
      console.error("Save employee error:", err);
      alert("Failed to save: " + (err instanceof Error ? err.message : String(err)));
    }
  };

  const handleDelete = async (id: string) => {
    if (!confirm("Are you sure you want to dismiss this employee?")) return;
    try {
      await authFetch(`${API}/dash/employees/${id}`, { method: "DELETE" });
      fetchEmployees();
    } catch (err) {
      console.error(err);
    }
  };

  const handleDeleteDocument = async (docId: string) => {
    if (!editingEmployee) return;
    if (!confirm("Delete this document?")) return;
    try {
      await authFetch(`${API}/dash/employees/${editingEmployee.id}/documents/${docId}`, {
        method: "DELETE",
      });
      // Refresh list and local editing state
      await fetchEmployees();
      const updated = await authFetch(`${API}/dash/employees/${editingEmployee.id}`);
      if (updated.ok) {
        const emp = await updated.json();
        setEditingEmployee(emp);
      }
    } catch (err) {
      console.error(err);
    }
  };

  const handleImport = async () => {
    if (!importFile) {
      alert("Please select an Excel file to import");
      return;
    }

    setIsImporting(true);
    setImportResult(null);

    try {
      const formData = new FormData();
      formData.append("file", importFile);

      const res = await authFetch(`${API}/dash/employees/import`, {
        method: "POST",
        body: formData,
      });

      const result = await res.json();

      if (res.ok) {
        setImportResult(result);
        fetchEmployees(); // Refresh employee list
        setImportFile(null);
        if (importInputRef.current) {
          importInputRef.current.value = "";
        }
      } else {
        alert(`Import failed: ${result.error || "Unknown error"}`);
        if (result.details) {
          console.error("Import errors:", result.details);
        }
      }
    } catch (err) {
      console.error("Import error:", err);
      alert("Import failed: Could not connect to server");
    } finally {
      setIsImporting(false);
    }
  };

  const downloadTemplate = () => {
    // Create a simple CSV template as fallback
    const template = [
      "employeeId,firstName,lastName,cnic,department,designation,contractType,joiningDate,basicSalary,email,bankName,accountNumber,emergencyContact,emergencyContactPhone,biometricId,overtimeEnabled,eobiNo,pessiNo",
      "EMP-2026-001,John,Doe,3520212345678,Production,Operator,PERMANENT,2024-01-01,50000,john@company.com,HBL,1234567890,Ahmed Raza,0300-1234567,123456,TRUE,EOBI-123456,PESSI-123456"
    ].join("\n");

    const blob = new Blob([template], { type: "text/csv" });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "employee-import-template.csv";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    window.URL.revokeObjectURL(url);
  };

  const openCreate = () => {
    setEditingEmployee(null);
    setProfileImageFile(null);
    setProfileImagePreview(null);
    setFormData({
      employeeId: "",
      firstName: "",
      lastName: "",
      cnic: "",
      department: "",
      designation: "",
      joiningDate: new Date().toISOString().split("T")[0],
      dateOfBirth: "",
      contractType: "PERMANENT",
      basicSalary: 0,
      email: "",
      bankName: "",
      accountNumber: "",
      emergencyContact: "",
      emergencyContactPhone: "",
      biometricId: "",
      overtimeEnabled: true,
      eobiNo: "",
      pessiNo: "",
    });
    setIsSlideOverOpen(true);
  };

  const openEdit = async (emp: Employee) => {
    setProfileImageFile(null);
    setProfileImagePreview(emp.profileImage ?? null);
    try {
      const res = await authFetch(`${API}/dash/employees/${emp.id}`);
      const full = res.ok ? await res.json() : emp;
      setEditingEmployee(full);
      setProfileImagePreview(full.profileImage ?? null);
      setFormData({
        employeeId: full.employeeId,
        firstName: full.firstName,
        lastName: full.lastName,
        cnic: full.cnic,
        department: full.department,
        designation: full.designation,
        joiningDate: full.joiningDate.split("T")[0],
        dateOfBirth: full.dateOfBirth?.split("T")[0] ?? "",
        contractType: full.contractType,
        basicSalary: full.basicSalary ?? 0,
        email: full.email ?? "",
        bankName: full.bankName ?? "",
        accountNumber: full.accountNumber ?? "",
        emergencyContact: full.emergencyContact ?? "",
        emergencyContactPhone: full.emergencyContactPhone ?? "",
        biometricId: full.biometricId ?? "",
        overtimeEnabled: full.overtimeEnabled !== false,
        eobiNo: full.eobiNo ?? "",
        pessiNo: full.pessiNo ?? "",
      });
      setIsSlideOverOpen(true);
    } catch {
      setEditingEmployee(emp);
      setFormData({
        employeeId: emp.employeeId,
        firstName: emp.firstName,
        lastName: emp.lastName,
        cnic: emp.cnic,
        department: emp.department,
        designation: emp.designation,
        joiningDate: emp.joiningDate.split("T")[0],
        dateOfBirth: emp.dateOfBirth?.split("T")[0] ?? "",
        contractType: emp.contractType,
        basicSalary: emp.basicSalary ?? 0,
        email: emp.email ?? "",
        bankName: emp.bankName ?? "",
        accountNumber: emp.accountNumber ?? "",
        emergencyContact: emp.emergencyContact ?? "",
        emergencyContactPhone: emp.emergencyContactPhone ?? "",
        biometricId: emp.biometricId ?? "",
        overtimeEnabled: emp.overtimeEnabled !== false,
        eobiNo: emp.eobiNo ?? "",
        pessiNo: emp.pessiNo ?? "",
      });
      setIsSlideOverOpen(true);
    }
  };

  const [settingsDepts, setSettingsDepts] = useState<string[]>([]);
  const [settingsDesigs, setSettingsDesigs] = useState<string[]>([]);
  const [deptOpen, setDeptOpen] = useState(false);
  const [desigOpen, setDesigOpen] = useState(false);
  const deptRef = useRef<HTMLDivElement>(null);
  const desigRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    authFetch(`${API}/dash/settings`)
      .then(r => r.json())
      .then(data => {
        const parseCsv = (v: unknown): string[] => typeof v === "string" && v.trim() ? v.split(",").map((s: string) => s.trim()).filter(Boolean) : [];
        const depts = parseCsv(data.departments);
        const desigs = parseCsv(data.designations);
        if (depts.length > 0) setSettingsDepts(depts);
        if (desigs.length > 0) setSettingsDesigs(desigs);
      })
      .catch(() => {});
  }, []);

  useEffect(() => {
    const handler = (e: MouseEvent) => {
      if (deptRef.current && !deptRef.current.contains(e.target as Node)) setDeptOpen(false);
      if (desigRef.current && !desigRef.current.contains(e.target as Node)) setDesigOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  const addToSettings = async (field: "departments" | "designations", list: string[]) => {
    try {
      await authFetch(`${API}/dash/settings`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ [field]: list }),
      });
    } catch {}
  };

  // Handle search with debouncing
  const handleSearch = (query: string) => {
    setSearchQuery(query);
    setCurrentPage(1); // Reset to first page when searching
    // Debounce search
    const timeoutId = setTimeout(() => {
      fetchEmployees(1, query);
    }, 300);
    return () => clearTimeout(timeoutId);
  };

  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">
            Employee Directory
          </h1>
          <p className="mt-1 text-sm text-gray-500">
            View and manage {totalEmployees} factory employees.
          </p>
        </div>
        
        <div className="flex items-center gap-3">
          <button 
            onClick={downloadTemplate}
            className="inline-flex items-center justify-center rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 transition-colors"
          >
            <FileSpreadsheet className="mr-2 h-4 w-4" />
            Download Template
          </button>
          <button 
            onClick={() => importInputRef.current?.click()}
            className="inline-flex items-center justify-center rounded-lg border border-gray-300 bg-white px-4 py-2 text-sm font-medium text-gray-700 shadow-sm hover:bg-gray-50 transition-colors"
          >
            <Upload className="mr-2 h-4 w-4" />
            Import Excel
          </button>
          <input
            ref={importInputRef}
            type="file"
            accept=".xlsx,.xls"
            className="hidden"
            onChange={(e) => setImportFile(e.target.files?.[0] || null)}
          />
          <button 
            onClick={openCreate}
            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" />
            Add Employee
          </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">
          <div className="relative max-w-md">
            <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) => handleSearch(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 ID, Name, CNIC, or Department..."
            />
          </div>
        </div>

        {/* Table / Empty State */}
        {isLoading ? (
          <div className="p-12 text-center text-sm text-gray-500">Loading directory...</div>
        ) : employees.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">
              <Users className="h-8 w-8 text-brand-600" />
            </div>
            <h3 className="text-lg font-medium text-gray-900">No employees found</h3>
            <p className="mt-1 text-sm text-gray-500 max-w-sm">
              {searchQuery ? "No results matched your search." : "You haven't added any employees yet. Click 'Add Employee'."}
            </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">Name & ID</th>
                    <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">CNIC</th>
                    <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Role & Dept</th>
                    <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Contract</th>
                    <th className="px-3 py-3.5 text-left text-sm font-semibold text-gray-900">Joined</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">
                  {employees.map((person) => (
                  <motion.tr 
                    initial={{ opacity: 0 }} 
                    animate={{ opacity: 1 }} 
                    key={person.id}
                    className="hover:bg-gray-50 transition-colors group"
                  >
                    <td className="whitespace-nowrap py-4 pl-6 pr-3 text-sm">
                      <button onClick={() => router.push(`/dash/employees/${person.employeeId}`)} className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left">
                        <div className="h-10 w-10 flex-shrink-0 rounded-full overflow-hidden bg-brand-100 flex items-center justify-center text-brand-700 font-bold uppercase ring-2 ring-white">
                          {person.profileImage
                            ? <img src={person.profileImage} alt={person.firstName} className="h-full w-full object-cover" />
                            : <>{person.firstName.charAt(0)}{person.lastName.charAt(0)}</>
                          }
                        </div>
                        <div>
                          <div className="font-medium text-gray-900 hover:text-brand-600 transition-colors">{person.firstName} {person.lastName}</div>
                          <div className="mt-0.5 text-gray-400 text-xs font-mono">#{person.employeeId}</div>
                        </div>
                      </button>
                    </td>
                    <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500 font-mono">
                      {person.cnic}
                    </td>
                    <td className="whitespace-nowrap px-3 py-4 text-sm">
                      <div className="text-gray-900 font-medium">{person.designation}</div>
                      <div className="mt-1 text-gray-500 flex items-center">
                        <MapPin className="mr-1 h-3 w-3" />
                        {person.department}
                      </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",
                        person.contractType === 'PERMANENT' ? "bg-green-50 text-green-700 ring-green-600/20" : 
                        person.contractType === 'PROBATION' ? "bg-yellow-50 text-yellow-800 ring-yellow-600/20" :
                        "bg-blue-50 text-blue-700 ring-blue-700/10"
                      )}>
                        {person.contractType}
                      </span>
                    </td>
                    <td className="whitespace-nowrap px-3 py-4 text-sm text-gray-500">
                      {new Date(person.joiningDate).toLocaleDateString()}
                    </td>
                    <td className="whitespace-nowrap py-4 px-6 text-center text-sm font-medium">
                      <div className="flex items-center justify-center gap-3">
                        <button
                          onClick={() => openEdit(person)}
                          className="text-brand-600 hover:text-brand-900 transition-colors"
                          title="Edit Employee"
                        >
                          <Pencil className="h-4 w-4" />
                        </button>
                        <button
                          onClick={async () => await downloadEmployeeProfilePDF(person)}
                          className="text-gray-500 hover:text-brand-600 transition-colors"
                          title="Download Profile PDF"
                        >
                          <Download className="h-4 w-4" />
                        </button>
                        <button
                          onClick={async () => { await downloadEmployeeCardPDF(person); }}
                          className="text-gray-500 hover:text-brand-600 transition-colors"
                          title="Generate Employee ID Card"
                        >
                          <CreditCard className="h-4 w-4" />
                        </button>
                        <button 
                          onClick={() => handleDelete(person.id)}
                          className="text-red-600 hover:text-red-900"
                        >
                          <Trash2 className="h-4 w-4" />
                        </button>
                      </div>
                    </td>
                  </motion.tr>
                  ))}
                </tbody>
              </table>
            </div>
            
            {/* Pagination Controls */}
            {totalPages > 1 && (
              <div className="px-6 py-4 border-t border-gray-200 bg-gray-50/50">
                <div className="flex items-center justify-between">
                  <div className="text-sm text-gray-700">
                    Showing {((currentPage - 1) * pageSize) + 1} to {Math.min(currentPage * pageSize, totalEmployees)} of {totalEmployees} results
                  </div>
                  <div className="flex items-center gap-2">
                    <button
                      onClick={() => fetchEmployees(currentPage - 1, searchQuery)}
                      disabled={currentPage === 1}
                      className="px-3 py-2 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>
                    
                    <div className="flex items-center gap-1">
                      {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                        let pageNum;
                        if (totalPages <= 5) {
                          pageNum = i + 1;
                        } else if (currentPage <= 3) {
                          pageNum = i + 1;
                        } else if (currentPage >= totalPages - 2) {
                          pageNum = totalPages - 4 + i;
                        } else {
                          pageNum = currentPage - 2 + i;
                        }
                        
                        return (
                          <button
                            key={pageNum}
                            onClick={() => fetchEmployees(pageNum, searchQuery)}
                            className={`px-3 py-2 text-sm font-medium rounded-md ${
                              currentPage === pageNum
                                ? 'bg-brand-600 text-white'
                                : 'text-gray-700 bg-white border border-gray-300 hover:bg-gray-50'
                            }`}
                          >
                            {pageNum}
                          </button>
                        );
                      })}
                    </div>
                    
                    <button
                      onClick={() => fetchEmployees(currentPage + 1, searchQuery)}
                      disabled={currentPage === totalPages}
                      className="px-3 py-2 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>
            )}
          </>
        )}
      </div>

      {/* Import Result */}
      {importResult && (
        <div className="rounded-2xl bg-white shadow-sm border border-[#E2E8F0] overflow-hidden p-6">
          <div className="flex items-center justify-between mb-4">
            <h3 className="text-lg font-semibold text-gray-900">Import Results</h3>
            <button 
              onClick={() => setImportResult(null)}
              className="text-gray-400 hover:text-gray-600"
            >
              <X className="h-5 w-5" />
            </button>
          </div>
          <div className="space-y-2">
            <p className="text-sm text-gray-600">{importResult.message}</p>
            {importResult.results?.errors?.length > 0 && (
              <div className="mt-3">
                <p className="text-sm font-medium text-red-600 mb-2">Errors:</p>
                <ul className="text-xs text-red-600 space-y-1 max-h-32 overflow-y-auto">
                  {importResult.results.errors.map((error: string, idx: number) => (
                    <li key={idx}>• {error}</li>
                  ))}
                </ul>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Import Confirmation Dialog */}
      {importFile && (
        <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40 flex items-center justify-center p-4">
          <motion.div
            initial={{ opacity: 0, scale: 0.96 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.96 }}
            className="bg-white rounded-2xl p-6 max-w-md w-full"
          >
            <div className="flex items-center gap-3 mb-4">
              <div className="h-10 w-10 rounded-full bg-brand-100 flex items-center justify-center">
                <Upload className="h-5 w-5 text-brand-600" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-900">Import Employees</h3>
                <p className="text-sm text-gray-500">Import data from Excel file</p>
              </div>
            </div>
            
            <div className="mb-4">
              <p className="text-sm text-gray-600 mb-2">Selected file:</p>
              <p className="text-sm font-medium text-gray-900 truncate">{importFile.name}</p>
            </div>

            <div className="flex gap-3">
              <button
                onClick={() => {
                  setImportFile(null);
                  if (importInputRef.current) {
                    importInputRef.current.value = "";
                  }
                }}
                className="flex-1 px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                Cancel
              </button>
              <button
                onClick={handleImport}
                disabled={isImporting}
                className="flex-1 px-4 py-2 text-sm font-medium text-white bg-brand-600 rounded-lg hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                {isImporting ? "Importing..." : "Import"}
              </button>
            </div>
          </motion.div>
        </div>
      )}

      {/* Modal for Add/Edit Employee */}
      <AnimatePresence>
        {isSlideOverOpen && (
          <>
            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setIsSlideOverOpen(false)}
              className="fixed inset-0 bg-black/50 backdrop-blur-sm z-40"
            />
            <div className="fixed inset-0 z-50 flex items-center justify-center p-4">
            <motion.div
              initial={{ opacity: 0, scale: 0.96, y: 8 }}
              animate={{ opacity: 1, scale: 1, y: 0 }}
              exit={{ opacity: 0, scale: 0.96, y: 8 }}
              transition={{ type: "spring", bounce: 0.1, duration: 0.3 }}
              className="w-full max-w-6xl bg-white text-gray-900 shadow-2xl flex flex-col border border-gray-200 max-h-[90vh]"
            >
              <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">
                    <Users className="h-5 w-5 text-brand-600" />
                  </div>
                  <div>
                    <h2 className="text-lg font-semibold text-gray-900">
                      {editingEmployee ? "Edit Employee" : "Add New Employee"}
                    </h2>
                    <p className="text-xs text-gray-500 font-medium mt-0.5">
                      {editingEmployee ? "Update profile details or attach documents." : "Fill out core profile 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-5 bg-gray-50/30">
                <form id="employee-form" onSubmit={handleSaveEmployee} className="space-y-6">

                  {/* Profile Photo */}
                  <div className="flex flex-col items-center gap-3 py-2">
                    <div className="relative">
                      <div className="h-24 w-24 rounded-2xl bg-brand-100 overflow-hidden flex items-center justify-center ring-2 ring-brand-100 shadow-sm">
                        {profileImagePreview ? (
                          <img src={profileImagePreview} alt="Profile" className="h-full w-full object-cover" />
                        ) : (
                          <span className="text-2xl font-bold text-brand-500">
                            {formData.firstName ? formData.firstName.charAt(0).toUpperCase() : "?"}
                          </span>
                        )}
                      </div>
                      <button
                        type="button"
                        onClick={() => imageInputRef.current?.click()}
                        className="absolute -bottom-1 -right-1 h-8 w-8 rounded-full bg-brand-600 text-white flex items-center justify-center shadow hover:bg-brand-700 transition-colors"
                      >
                        <Camera className="h-3.5 w-3.5" />
                      </button>
                      <input
                        ref={imageInputRef}
                        type="file"
                        accept="image/*"
                        className="hidden"
                        onChange={(e) => {
                          const f = e.target.files?.[0];
                          if (!f) return;
                          setProfileImageFile(f);
                          setProfileImagePreview(URL.createObjectURL(f));
                        }}
                      />
                    </div>
                    <p className="text-xs text-gray-400">Click camera to upload photo</p>
                  </div>

                  {/* Two-column layout for the form sections */}
                  <div className="grid grid-cols-2 gap-4">

                  {/* Personal Information */}
                  <div className="space-y-3 rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-900/5">
                    <h3 className="text-xs font-semibold uppercase tracking-wider text-gray-400 border-b border-gray-100 pb-2">Personal</h3>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs font-medium text-gray-500 mb-1">First Name</label>
                        <input required type="text" placeholder="Ali" value={formData.firstName} onChange={e => setFormData({...formData, firstName: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-gray-500 mb-1">Last Name</label>
                        <input required type="text" placeholder="Raza" value={formData.lastName} onChange={e => setFormData({...formData, lastName: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                      </div>
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">CNIC <span className="text-gray-400">(13 digits)</span></label>
                      <input required type="text" placeholder="3520212345678" maxLength={13} value={formData.cnic} onChange={e => setFormData({...formData, cnic: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">Email</label>
                      <input type="email" placeholder="ali@company.com" value={formData.email} onChange={e => setFormData({...formData, email: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">Date of Birth</label>
                      <input type="date" value={formData.dateOfBirth} onChange={e => setFormData({...formData, dateOfBirth: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">Biometric / Device ID</label>
                      <input type="text" placeholder="e.g. 123456" value={formData.biometricId} onChange={e => setFormData({...formData, biometricId: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                    </div>
                  </div>

                  {/* Employment Details */}
                  <div className="space-y-3 rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-900/5">
                    <h3 className="text-xs font-semibold uppercase tracking-wider text-gray-400 border-b border-gray-100 pb-2">Employment</h3>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">Employee ID</label>
                      <input required type="text" placeholder="EMP-2026-001" value={formData.employeeId} onChange={e => setFormData({...formData, employeeId: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors font-mono" />
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      {/* Department combobox */}
                      <div ref={deptRef}>
                        <label className="block text-xs font-medium text-gray-500 mb-1">Department</label>
                        <div className="relative">
                          <input
                            required
                            type="text"
                            placeholder="Select or type new..."
                            value={formData.department}
                            onChange={e => { setFormData({...formData, department: e.target.value}); setDeptOpen(true); }}
                            onFocus={() => setDeptOpen(true)}
                            className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors"
                          />
                          <button type="button" onClick={() => setDeptOpen(o => !o)} tabIndex={-1} className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400">
                            <ChevronDown className="h-3.5 w-3.5" />
                          </button>
                          {deptOpen && (
                            <div className="absolute z-50 mt-1 w-full rounded-lg bg-white shadow-lg ring-1 ring-gray-200 max-h-40 overflow-y-auto">
                              {[...new Set([...settingsDepts, ...(formData.department && !settingsDepts.includes(formData.department) ? [formData.department] : [])])]
                                .filter(d => d.toLowerCase().includes(formData.department.toLowerCase()))
                                .map(d => (
                                  <button
                                    key={d} type="button"
                                    onMouseDown={() => { setFormData({...formData, department: d}); setDeptOpen(false); }}
                                    className={`w-full text-left px-3 py-2 text-sm hover:bg-brand-50 hover:text-brand-700 ${ formData.department === d ? "bg-brand-50 text-brand-700 font-medium" : "text-gray-700" }`}
                                  >{d}</button>
                                ))}
                              {formData.department.trim() && !settingsDepts.map(d=>d.toLowerCase()).includes(formData.department.trim().toLowerCase()) && (
                                <button
                                  type="button"
                                  onMouseDown={() => {
                                    const val = formData.department.trim();
                                    const updated = [...settingsDepts, val];
                                    setSettingsDepts(updated);
                                    addToSettings("departments", updated);
                                    setDeptOpen(false);
                                  }}
                                  className="w-full text-left px-3 py-2 text-sm text-brand-600 font-semibold hover:bg-brand-50 border-t border-gray-100"
                                >+ Add &ldquo;{formData.department.trim()}&rdquo; to departments</button>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                      {/* Designation combobox */}
                      <div ref={desigRef}>
                        <label className="block text-xs font-medium text-gray-500 mb-1">Designation</label>
                        <div className="relative">
                          <input
                            required
                            type="text"
                            placeholder="Select or type new..."
                            value={formData.designation}
                            onChange={e => { setFormData({...formData, designation: e.target.value}); setDesigOpen(true); }}
                            onFocus={() => setDesigOpen(true)}
                            className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors"
                          />
                          <button type="button" onClick={() => setDesigOpen(o => !o)} tabIndex={-1} className="absolute right-2 top-1/2 -translate-y-1/2 text-gray-400">
                            <ChevronDown className="h-3.5 w-3.5" />
                          </button>
                          {desigOpen && (
                            <div className="absolute z-50 mt-1 w-full rounded-lg bg-white shadow-lg ring-1 ring-gray-200 max-h-40 overflow-y-auto">
                              {[...new Set([...settingsDesigs, ...(formData.designation && !settingsDesigs.includes(formData.designation) ? [formData.designation] : [])])]
                                .filter(d => d.toLowerCase().includes(formData.designation.toLowerCase()))
                                .map(d => (
                                  <button
                                    key={d} type="button"
                                    onMouseDown={() => { setFormData({...formData, designation: d}); setDesigOpen(false); }}
                                    className={`w-full text-left px-3 py-2 text-sm hover:bg-brand-50 hover:text-brand-700 ${ formData.designation === d ? "bg-brand-50 text-brand-700 font-medium" : "text-gray-700" }`}
                                  >{d}</button>
                                ))}
                              {formData.designation.trim() && !settingsDesigs.map(d=>d.toLowerCase()).includes(formData.designation.trim().toLowerCase()) && (
                                <button
                                  type="button"
                                  onMouseDown={() => {
                                    const val = formData.designation.trim();
                                    const updated = [...settingsDesigs, val];
                                    setSettingsDesigs(updated);
                                    addToSettings("designations", updated);
                                    setDesigOpen(false);
                                  }}
                                  className="w-full text-left px-3 py-2 text-sm text-brand-600 font-semibold hover:bg-brand-50 border-t border-gray-100"
                                >+ Add &ldquo;{formData.designation.trim()}&rdquo; to designations</button>
                              )}
                            </div>
                          )}
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs font-medium text-gray-500 mb-1">Joining Date</label>
                        <input required type="date" value={formData.joiningDate} onChange={e => setFormData({...formData, joiningDate: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                      </div>
                      <div>
                        <label className="block text-xs font-medium text-gray-500 mb-1">Contract Type</label>
                        <select required value={formData.contractType} onChange={e => setFormData({...formData, contractType: e.target.value})} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors appearance-none">
                          <option value="PERMANENT">PERMANENT</option>
                          <option value="PROBATION">PROBATION</option>
                          <option value="CONTRACT">CONTRACT</option>
                          <option value="INTERN">INTERN</option>
                        </select>
                      </div>
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">Basic Salary (PKR)</label>
                      <div className="relative">
                        <div className="pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3">
                          <span className="text-gray-400 text-sm">₨</span>
                        </div>
                        <input required type="number" min="0" placeholder="0" value={formData.basicSalary} onChange={e => setFormData({...formData, basicSalary: Number(e.target.value)})} className="block w-full rounded-lg border-0 py-2 pl-9 pr-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 text-sm transition-colors" />
                      </div>
                    </div>
                    <label className="flex items-center gap-2 cursor-pointer">
                      <input type="checkbox" checked={formData.overtimeEnabled} onChange={e => setFormData({ ...formData, overtimeEnabled: e.target.checked })} className="h-4 w-4 rounded border-gray-300 text-brand-600 focus:ring-brand-600" />
                      <span className="text-xs font-medium text-gray-700">Enable overtime</span>
                    </label>
                  </div>

                  </div>{/* end two-column grid */}

                  {/* Bank & Social Security */}
                  <div className="grid grid-cols-2 gap-4">
                  <div className="space-y-3 rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-900/5">
                    <h3 className="text-xs font-semibold uppercase tracking-wider text-gray-400 border-b border-gray-100 pb-2">Bank Details</h3>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">Bank Name</label>
                      <input type="text" placeholder="HBL, UBL, MCB" value={formData.bankName} onChange={e => setFormData({ ...formData, bankName: e.target.value })} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">Account Number</label>
                      <input type="text" placeholder="0012345678901" value={formData.accountNumber} onChange={e => setFormData({ ...formData, accountNumber: e.target.value })} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors font-mono" />
                    </div>
                  </div>
                  <div className="space-y-3 rounded-xl bg-white p-4 shadow-sm ring-1 ring-gray-900/5">
                    <h3 className="text-xs font-semibold uppercase tracking-wider text-gray-400 border-b border-gray-100 pb-2">EOBI &amp; PESSI</h3>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">EOBI Number</label>
                      <input type="text" placeholder="EOBI-123456" value={formData.eobiNo} onChange={e => setFormData({ ...formData, eobiNo: e.target.value })} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors font-mono" />
                    </div>
                    <div>
                      <label className="block text-xs font-medium text-gray-500 mb-1">PESSI Number</label>
                      <input type="text" placeholder="PESSI-123456" value={formData.pessiNo} onChange={e => setFormData({ ...formData, pessiNo: e.target.value })} className="block w-full rounded-lg border-0 py-2 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 text-sm transition-colors font-mono" />
                    </div>
                  </div>
                  </div>

                  {/* Emergency Contact */}
                  <div className="space-y-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-900/5">
                    <h3 className="text-sm font-semibold leading-6 text-gray-900 border-b border-gray-100 pb-2">Emergency Contact</h3>
                    <div className="grid grid-cols-2 gap-4 pt-1">
                      <div>
                        <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Contact Name</label>
                        <input type="text" placeholder="e.g. Ahmed Raza" value={formData.emergencyContact} onChange={e => setFormData({...formData, emergencyContact: 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 transition-colors shadow-sm" />
                      </div>
                      <div>
                        <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">Phone Number</label>
                        <input type="tel" placeholder="e.g. 0300-1234567" value={formData.emergencyContactPhone} onChange={e => setFormData({...formData, emergencyContactPhone: 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 transition-colors shadow-sm" />
                      </div>
                    </div>
                    <p className="text-xs text-gray-400">Person to contact in case of emergency.</p>
                  </div>

                  {/* Documents */}
                  <div className="space-y-4 rounded-xl bg-white p-5 shadow-sm ring-1 ring-gray-900/5">
                    <h3 className="text-sm font-semibold leading-6 text-gray-900 border-b border-gray-100 pb-2">
                      Attach Documents
                    </h3>
                    {editingEmployee && editingEmployee.documents && editingEmployee.documents.length > 0 && (
                      <div className="mb-3">
                        <p className="text-xs font-semibold text-gray-500 mb-1.5">Existing documents</p>
                        <ul className="space-y-1 text-xs text-gray-600 max-h-24 overflow-y-auto">
                          {editingEmployee.documents.map((doc) => (
                            <li key={doc.id} className="flex items-center justify-between gap-2">
                              <span className="truncate">
                                {doc.type}: {doc.title}
                              </span>
                              <div className="flex items-center gap-2 flex-shrink-0">
                                <a
                                  href={`${API}${doc.fileUrl}`}
                                  target="_blank"
                                  rel="noreferrer"
                                  className="text-brand-600 hover:text-brand-800"
                                >
                                  View
                                </a>
                                <button
                                  type="button"
                                  onClick={() => handleDeleteDocument(doc.id)}
                                  className="text-red-600 hover:text-red-800"
                                >
                                  Delete
                                </button>
                              </div>
                            </li>
                          ))}
                        </ul>
                      </div>
                    )}
                    <p className="text-xs text-gray-500">
                      Upload CNIC, education certificates, or resume. Optional.
                    </p>
                    <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">
                          Document Type
                        </label>
                        <select
                          value={documentType}
                          onChange={(e) => setDocumentType(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="ID_CARD">ID Card</option>
                          <option value="EDUCATION">Educational Document</option>
                          <option value="RESUME">Resume</option>
                          <option value="OTHER">Other</option>
                        </select>
                      </div>
                      <div>
                        <label className="block text-xs font-semibold uppercase tracking-wider text-gray-500 mb-1.5">
                          File
                        </label>
                        <input
                          type="file"
                          onChange={(e) => setDocumentFile(e.target.files?.[0] ?? null)}
                          className="block w-full text-sm text-gray-900 file:mr-3 file:rounded-md file:border-0 file:bg-brand-50 file:px-3 file:py-1.5 file:text-xs file:font-semibold file:text-brand-700 hover:file:bg-brand-100"
                        />
                      </div>
                    </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="employee-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">
                  Save Profile
                </button>
              </div>
            </motion.div>
            </div>
          </>
        )}
      </AnimatePresence>
    </div>
  );
}




