/**
 * ProjectDetailsModal Component
 *
 * This component displays detailed information about a project and provides
 * functionality to manage project details, employees, and project information.
 *
 * Features:
 * - Display comprehensive project information (name, status, priority, dates, etc.)
 * - Manage project employees (view, add, remove)
 * - Upload and download project forms
 * - Edit and delete project details
 * - Theme-aware styling (light/dark mode)
 *
 * @component
 * @param {Object} project - Project data object containing all project details
 * @param {boolean} isOpen - Controls modal visibility
 * @param {Function} onClose - Callback to close the modal
 * @param {Function} onEdit - Callback to handle project editing
 * @param {Function} onDelete - Callback to handle project deletion
 * @param {Function} downloadProjectForm - Callback to download project form
 * @param {boolean} showDeleteButton - Whether to show the delete button (default: true)
 */

import React, { useState, useEffect } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import {
  FaEdit,
  FaTrash,
  FaTimes,
  FaProjectDiagram,
  FaCalendarAlt,
  FaClock,
  FaUser,
  FaChartLine,
  FaExclamationTriangle,
  FaCheckCircle,
  FaPause,
  FaPlay,
  FaUsers,
  FaPlus,
  FaSpinner,
  FaDownload,
  FaUpload,
} from "react-icons/fa";
import "./ProjectDetailsModal.css";
import { formatIST } from "../../utils/timeUtils";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const ProjectDetailsModal = ({
  project,
  isOpen,
  onClose,
  onEdit,
  onDelete,
  downloadProjectForm,
  showDeleteButton = true, // Default to true to maintain existing behavior
}) => {
  // Theme context for light/dark mode styling
  const { isLight } = useTheme();

  // Employee management state
  const [showEmployees, setShowEmployees] = useState(false); // Controls employee list visibility
  const [employees, setEmployees] = useState([]); // List of employees assigned to project
  const [loadingEmployees, setLoadingEmployees] = useState(false); // Loading state for employee fetch
  const [employeeError, setEmployeeError] = useState(""); // Error state for employee operations
  const [showAddEmployeeModal, setShowAddEmployeeModal] = useState(false); // Controls add employee modal
  const [availableEmployees, setAvailableEmployees] = useState([]); // List of employees not assigned to project
  const [loadingAvailableEmployees, setLoadingAvailableEmployees] =
    useState(false); // Loading state for available employees
  const [selectedEmployeeId, setSelectedEmployeeId] = useState(""); // ID of employee selected for assignment
  const [addingEmployee, setAddingEmployee] = useState(false); // Loading state for adding employee

  // File upload modal states
  const [showUploadModal, setShowUploadModal] = useState(false); // Controls upload modal visibility
  const [selectedFile, setSelectedFile] = useState(null); // Currently selected file for upload
  const [uploading, setUploading] = useState(false); // Loading state for file upload

  // Filter states
  const [divisions, setDivisions] = useState([]);
  const [roles, setRoles] = useState([]);
  const [selectedDivisionId, setSelectedDivisionId] = useState("");
  const [selectedRoleId, setSelectedRoleId] = useState("");
  const [loadingDivisions, setLoadingDivisions] = useState(false);
  const [loadingRoles, setLoadingRoles] = useState(false);

  // Delete employee confirmation state
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [employeeToDelete, setEmployeeToDelete] = useState(null);

  // Form availability state
  const [hasForm, setHasForm] = useState(false);
  const [checkingForm, setCheckingForm] = useState(false);

  // Popup states
  const [showSuccessPopup, setShowSuccessPopup] = useState(false);
  const [successMessage, setSuccessMessage] = useState("");
  const [successSubMessage, setSuccessSubMessage] = useState("");
  const [showErrorPopup, setShowErrorPopup] = useState(false);

  // Employee contribution modal states
  const [showAddContributionModal, setShowAddContributionModal] = useState(false);
  const [selectedContributionEmployeeId, setSelectedContributionEmployeeId] = useState("");
  const [contributionPercentage, setContributionPercentage] = useState("");
  const [contributionDescription, setContributionDescription] = useState("");
  const [addingContribution, setAddingContribution] = useState(false);
  const [contributionError, setContributionError] = useState("");
  const [isUpdatingContribution, setIsUpdatingContribution] = useState(false);
  const [existingContributionId, setExistingContributionId] = useState(null);
  const [employeeContributions, setEmployeeContributions] = useState({}); // Map of employee_id to contribution percentage

  // Reset employee state when project changes
  useEffect(() => {
    if (project) {
      setShowEmployees(false);
      setEmployees([]);
      setLoadingEmployees(false);
      setEmployeeError("");
      setShowAddEmployeeModal(false);
      setAvailableEmployees([]);
      setLoadingAvailableEmployees(false);
      setSelectedEmployeeId("");
      setAddingEmployee(false);
      setShowAddContributionModal(false);
      setSelectedContributionEmployeeId("");
      setContributionPercentage("");
      setContributionDescription("");
      setAddingContribution(false);
      setContributionError("");
      setIsUpdatingContribution(false);
      setExistingContributionId(null);
      setEmployeeContributions({});
      setShowDeleteConfirm(false);
      setEmployeeToDelete(null);

      // Reset popup states
      setShowSuccessPopup(false);
      setSuccessMessage("");
      setSuccessSubMessage("");
      setShowErrorPopup(false);

      // Check if project has a form
      checkProjectFormAvailability();
    }
  }, [project]);

  // Cleanup effect to reset popup states when component unmounts
  useEffect(() => {
    return () => {
      setShowSuccessPopup(false);
      setShowErrorPopup(false);
    };
  }, []);

  // Check if the project has a kickoff form
  const checkProjectFormAvailability = async () => {
    if (!project) return;

    setCheckingForm(true);
    try {
      // Check if the project is in the missing forms list
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.PROJECT_MISSING_FORMS)
      );
      if (response.ok) {
        const missingForms = await response.json();
        const isMissingForm = missingForms.some(
          (form) => form.project_name === project.project_name
        );
        const newHasForm = !isMissingForm;
        setHasForm(newHasForm);

        console.log(
          `Project "${project.project_name}" form availability:`,
          newHasForm ? "Available" : "Missing"
        );
      } else {
        console.warn("Failed to check form availability, assuming form exists");
        // If we can't check, assume it has a form to be safe
        setHasForm(true);
      }
    } catch (error) {
      console.error("Error checking form availability:", error);
      console.warn("Error occurred, assuming form exists");
      // If there's an error, assume it has a form to be safe
      setHasForm(true);
    } finally {
      setCheckingForm(false);
    }
  };

  if (!isOpen || !project) return null;

  // Debug logging for PO Status
  console.log("ProjectDetailsModal received project:", project);
  console.log("PO Status in modal:", project.po_status_name);

  // Theme-aware CSS classes for consistent styling across light/dark modes
  const modalBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-2xl"
    : "bg-gradient-to-br from-gray-800 to-slate-800 border border-gray-700 shadow-2xl";

  const textClass = isLight ? "text-amber-700" : "text-gray-300";



  /**
   * Wrapper function to close the modal and reset all states
   */
  const handleClose = () => {
    setShowSuccessPopup(false);
    setShowErrorPopup(false);
    onClose();
  };

  /**
   * Opens the file upload modal for the current project
   */
  const handleUpload = () => {
    setShowUploadModal(true);
  };

  /**
   * Handles file selection from the file input
   * @param {Event} event - File input change event
   */
  const handleFileChange = (event) => {
    const file = event.target.files[0];
    setSelectedFile(file);
  };

  /**
   * Handles file upload confirmation and submission
   * Creates FormData and sends file to the backend API
   */
  const handleUploadConfirm = async () => {
    if (!selectedFile) {
      return;
    }

    setUploading(true);
    try {
      // Create FormData for file upload with project context
      const formData = new FormData();
      formData.append("document", selectedFile);
      formData.append("project_name", project.project_name); // Use current project automatically

      // Make API call to upload the document
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.PROJECT_FORM_UPLOAD),
        {
          method: "POST",
          body: formData,
          // Note: Don't set Content-Type header for FormData, let the browser set it
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(
          errorData.error || `Upload failed with status: ${response.status}`
        );
      }

      // Re-check form availability to enable download button
      await checkProjectFormAvailability();

      // Show success popup with form upload message
      setSuccessMessage("Form uploaded successfully");
      setSuccessSubMessage("The download button is now enabled.");
      setShowSuccessPopup(true);

      // Close modal and reset states after a short delay
      setTimeout(() => {
        setShowUploadModal(false);
        setSelectedFile(null);
        setUploading(false);
        setShowSuccessPopup(false);
        setSuccessMessage("");
        setSuccessSubMessage("");
      }, 2000); // Show popup for 2 seconds
    } catch (error) {
      console.error("Error uploading file:", error);
      // Show error popup
      setShowErrorPopup(true);
      setTimeout(() => setShowErrorPopup(false), 3000);
    } finally {
      setUploading(false);
    }
  };

  /**
   * Closes the upload modal and resets all upload-related states
   */
  const closeUploadModal = () => {
    setShowUploadModal(false);
    setSelectedFile(null);
    setUploading(false);
    setShowSuccessPopup(false);
    setShowErrorPopup(false);
  };

  /**
   * Fetches all employees assigned to the current project
   * Handles various API response structures and provides error handling
   */
  const fetchEmployees = async () => {
    setLoadingEmployees(true);
    setEmployeeError("");

    try {
      console.log("Fetching employees for project ID:", project.project_id);
      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEES_BY_PROJECT(project.project_id))
      );

      console.log("Response status:", response.status);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();
      console.log("Employees data received:", data);
      console.log(
        "Number of employees:",
        Array.isArray(data) ? data.length : "Not an array"
      );

      // Handle different possible response structures from various API endpoints
      let employeesData = [];
      if (Array.isArray(data)) {
        employeesData = data;
      } else if (data && Array.isArray(data.data)) {
        employeesData = data.data;
      } else if (data && Array.isArray(data.employees)) {
        employeesData = data.employees;
      } else if (data && Array.isArray(data.results)) {
        employeesData = data.results;
      } else if (data && typeof data === "object") {
        // If it's an object, try to find any array property
        const arrayKeys = Object.keys(data).filter((key) =>
          Array.isArray(data[key])
        );
        if (arrayKeys.length > 0) {
          employeesData = data[arrayKeys[0]];
        }
      }

      console.log("Processed employees data:", employeesData);
      if (employeesData.length > 0) {
        console.log("First employee object:", employeesData[0]);
        console.log(
          "Available fields in first employee:",
          Object.keys(employeesData[0])
        );
      }

      // Set employees data
      setEmployees(employeesData);
      
      // Fetch contributions for all employees
      if (employeesData.length > 0 && project?.project_id) {
        await fetchEmployeeContributions(employeesData, project.project_id);
      }
    } catch (err) {
      console.error("Error fetching employees:", err);
      setEmployeeError("Failed to load employees. Please try again.");
      setEmployees([]);
    } finally {
      setLoadingEmployees(false);
    }
  };

  /**
   * Fetches contribution percentages for all employees in the project
   */
  const fetchEmployeeContributions = async (employeesList, projectId) => {
    if (!projectId || !employeesList || employeesList.length === 0) return;

    try {
      const contributionsMap = {};
      
      // Fetch contributions for each employee
      const contributionPromises = employeesList.map(async (employee) => {
        const employeeId = employee.employee_id || employee.id;
        if (!employeeId) return;

        try {
          const response = await fetch(
            buildApiUrl(
              `${API_ENDPOINTS.GET_EMPLOYEE_CONTRIBUTION}?employee_id=${employeeId}&project_id=${projectId}`
            )
          );

          if (response.ok) {
            const data = await response.json();
            if (data.data && data.data.length > 0) {
              // Get the most recent contribution
              const contribution = data.data[0];
              contributionsMap[employeeId] = contribution.contribution_percentage;
            }
          }
        } catch (err) {
          console.error(`Error fetching contribution for employee ${employeeId}:`, err);
        }
      });

      await Promise.all(contributionPromises);
      setEmployeeContributions(contributionsMap);
    } catch (err) {
      console.error("Error fetching employee contributions:", err);
    }
  };

  /**
   * Handles download button click - downloads project form in its original format
   * Uses the downloadProjectForm callback passed from parent component
   */
  const handleDownload = () => {
    if (!hasForm) {
      console.log("No form available for this project");
      return;
    }

    if (downloadProjectForm && project) {
      downloadProjectForm(project.project_name);
    } else {
      console.log("Download functionality coming soon...");
    }
  };

  /**
   * Toggles the employee list visibility and fetches employee data if needed
   * Only fetches data when opening the list to avoid unnecessary API calls
   */
  const handleShowEmployees = () => {
    if (!showEmployees) {
      fetchEmployees();
    }
    setShowEmployees(!showEmployees);
  };

  /**
   * Fetches all available employees that are not currently assigned to this project
   * Filters out already assigned employees to prevent duplicate assignments
   */
  const fetchAvailableEmployees = async () => {
    setLoadingAvailableEmployees(true);
    try {
      // Fetch all employees from the system
      const response = await fetch(buildApiUrl(API_ENDPOINTS.EMPLOYEES));
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      const data = await response.json();

      // Filter out employees already assigned to this project to prevent duplicates
      const currentEmployeeIds = employees.map(
        (emp) => emp.employee_id || emp.id
      );
      let available = Array.isArray(data)
        ? data.filter(
            (emp) => !currentEmployeeIds.includes(emp.employee_id || emp.id)
          )
        : [];

      // Also filter out directors (role_name = Director)
      available = available.filter((emp) => emp.role_name !== "Director");

      setAvailableEmployees(available);
    } catch (err) {
      console.error("Error fetching available employees:", err);
    } finally {
      setLoadingAvailableEmployees(false);
    }
  };

  // Fetch divisions for filtering
  const fetchDivisions = async () => {
    try {
      setLoadingDivisions(true);
      const response = await fetch(buildApiUrl(API_ENDPOINTS.DIVISIONS));
      if (response.ok) {
        const data = await response.json();
        // Filter out Directors division (division_name = Directors)
        const nonDirectorDivisions = data.filter(
          (div) => div.division_name !== "Directors"
        );
        setDivisions(nonDirectorDivisions);
      }
    } catch (err) {
      console.error("Error fetching divisions:", err);
    } finally {
      setLoadingDivisions(false);
    }
  };

  // Fetch roles for filtering
  const fetchRoles = async () => {
    try {
      setLoadingRoles(true);
      const response = await fetch(buildApiUrl(API_ENDPOINTS.ROLES));
      if (response.ok) {
        const data = await response.json();
        // Filter out Director role (role_name = Director)
        const nonDirectorRoles = data.filter(
          (role) => role.role_name !== "Director"
        );
        setRoles(nonDirectorRoles);
      }
    } catch (err) {
      console.error("Error fetching roles:", err);
    } finally {
      setLoadingRoles(false);
    }
  };

  // Fetch filtered employees based on division and role
  const fetchFilteredEmployees = async (divisionId = selectedDivisionId, roleId = selectedRoleId) => {

    setLoadingAvailableEmployees(true);
    try {
      // Build query parameters for the filter API
      const params = new URLSearchParams();
      
      // Always send both parameters, even if they're empty
      // This allows the backend switch case to handle all combinations properly
      params.append("division_id", divisionId || "");
      params.append("role_id", roleId || "");

      const url = `${buildApiUrl(
        API_ENDPOINTS.EMPLOYEES_FILTER
      )}?${params.toString()}`;


      const response = await fetch(url);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      // Filter out employees already assigned to this project
      const currentEmployeeIds = employees.map(
        (emp) => emp.employee_id || emp.id
      );

      let available = [];
      if (Array.isArray(data)) {
        // First filter out current project employees
        available = data.filter(
          (emp) => !currentEmployeeIds.includes(emp.employee_id || emp.id)
        );

        // Then filter out directors (role_name = Director)
        available = available.filter((emp) => emp.role_name !== "Director");
      } else {
        console.warn("Response is not an array:", data);
      }



      // If no employees found after filtering, show all employees for debugging
      if (available.length === 0 && Array.isArray(data) && data.length > 0) {
        setAvailableEmployees(data);
      } else {
        setAvailableEmployees(available);
      }
    } catch (err) {
      console.error("Error fetching filtered employees:", err);
      // Fallback to fetching all available employees
      fetchAvailableEmployees();
    } finally {
      setLoadingAvailableEmployees(false);
    }
  };

  // Reset filters when modal is closed
  const handleCloseModal = () => {
    setShowAddEmployeeModal(false);
    setSelectedDivisionId("");
    setSelectedRoleId("");
    setSelectedEmployeeId("");
    setAvailableEmployees([]);
    setEmployeeError(""); // Clear any error messages
  };

  // Employee management functions
  const handleAddEmployee = () => {
    setShowAddEmployeeModal(true);
    fetchDivisions();
    fetchRoles();
    // Use the unified filtering function to get all employees initially
    fetchFilteredEmployees();
  };

  // Employee contribution functions
  const handleAddContribution = () => {
    // Ensure employees are loaded before opening modal
    if (employees.length === 0) {
      fetchEmployees();
    }
    setShowAddContributionModal(true);
    setContributionError("");
    setSelectedContributionEmployeeId("");
    setContributionPercentage("");
    setContributionDescription("");
    setIsUpdatingContribution(false);
    setExistingContributionId(null);
  };

  const handleCloseContributionModal = () => {
    setShowAddContributionModal(false);
    setSelectedContributionEmployeeId("");
    setContributionPercentage("");
    setContributionDescription("");
    setContributionError("");
    setIsUpdatingContribution(false);
    setExistingContributionId(null);
  };

  // Check for existing contribution when employee is selected
  const checkExistingContribution = async (employeeId) => {
    if (!employeeId || !project?.project_id) return;

    try {
      const response = await fetch(
        buildApiUrl(
          `${API_ENDPOINTS.GET_EMPLOYEE_CONTRIBUTION}?employee_id=${employeeId}&project_id=${project.project_id}`
        )
      );

      if (response.ok) {
        const data = await response.json();
        if (data.data && data.data.length > 0) {
          // Contribution exists, pre-populate fields
          const contribution = data.data[0]; // Get the most recent one
          setContributionPercentage(contribution.contribution_percentage?.toString() || "");
          setContributionDescription(contribution.contribution_description || "");
          setIsUpdatingContribution(true);
          setExistingContributionId(contribution.contribution_id);
          return true;
        }
      }
    } catch (err) {
      console.error("Error checking existing contribution:", err);
    }

    // No existing contribution found
    setContributionPercentage("");
    setContributionDescription("");
    setIsUpdatingContribution(false);
    setExistingContributionId(null);
    return false;
  };

  /**
   * Fetches all contributions for the current project to calculate total
   */
  const fetchAllProjectContributions = async (projectId) => {
    try {
      const response = await fetch(
        buildApiUrl(
          `${API_ENDPOINTS.GET_EMPLOYEE_CONTRIBUTION}?project_id=${projectId}`
        )
      );

      if (response.ok) {
        const data = await response.json();
        if (data.data && Array.isArray(data.data)) {
          // Get the most recent contribution for each employee
          const contributionsMap = {};
          data.data.forEach((contribution) => {
            const empId = contribution.employee_id;
            // Only keep the most recent contribution per employee
            if (!contributionsMap[empId] || 
                new Date(contribution.date_logged) > new Date(contributionsMap[empId].date_logged)) {
              contributionsMap[empId] = contribution;
            }
          });
          return contributionsMap;
        }
      }
      return {};
    } catch (err) {
      console.error("Error fetching all project contributions:", err);
      return {};
    }
  };

  const addEmployeeContribution = async () => {
    if (!selectedContributionEmployeeId || !contributionPercentage) {
      setContributionError("Please select an employee and enter contribution percentage");
      return;
    }

    const percentage = parseFloat(contributionPercentage);
    if (isNaN(percentage) || percentage < 0 || percentage > 100) {
      setContributionError("Contribution percentage must be a number between 0 and 100");
      return;
    }

    setAddingContribution(true);
    setContributionError("");

    try {
      // Validate total contributions don't exceed 100%
      const allContributions = await fetchAllProjectContributions(project.project_id);
      let totalContribution = 0;
      
      // Calculate current total, excluding the employee being updated (if updating)
      Object.keys(allContributions).forEach((empId) => {
        const empIdNum = parseInt(empId);
        const selectedEmpIdNum = parseInt(selectedContributionEmployeeId);
        
        // If updating, exclude the old contribution of this employee
        if (isUpdatingContribution && empIdNum === selectedEmpIdNum) {
          // Skip this employee's old contribution
          return;
        }
        
        totalContribution += parseFloat(allContributions[empId].contribution_percentage || 0);
      });
      
      // Add the new contribution
      const newTotal = totalContribution + percentage;
      
      if (newTotal > 100) {
        const currentTotal = totalContribution.toFixed(2);
        const remaining = (100 - totalContribution).toFixed(2);
        setContributionError(
          `Total contribution cannot exceed 100%. Current total: ${currentTotal}%. ` +
          `You can only add up to ${remaining}% more.`
        );
        setAddingContribution(false);
        return;
      }

      // Helper function to get current user ID from localStorage or sessionStorage
      const getCurrentUserId = () => {
        try {
          const user = JSON.parse(
            localStorage.getItem("user") || sessionStorage.getItem("user") || "{}"
          );
          return user.user_id || 201; // Default fallback user ID
        } catch (error) {
          console.error("Error getting current user:", error);
          return 201; // Default fallback
        }
      };

      // Use UPDATE route if contribution exists, otherwise use ADD route
      const endpoint = isUpdatingContribution
        ? API_ENDPOINTS.UPDATE_EMPLOYEE_CONTRIBUTION
        : API_ENDPOINTS.ADD_EMPLOYEE_CONTRIBUTION;
      
      const method = isUpdatingContribution ? "PUT" : "POST";

      const response = await fetch(
        buildApiUrl(endpoint),
        {
          method: method,
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            employee_id: parseInt(selectedContributionEmployeeId),
            project_id: project.project_id,
            contribution_percentage: percentage,
            contribution_description: contributionDescription || null,
            user_id: getCurrentUserId(),
          }),
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || `Failed to ${isUpdatingContribution ? 'update' : 'add'} employee contribution`);
      }

      // Refresh employee contributions to show updated percentage
      if (employees.length > 0 && project?.project_id) {
        await fetchEmployeeContributions(employees, project.project_id);
      }
      
      // Show success popup with contribution message
      setSuccessMessage(isUpdatingContribution ? "Contribution updated successfully" : "Contribution added successfully");
      setSuccessSubMessage("");
      setShowSuccessPopup(true);
      
      // Close modal and reset states after a short delay
      setTimeout(() => {
        handleCloseContributionModal();
        setShowSuccessPopup(false);
        setSuccessMessage("");
        setSuccessSubMessage("");
      }, 2000);
    } catch (err) {
      console.error(`Error ${isUpdatingContribution ? 'updating' : 'adding'} employee contribution:`, err);
      setContributionError(err.message || `Failed to ${isUpdatingContribution ? 'update' : 'add'} employee contribution`);
    } finally {
      setAddingContribution(false);
    }
  };

  /**
   * Handles employee removal with confirmation dialog
   * @param {Object} employee - Employee object to be removed
   */
  const handleDeleteEmployee = (employee) => {
    setEmployeeToDelete(employee);
    setShowDeleteConfirm(true);
  };

  /**
   * Removes an employee from the current project
   * @param {Object} employee - Employee object to be removed
   */
  const deleteEmployeeFromProject = async (employee) => {
    try {
      // Helper function to get current user ID from localStorage or sessionStorage
      const getCurrentUserId = () => {
        const user = JSON.parse(
          localStorage.getItem("user") || sessionStorage.getItem("user") || "{}"
        );
        return user.user_id || 201; // Default fallback user ID
      };

      const response = await fetch(
        buildApiUrl(
          API_ENDPOINTS.EMPLOYEE_PROJECT_BY_ID(
            employee.employee_id || employee.id,
            project.project_id
          )
        ),
        {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            user_id: getCurrentUserId(),
          }),
        }
      );

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      // Refresh the employees list after successful removal (this will also refresh contributions)
      await fetchEmployees();
    } catch (err) {
      console.error("Error removing employee from project:", err);
    }
  };

  // Handle division change
  const handleDivisionChange = (e) => {
    const divisionId = e.target.value;
    setSelectedDivisionId(divisionId);
    setSelectedRoleId(""); // Reset role when division changes
    setSelectedEmployeeId(""); // Reset employee selection

    // Always use the unified filtering function with the new divisionId
    fetchFilteredEmployees(divisionId, "");
  };

  // Handle role change
  const handleRoleChange = (e) => {
    const roleId = e.target.value;
    setSelectedRoleId(roleId);
    setSelectedEmployeeId(""); // Reset employee selection

    // Always use the unified filtering function with the new roleId
    fetchFilteredEmployees(selectedDivisionId, roleId);
  };



  // Add employee to project
  const addEmployeeToProject = async () => {
    if (!selectedEmployeeId) {
      return;
    }

    setAddingEmployee(true);
    try {
      // Helper function to get current user ID from localStorage or sessionStorage
      const getCurrentUserId = () => {
        // Try to get from localStorage or session
        const user = JSON.parse(
          localStorage.getItem("user") || sessionStorage.getItem("user") || "{}"
        );
        return user.user_id || 201; // Default to 201 if no user found
      };

      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.EMPLOYEE_PROJECTS),
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            project_id: project.project_id,
            employee_id: selectedEmployeeId,
            user_id: getCurrentUserId(),
          }),
        }
      );

      if (!response.ok) {
        const errorText = await response.text();
        throw new Error(`HTTP error! status: ${response.status} - ${errorText}`);
      }

      // Refresh the employees list to show newly added employee
      await fetchEmployees();

      // Close modal and reset form
      setShowAddEmployeeModal(false);
      setSelectedEmployeeId("");
    } catch (err) {
      console.error("Error adding employee to project:", err);
      // Show error to user
      setEmployeeError(`Failed to add employee: ${err.message}`);
    } finally {
      setAddingEmployee(false);
    }
  };

  return (
    <>
      {/* Main Modal Overlay - Full screen with semi-transparent background */}
      <div
        className="fixed inset-0 flex items-center justify-center z-50 p-4"
        style={{ backgroundColor: "rgba(0, 0, 0, 0.1)" }}
      >
        {/* Clickable backdrop to close modal when clicked outside */}
        <div
          className="absolute inset-0"
          onClick={handleClose}
          style={{ cursor: "pointer" }}
          title="Click to close"
        />
        {/* Modal Content Container - Prevents event bubbling and provides scrolling */}
        <div
          className={`${modalBgClass} rounded-lg max-w-4xl w-full max-h-[95vh] sm:max-h-[90vh] overflow-y-auto relative z-60 border mobile-scroll-hidden ${
            isLight ? "border-yellow-200" : "border-slate-600 shadow-2xl"
          }`}
          onClick={(e) => e.stopPropagation()}
        >
          {/* Modal Header - Contains title, description, and action buttons */}
          <div
            className={`p-4 sm:p-6 border-b ${
              isLight ? "border-yellow-200" : "border-slate-600"
            }`}
          >
            <div className="flex items-start justify-between gap-4">
              {/* Header Info Section */}
              <div className="flex items-center gap-3 flex-1 min-w-0">
                <div
                  className={`p-2 rounded-full flex-shrink-0 ${
                    isLight ? "bg-yellow-100" : "bg-blue-900"
                  }`}
                >
                  <FaProjectDiagram
                    className={`text-base sm:text-lg ${
                      isLight ? "text-amber-600" : "text-cyan-400"
                    }`}
                  />
                </div>
                <div className="min-w-0 flex-1">
                  <h2
                    className={`text-lg sm:text-xl font-semibold ${
                      isLight ? "text-amber-800" : "text-slate-100"
                    }`}
                  >
                    Project Details
                  </h2>
                  <p
                    className={`text-xs sm:text-sm ${
                      isLight ? "text-amber-700" : "text-slate-300"
                    } opacity-75`}
                  >
                    Comprehensive project information
                  </p>
                </div>
              </div>

              {/* Close Button - Aligned with header */}
              <div className="flex-shrink-0 self-start">
                <button
                  onClick={handleClose}
                  className={`p-2.5 rounded-lg font-semibold text-sm transition-all duration-200 shadow-sm hover:shadow-md flex items-center justify-center ${
                    isLight
                      ? "text-gray-700 hover:text-gray-900 hover:bg-gray-100 bg-white border border-gray-400 hover:border-gray-500"
                      : "text-gray-200 hover:text-white hover:bg-gray-600 bg-gray-700 border border-gray-500 hover:border-gray-400"
                  }`}
                  title="Close modal"
                >
                  <FaTimes className="text-sm flex-shrink-0" />
                </button>
              </div>
            </div>

            {/* Action Buttons Row - All three buttons covering full width */}
            <div className="flex flex-row items-center gap-2 mt-4">
              {/* Upload Button */}
              <button
                onClick={handleUpload}
                className={`flex-1 px-3 py-2.5 rounded-lg font-semibold text-xs sm:text-sm transition-all duration-200 flex items-center justify-center gap-1 sm:gap-2 shadow-sm hover:shadow-md ${
                  isLight
                    ? "bg-blue-600 hover:bg-blue-700 text-white border border-blue-700"
                    : "bg-blue-600 hover:bg-blue-700 text-white border border-blue-500"
                }`}
                title="Upload Project Document"
              >
                <FaUpload className="text-sm" />
                <span>Upload</span>
              </button>
              
              {/* Download Button */}
              <button
                onClick={handleDownload}
                disabled={!hasForm || checkingForm}
                className={`flex-1 px-3 py-2.5 rounded-lg font-semibold text-xs sm:text-sm transition-all duration-200 flex items-center justify-center gap-1 sm:gap-2 shadow-sm hover:shadow-md ${
                  hasForm && !checkingForm
                    ? isLight
                      ? "bg-green-600 hover:bg-green-700 text-white border border-green-700"
                      : "bg-green-600 hover:bg-green-700 text-white border border-green-500"
                    : isLight
                    ? "bg-gray-300 text-gray-500 cursor-not-allowed border border-gray-300"
                    : "bg-gray-600 text-gray-400 cursor-not-allowed border border-gray-600"
                }`}
                title={
                  checkingForm
                    ? "Checking form availability..."
                    : hasForm
                    ? "Download Project Form"
                    : "No form available"
                }
              >
                {checkingForm ? (
                  <FaSpinner className="text-sm animate-spin" />
                ) : (
                  <FaDownload className="text-sm" />
                )}
                <span>{checkingForm ? "Checking..." : "Download"}</span>
              </button>

              {/* Show/Hide Employees Button */}
              <button
                onClick={handleShowEmployees}
                className={`flex-1 px-3 py-2.5 rounded-lg font-semibold text-xs sm:text-sm transition-all duration-200 flex items-center justify-center gap-1 sm:gap-2 shadow-sm hover:shadow-md ${
                  showEmployees
                    ? isLight
                      ? "bg-amber-600 hover:bg-amber-700 text-white border border-amber-700"
                      : "bg-amber-600 hover:bg-amber-700 text-white border border-amber-500"
                    : isLight
                    ? "bg-gray-100 hover:bg-gray-200 text-gray-700 border border-gray-300"
                    : "bg-gray-700 hover:bg-gray-600 text-gray-200 border border-gray-600"
                }`}
                title={showEmployees ? "Hide employee list" : "Show employee list"}
              >
                <FaUsers className="text-sm" />
                <span className="hidden sm:inline">
                  {showEmployees ? "Hide Employees" : "Employees"}
                </span>
                <span className="sm:hidden">
                  {showEmployees ? "Hide" : "Show"}
                </span>
              </button>
            </div>
          </div>

          {/* Employees Section */}
          {showEmployees && (
            <div
              className={`p-4 sm:p-6 border-b ${
                isLight
                  ? "border-yellow-200 bg-yellow-50"
                  : "border-slate-600 bg-slate-700"
              }`}
            >
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-4">
                <h3
                  className={`text-base sm:text-lg font-semibold ${
                    isLight ? "text-amber-800" : "text-slate-100"
                  }`}
                >
                  Project Employees
                </h3>
                <div className="flex gap-2">
                  <button
                    onClick={handleAddEmployee}
                    className={`flex-1 sm:flex-none px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 flex items-center justify-center gap-2 shadow-sm hover:shadow-md ${
                      isLight
                        ? "bg-green-600 hover:bg-green-700 text-white border border-green-700"
                        : "bg-green-600 hover:bg-green-700 text-white border border-green-500"
                    }`}
                    title="Add new employee to project"
                  >
                    <FaPlus className="text-sm" />
                    <span className="hidden sm:inline">Add Employee</span>
                    <span className="sm:hidden">Add</span>
                  </button>
                  <button
                    onClick={handleAddContribution}
                    disabled={employees.length === 0 || loadingEmployees}
                    className={`flex-1 sm:flex-none px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 flex items-center justify-center gap-2 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed ${
                      employees.length === 0 || loadingEmployees
                        ? isLight
                          ? "bg-gray-300 text-gray-500 cursor-not-allowed border border-gray-300"
                          : "bg-gray-600 text-gray-400 cursor-not-allowed border border-gray-600"
                        : isLight
                        ? "bg-purple-400 hover:bg-purple-500 text-white border border-purple-500"
                        : "bg-purple-500 hover:bg-purple-600 text-white border border-purple-400"
                    }`}
                    title={
                      loadingEmployees
                        ? "Loading employees..."
                        : employees.length === 0
                        ? "No employees assigned to this project"
                        : "Add employee contribution to project"
                    }
                  >
                    <FaPlus className="text-sm" />
                    <span className="hidden sm:inline">Add Contribution</span>
                    <span className="sm:hidden">Contribution</span>
                  </button>
                  <button
                    onClick={() => fetchEmployees()}
                    disabled={loadingEmployees}
                    className={`flex-1 sm:flex-none px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 flex items-center justify-center gap-2 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed ${
                      isLight
                        ? "bg-blue-600 hover:bg-blue-700 text-white border border-blue-700"
                        : "bg-blue-600 hover:bg-blue-700 text-white border border-blue-500"
                    }`}
                    title="Refresh employee list"
                  >
                    {loadingEmployees ? (
                      <FaSpinner className="text-sm animate-spin" />
                    ) : (
                      <FaUser className="text-sm" />
                    )}
                    <span className="hidden sm:inline">Refresh</span>
                    <span className="sm:hidden">↻</span>
                  </button>
                </div>
              </div>

              {/* Employees List */}
              {loadingEmployees ? (
                <div className="flex items-center justify-center py-8">
                  <FaSpinner className="animate-spin text-2xl text-blue-500" />
                  <span className={`ml-2 ${textClass}`}>
                    Loading employees...
                  </span>
                </div>
              ) : employees.length > 0 ? (
                <div className="space-y-3">
                  {employees.map((employee, index) => (
                    <div
                      key={employee.employee_id || employee.id || index}
                      className={`p-3 sm:p-4 rounded-lg border ${
                        isLight
                          ? "bg-white border-yellow-200 shadow-sm"
                          : "bg-slate-800 border-slate-600 shadow-sm"
                      }`}
                    >
                      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between relative">
                        <div className="flex-1 min-w-0">
                          <h4
                            className={`font-medium text-sm sm:text-base truncate ${
                              isLight ? "text-gray-900" : "text-slate-100"
                            }`}
                          >
                            {employee.employee_name ||
                              employee.name ||
                              employee.full_name ||
                              employee.first_name ||
                              "Unknown Employee"}
                          </h4>
                          <div className="flex flex-col gap-1 sm:flex-row sm:gap-4 mt-1">
                            <p
                              className={`text-xs sm:text-sm ${
                                isLight ? "text-gray-600" : "text-slate-400"
                              }`}
                            >
                              ID:{" "}
                              {employee.employee_id ||
                                employee.id ||
                                employee.user_id ||
                                "N/A"}
                            </p>
                            <p
                              className={`text-xs sm:text-sm ${
                                isLight ? "text-gray-600" : "text-slate-400"
                              }`}
                            >
                              Role:{" "}
                              {employee.role ||
                                employee.position ||
                                employee.job_title ||
                                employee.designation ||
                                employee.role_name ||
                                employee.position_name ||
                                employee.title ||
                                "N/A"}
                            </p>
                          </div>
                        </div>
                        {employeeContributions[employee.employee_id || employee.id] !== undefined && (
                          <div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2 flex flex-col items-center gap-1 min-w-[100px] max-w-[180px]">
                            <div className="flex items-center gap-2 w-full">
                              <span
                                className={`text-xs font-medium whitespace-nowrap ${
                                  isLight ? "text-black" : "text-white"
                                }`}
                              >
                                Contribution
                              </span>
                              <span
                                className={`text-xs font-semibold whitespace-nowrap ${
                                  isLight ? "text-black" : "text-white"
                                }`}
                              >
                                {employeeContributions[employee.employee_id || employee.id]}%
                              </span>
                            </div>
                            <div
                              className={`w-full h-1.5 rounded-full ${
                                isLight ? "bg-gray-200" : "bg-slate-600"
                              }`}
                            >
                              <div
                                className={`h-1.5 rounded-full transition-all duration-500 ${
                                  isLight 
                                    ? "bg-gradient-to-r from-purple-400 to-purple-500" 
                                    : "bg-gradient-to-r from-purple-400 to-purple-500"
                                }`}
                                style={{
                                  width: `${Math.min(
                                    parseFloat(employeeContributions[employee.employee_id || employee.id]) || 0,
                                    100
                                  )}%`,
                                }}
                                title={`Contribution: ${employeeContributions[employee.employee_id || employee.id]}%`}
                              ></div>
                            </div>
                          </div>
                        )}
                        <div className="flex gap-2 self-end sm:self-center">
                          <button
                            onClick={() => handleDeleteEmployee(employee)}
                            className={`px-4 py-2 rounded-lg font-semibold text-sm transition-all duration-200 shadow-sm hover:shadow-md ${
                              isLight
                                ? "bg-red-600 hover:bg-red-700 text-white border border-red-700"
                                : "bg-red-600 hover:bg-red-700 text-white border border-red-500"
                            }`}
                            title="Remove employee from project"
                          >
                            Remove
                          </button>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <div
                  className={`text-center py-8 ${
                    isLight ? "text-gray-500" : "text-slate-400"
                  }`}
                >
                  <FaUsers className="text-3xl mx-auto mb-2 opacity-50" />
                  <p>No employees assigned to this project</p>
                  {/* Debug information */}
                  {/* <div
                  className={`mt-4 p-3 rounded-lg border text-left text-xs ${
                    isLight
                      ? "bg-gray-100 border-gray-300"
                      : "bg-slate-800 border-slate-600"
                  }`}
                >
                  <p className="font-semibold mb-2">Debug Info:</p>
                  <p>Employees array length: {employees.length}</p>
                  <p>Employees data: {JSON.stringify(employees, null, 2)}</p>
                  {employees.length > 0 && (
                    <div className="mt-2">
                      <p className="font-semibold">
                        First employee field names:
                      </p>
                      <p>{Object.keys(employees[0]).join(", ")}</p>
                    </div>
                  )}
                </div> */}
                </div>
              )}
            </div>
          )}

          {/* Content */}
          <div className="p-4 sm:p-6 space-y-4 sm:space-y-6">
            {/* Project Overview */}
            <div
              className={`p-3 sm:p-4 rounded-lg ${
                isLight
                  ? "bg-yellow-50 border border-yellow-200"
                  : "bg-slate-700 border border-slate-600"
              }`}
            >
              <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between mb-3">
                <div className="min-w-0">
                  <h3
                    className={`text-base sm:text-lg font-semibold truncate ${
                      isLight ? "text-amber-800" : "text-slate-100"
                    }`}
                    title={project.project_name}
                  >
                    {project.project_name}
                  </h3>
                  <p
                    className={`text-xs sm:text-sm ${
                      isLight ? "text-amber-700" : "text-slate-300"
                    }`}
                  >
                    Project ID: {project.project_id}
                  </p>
                </div>
                <div className="flex flex-col gap-2 sm:items-end">
                  <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">
                    <div className="flex items-center gap-2">
                      <span
                        className={`text-xs font-medium ${
                          isLight ? "text-amber-700" : "text-slate-300"
                        }`}
                      >
                        Status:
                      </span>
                      <span
                        className={`px-2 sm:px-3 py-1 rounded-full text-xs sm:text-sm font-medium ${
                          project.status_name === "Completed"
                            ? "bg-green-100 text-green-800"
                            : project.status_name === "Ongoing"
                            ? "bg-blue-100 text-blue-800"
                            : project.status_name === "PO Received"
                            ? "bg-yellow-100 text-yellow-800"
                            : project.status_name === "Opened"
                            ? "bg-purple-100 text-purple-800"
                            : project.status_name === "Extended"
                            ? "bg-red-100 text-red-800"
                            : project.status_name === "Shelved"
                            ? "bg-gray-100 text-gray-600"
                            : "bg-gray-100 text-gray-800"
                        }`}
                      >
                        {project.status_name || "Not Assigned"}
                      </span>
                    </div>
                    <div className="flex items-center gap-2">
                      <span
                        className={`text-xs font-medium ${
                          isLight ? "text-amber-700" : "text-slate-300"
                        }`}
                      >
                        Priority:
                      </span>
                      <span
                        className={`px-2 sm:px-3 py-1 rounded-full text-xs sm:text-sm font-medium ${
                          project.priority_level_name === "High"
                            ? "bg-red-100 text-red-800"
                            : project.priority_level_name === "Medium"
                            ? "bg-yellow-100 text-yellow-800"
                            : project.priority_level_name === "Low"
                            ? "bg-green-100 text-green-800"
                            : "bg-gray-100 text-gray-800"
                        }`}
                      >
                        {project.priority_level_name || "Not Set"}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {/* Progress Bar */}
              <div>
                <div className="flex justify-between items-center mb-2">
                  <span
                    className={`text-xs sm:text-sm font-medium ${
                      isLight ? "text-amber-700" : "text-slate-300"
                    }`}
                  >
                    Progress
                  </span>
                  <span
                    className={`text-base sm:text-lg font-bold ${
                      isLight ? "text-amber-800" : "text-slate-100"
                    }`}
                  >
                    {project.percent_completed || 0}%
                  </span>
                </div>
                <div
                  className={`w-full h-2 sm:h-3 rounded-full ${
                    isLight ? "bg-gray-200" : "bg-slate-600"
                  }`}
                >
                  <div
                    className={`h-2 sm:h-3 rounded-full transition-all duration-500 ${
                      (project.percent_completed || 0) >= 80
                        ? "bg-gradient-to-r from-green-500 to-green-600"
                        : (project.percent_completed || 0) >= 50
                        ? "bg-gradient-to-r from-blue-500 to-blue-600"
                        : (project.percent_completed || 0) >= 25
                        ? "bg-gradient-to-r from-yellow-500 to-yellow-600"
                        : "bg-gradient-to-r from-red-500 to-red-600"
                    }`}
                    style={{ width: `${project.percent_completed || 0}%` }}
                  ></div>
                </div>
              </div>
            </div>

            {/* Form-like Information Display */}
            <div className="space-y-4 sm:space-y-6">
              {/* Row 1: Project Type, Invoice Status, PO Status */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                <div>
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Project Type
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.type_name || "Not Assigned"}
                  </div>
                </div>

                <div>
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Invoice Status
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.invoice_status_name || "Not Set"}
                  </div>
                </div>

                <div>
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    PO Status
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.po_status_name || project.po_status || "Not Set"}
                  </div>
                </div>
              </div>

              {/* Row 2: Start Date, Division, Deadline */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                <div>
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Start Date
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.project_start_date
                      ? formatIST(project.project_start_date, "date")
                      : "Not Set"}
                  </div>
                </div>

                <div>
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Division
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.division_name || "Not Assigned"}
                  </div>
                </div>

                <div className="sm:col-span-2 lg:col-span-1">
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Deadline
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.deadline
                      ? formatIST(project.deadline, "date")
                      : "Not Set"}
                  </div>
                </div>
              </div>

              {/* Row 3: Estimated Hours, Actual Hours, Project Lead */}
              <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 sm:gap-4">
                <div>
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Estimated Hours
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.estimated_hours
                      ? `${parseFloat(project.estimated_hours).toFixed(
                          2
                        )} hours`
                      : "0.00 hours"}
                  </div>
                </div>

                <div>
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Actual Hours
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.actual_hours
                      ? `${parseFloat(project.actual_hours).toFixed(2)} hours`
                      : "0.00 hours"}
                  </div>
                </div>

                <div className="sm:col-span-2 lg:col-span-1">
                  <label
                    className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                  >
                    Project Lead
                  </label>
                  <div
                    className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  >
                    {project.project_lead_name || "Not Assigned"}
                  </div>
                </div>
              </div>



              {/* Row 4: Remarks (Full Width) */}
              <div>
                <label
                  className={`block text-xs sm:text-sm font-medium ${textClass} mb-1 sm:mb-2`}
                >
                  Remarks
                </label>
                <div
                  className={`w-full px-3 py-2 rounded-md border text-xs sm:text-sm min-h-[60px] ${
                    isLight
                      ? "bg-gray-50 text-gray-900 border-yellow-200"
                      : "bg-slate-700 text-slate-100 border-slate-600"
                  }`}
                >
                  {project.remarks || "No remarks available"}
                </div>
              </div>
            </div>
          </div>

          {/* Footer with Actions */}
          <div
            className={`px-4 sm:px-6 py-3 sm:py-4 border-t ${
              isLight ? "border-yellow-200" : "border-slate-600"
            }`}
          >
            <div className="flex flex-col gap-3 sm:flex-row sm:justify-end sm:gap-3">
              <button
                onClick={() => {
                  onEdit(project);
                  handleClose();
                }}
                className={`px-6 py-3 rounded-lg font-semibold text-sm transition-all duration-200 border shadow-sm hover:shadow-md ${
                  isLight
                    ? "border-amber-400 text-amber-700 hover:bg-amber-50 bg-white hover:border-amber-500"
                    : "border-slate-500 text-slate-200 hover:bg-slate-700 bg-slate-800 hover:border-slate-400"
                } flex items-center justify-center gap-2`}
                title="Edit project details"
              >
                <FaEdit className="text-sm" />
                <span>Edit Project</span>
              </button>

              {showDeleteButton && (
                <button
                  onClick={() => {
                    onDelete(project);
                  }}
                  className={`px-4 py-2 rounded-md font-medium text-sm transition-colors ${
                    isLight
                      ? "bg-red-500 hover:bg-red-600 text-white"
                      : "bg-red-600 hover:bg-red-700 text-white"
                  } flex items-center justify-center gap-2`}
                >
                  <FaTrash className="text-sm" />
                  <span>Delete</span>
                </button>
              )}
            </div>
          </div>
        </div>

        {/* Add Employee Modal - Separate modal for adding employees to the project */}
        {showAddEmployeeModal && (
          <div
            className="fixed inset-0 flex items-center justify-center z-70 p-4"
            style={{ backgroundColor: "rgba(0, 0, 0, 0.3)" }}
          >
            <div
              className="absolute inset-0"
              onClick={handleCloseModal}
              style={{ cursor: "pointer" }}
            />
            <div
              className={`${modalBgClass} rounded-lg max-w-md w-full relative z-80 border ${
                isLight ? "border-yellow-200" : "border-slate-600 shadow-2xl"
              }`}
              onClick={(e) => e.stopPropagation()}
            >
              {/* Modal Header */}
              <div
                className={`p-4 border-b ${
                  isLight ? "border-yellow-200" : "border-slate-600"
                }`}
              >
                <div className="flex items-center justify-between">
                  <h3
                    className={`text-lg font-semibold ${
                      isLight ? "text-amber-800" : "text-slate-100"
                    }`}
                  >
                    Add Employee to Project
                  </h3>
                  <button
                    onClick={handleCloseModal}
                    className={`p-2 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md ${
                      isLight
                        ? "text-gray-600 hover:text-gray-800 hover:bg-gray-100 bg-white border border-gray-300 hover:border-gray-400"
                        : "text-gray-300 hover:text-white hover:bg-gray-600 bg-gray-700 border border-gray-500 hover:border-gray-400"
                    }`}
                    title="Close modal"
                  >
                    <FaTimes className="text-sm flex-shrink-0" />
                  </button>
                </div>
              </div>

              {/* Modal Content */}
              <div className="p-4">
                {/* Division Selection */}
                <div className="mb-4">
                  <label
                    className={`block text-sm font-medium ${textClass} mb-2`}
                  >
                    Select Division (Optional)
                  </label>
                  {loadingDivisions ? (
                    <div className="flex items-center justify-center py-2">
                      <FaSpinner className="animate-spin text-sm text-blue-500" />
                      <span className={`ml-2 text-xs ${textClass}`}>
                        Loading divisions...
                      </span>
                    </div>
                  ) : (
                    <select
                      name="division_id"
                      value={selectedDivisionId}
                      onChange={handleDivisionChange}
                      className={`w-full px-3 py-2 rounded-md border text-sm ${
                        isLight
                          ? "bg-gray-50 text-gray-900 border-yellow-200"
                          : "bg-slate-700 text-slate-100 border-slate-600"
                      }`}
                    >
                      <option value="">No Division Filter</option>
                      {divisions.map((division) => (
                        <option
                          key={division.division_id}
                          value={division.division_id}
                        >
                          {division.division_name}
                        </option>
                      ))}
                    </select>
                  )}
                </div>

                {/* Role Selection */}
                <div className="mb-4">
                  <label
                    className={`block text-sm font-medium ${textClass} mb-2`}
                  >
                    Select Role (Optional)
                  </label>
                  {loadingRoles ? (
                    <div className="flex items-center justify-center py-2">
                      <FaSpinner className="animate-spin text-sm text-blue-500" />
                      <span className={`ml-2 text-xs ${textClass}`}>
                        Loading roles...
                      </span>
                    </div>
                  ) : (
                    <select
                      name="role_id"
                      value={selectedRoleId}
                      onChange={handleRoleChange}
                      className={`w-full px-3 py-2 rounded-md border text-sm ${
                        isLight
                          ? "bg-gray-50 text-gray-900 border-yellow-200"
                          : "bg-slate-700 text-slate-100 border-slate-600"
                      }`}
                    >
                      <option value="">No Role Filter</option>
                      {roles.map((role) => (
                        <option key={role.role_id} value={role.role_id}>
                          {role.role_name}
                        </option>
                      ))}
                    </select>
                  )}
                </div>

                {/* Employee Selection */}
                <div className="mb-4">
                  <label
                    className={`block text-sm font-medium ${textClass} mb-2`}
                  >
                    Select Employee ({availableEmployees.length} available)
                  </label>
                  
                  {/* Error Display */}
                  {employeeError && (
                    <div className={`mb-3 p-3 rounded-md text-sm ${
                      isLight 
                        ? "bg-red-50 border border-red-200 text-red-800" 
                        : "bg-red-900/20 border border-red-700 text-red-300"
                    }`}>
                      <span className="font-medium">Error:</span> {employeeError}
                    </div>
                  )}
                  
                  {loadingAvailableEmployees ? (
                    <div className="flex items-center justify-center py-4">
                      <FaSpinner className="animate-spin text-lg text-blue-500" />
                      <span className={`ml-2 ${textClass}`}>
                        Loading employees...
                      </span>
                    </div>
                  ) : availableEmployees.length > 0 ? (
                    <select
                      name="employee_id"
                      value={selectedEmployeeId}
                      onChange={(e) => {
                        setSelectedEmployeeId(e.target.value);
                        setEmployeeError(""); // Clear error when employee is selected
                      }}
                      className={`w-full px-3 py-2 rounded-md border text-sm ${
                        isLight
                          ? "bg-gray-50 text-gray-900 border-yellow-200"
                          : "bg-slate-700 text-slate-100 border-slate-600"
                      }`}
                    >
                      <option value="">Select an employee...</option>
                      {availableEmployees.map((employee) => (
                        <option
                          key={employee.employee_id || employee.id}
                          value={employee.employee_id || employee.id}
                        >
                          {employee.employee_name ||
                            employee.name ||
                            employee.full_name ||
                            employee.first_name ||
                            "Unknown Employee"}
                          {employee.division_name
                            ? ` (${employee.division_name})`
                            : ""}
                          {employee.role_name ? ` - ${employee.role_name}` : ""}
                        </option>
                      ))}
                    </select>
                  ) : (
                    <div
                      className={`text-center py-4 ${
                        isLight ? "text-gray-500" : "text-slate-400"
                      }`}
                    >
                      <FaUsers className="text-2xl mx-auto mb-2 opacity-50" />
                      <p>No available employees found with selected filters</p>
                      <p className="text-xs mt-1">
                        Try adjusting your division and role selection
                      </p>
                    </div>
                  )}
                </div>

                {/* Modal Footer */}
                <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
                  <button
                    onClick={handleCloseModal}
                    className={`px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 border shadow-sm hover:shadow-md ${
                      isLight
                        ? "border-gray-400 text-gray-700 hover:bg-gray-50 bg-white hover:border-gray-500"
                        : "border-slate-500 text-slate-300 hover:bg-slate-700 bg-slate-800 hover:border-slate-400"
                    }`}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={addEmployeeToProject}
                    disabled={!selectedEmployeeId || addingEmployee}
                    className={`px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 ${
                      isLight
                        ? "bg-green-600 hover:bg-green-700 text-white border border-green-700"
                        : "bg-green-600 hover:bg-green-700 text-white border border-green-500"
                    }`}
                  >
                    {addingEmployee ? (
                      <>
                        <FaSpinner className="text-sm animate-spin" />
                        Adding...
                      </>
                    ) : (
                      <>
                        <FaPlus className="text-sm" />
                        Add Employee
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Add Contribution Modal */}
        {showAddContributionModal && (
          <div
            className="fixed inset-0 flex items-center justify-center z-70 p-4"
            style={{ backgroundColor: "rgba(0, 0, 0, 0.3)" }}
          >
            <div
              className="absolute inset-0"
              onClick={handleCloseContributionModal}
              style={{ cursor: "pointer" }}
            />
            <div
              className={`${modalBgClass} rounded-lg max-w-4xl w-full relative z-80 border ${
                isLight ? "border-yellow-200" : "border-slate-600 shadow-2xl"
              }`}
              onClick={(e) => e.stopPropagation()}
            >
              {/* Modal Header */}
              <div
                className={`p-4 border-b ${
                  isLight ? "border-yellow-200" : "border-slate-600"
                }`}
              >
                <div className="flex items-center justify-between">
                  <h3
                    className={`text-lg font-semibold ${
                      isLight ? "text-amber-800" : "text-slate-100"
                    }`}
                  >
                    {isUpdatingContribution ? "Update Employee Contribution" : "Add Employee Contribution"}
                  </h3>
                  <button
                    onClick={handleCloseContributionModal}
                    className={`p-2 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md ${
                      isLight
                        ? "text-gray-600 hover:text-gray-800 hover:bg-gray-100 bg-white border border-gray-300 hover:border-gray-400"
                        : "text-gray-300 hover:text-white hover:bg-gray-600 bg-gray-700 border border-gray-500 hover:border-gray-400"
                    }`}
                    title="Close contribution modal"
                  >
                    <FaTimes className="text-sm flex-shrink-0" />
                  </button>
                </div>
              </div>

              {/* Modal Content - 3 Column Layout */}
              <div className="p-4">
                {/* Error Display */}
                {contributionError && (
                  <div className={`mb-4 p-3 rounded-md text-sm ${
                    isLight 
                      ? "bg-red-50 border border-red-200 text-red-800" 
                      : "bg-red-900/20 border border-red-700 text-red-300"
                  }`}>
                    <span className="font-medium">Error:</span> {contributionError}
                  </div>
                )}

                {/* 2 Column Grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {/* Column 1: Employees List */}
                  <div className="space-y-2">
                    <label
                      className={`block text-sm font-medium ${textClass} mb-2`}
                    >
                      Select Employee ({employees.length} available)
                    </label>
                    <div
                      className={`border rounded-lg p-3 max-h-96 overflow-y-auto ${
                        isLight
                          ? "bg-white border-gray-300"
                          : "bg-slate-800 border-slate-600"
                      }`}
                    >
                      {loadingEmployees ? (
                        <div className="flex items-center justify-center py-4">
                          <FaSpinner className="animate-spin text-lg text-blue-500" />
                          <span className={`ml-2 ${textClass} text-sm`}>
                            Loading employees...
                          </span>
                        </div>
                      ) : employees.length > 0 ? (
                        <div className="space-y-2">
                          {employees.map((employee) => (
                            <div
                              key={employee.employee_id || employee.id}
                              onClick={async () => {
                                const empId = employee.employee_id || employee.id;
                                setSelectedContributionEmployeeId(empId);
                                // Check for existing contribution and pre-populate
                                await checkExistingContribution(empId);
                              }}
                              className={`p-3 rounded-lg cursor-pointer transition-all duration-200 border ${
                                selectedContributionEmployeeId ===
                                (employee.employee_id || employee.id)
                                  ? isLight
                                    ? "bg-blue-100 border-blue-400"
                                    : "bg-blue-900/30 border-blue-500"
                                  : isLight
                                  ? "bg-gray-50 border-gray-200 hover:bg-gray-100"
                                  : "bg-slate-700 border-slate-600 hover:bg-slate-600"
                              }`}
                            >
                              <h4
                                className={`font-medium text-sm ${
                                  isLight ? "text-gray-900" : "text-slate-100"
                                }`}
                              >
                                {employee.employee_name ||
                                  employee.name ||
                                  employee.full_name ||
                                  "Unknown Employee"}
                              </h4>
                              <p
                                className={`text-xs mt-1 ${
                                  isLight ? "text-gray-600" : "text-slate-400"
                                }`}
                              >
                                ID: {employee.employee_id || employee.id || "N/A"}
                                {employee.role_name && ` • ${employee.role_name}`}
                              </p>
                            </div>
                          ))}
                        </div>
                      ) : (
                        <div
                          className={`text-center py-4 ${
                            isLight ? "text-gray-500" : "text-slate-400"
                          }`}
                        >
                          <FaUsers className="text-2xl mx-auto mb-2 opacity-50" />
                          <p className="text-sm">No employees assigned to this project</p>
                        </div>
                      )}
                    </div>
                  </div>

                  {/* Column 2: Contribution Percentage and Description */}
                  <div className="space-y-4">
                    {/* Contribution Percentage */}
                    <div className="space-y-2">
                      <label
                        htmlFor="contributionPercentage"
                        className={`block text-sm font-medium ${textClass} mb-2`}
                      >
                        Contribution Percentage (%)
                      </label>
                      <input
                        type="number"
                        id="contributionPercentage"
                        min="0"
                        max="100"
                        step="0.01"
                        value={contributionPercentage}
                        onChange={(e) => setContributionPercentage(e.target.value)}
                        placeholder="Enter percentage (0-100)"
                        className={`w-full px-3 py-2 rounded-md border text-sm ${
                          isLight
                            ? "bg-white text-gray-900 border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
                            : "bg-slate-700 text-slate-100 border-slate-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-900"
                        } focus:outline-none`}
                      />
                      <p
                        className={`text-xs ${
                          isLight ? "text-gray-500" : "text-slate-400"
                        }`}
                      >
                        Enter a value between 0 and 100
                      </p>
                    </div>

                    {/* Contribution Description */}
                    <div className="space-y-2">
                      <label
                        htmlFor="contributionDescription"
                        className={`block text-sm font-medium ${textClass} mb-2`}
                      >
                        Contribution Description
                      </label>
                      <textarea
                        id="contributionDescription"
                        value={contributionDescription}
                        onChange={(e) => setContributionDescription(e.target.value)}
                        placeholder="Describe the contribution..."
                        rows="8"
                        className={`w-full px-3 py-2 rounded-md border text-sm resize-none min-h-[160px] ${
                          isLight
                            ? "bg-white text-gray-900 border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-200"
                            : "bg-slate-700 text-slate-100 border-slate-600 focus:border-blue-500 focus:ring-2 focus:ring-blue-900"
                        } focus:outline-none`}
                      />
                      <p
                        className={`text-xs ${
                          isLight ? "text-gray-500" : "text-slate-400"
                        }`}
                      >
                        Optional: Describe what the employee contributed
                      </p>
                    </div>
                  </div>
                </div>

                {/* Selected Employee Display */}
                {selectedContributionEmployeeId && (
                  <div
                    className={`mt-4 p-3 rounded-lg border ${
                      isLight
                        ? "bg-blue-50 border-blue-200"
                        : "bg-blue-900/20 border-blue-700"
                    }`}
                  >
                    <p className={`text-sm font-medium ${
                      isLight ? "text-blue-800" : "text-blue-300"
                    }`}>
                      Selected:{" "}
                      {employees.find(
                        (e) =>
                          (e.employee_id || e.id) ===
                          parseInt(selectedContributionEmployeeId)
                      )?.employee_name ||
                        employees.find(
                          (e) =>
                            (e.employee_id || e.id) ===
                            parseInt(selectedContributionEmployeeId)
                        )?.name ||
                        "Unknown"}
                    </p>
                  </div>
                )}
              </div>

              {/* Modal Footer */}
              <div className="flex justify-end gap-3 p-4 border-t border-gray-200">
                <button
                  onClick={handleCloseContributionModal}
                  className={`px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 border shadow-sm hover:shadow-md ${
                    isLight
                      ? "border-gray-400 text-gray-700 hover:bg-gray-50 bg-white hover:border-gray-500"
                      : "border-slate-500 text-slate-300 hover:bg-slate-700 bg-slate-800 hover:border-slate-400"
                  }`}
                >
                  Cancel
                </button>
                <button
                  onClick={addEmployeeContribution}
                  disabled={
                    !selectedContributionEmployeeId ||
                    !contributionPercentage ||
                    addingContribution
                  }
                  className={`px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 ${
                    isLight
                      ? "bg-purple-400 hover:bg-purple-500 text-white border border-purple-500"
                      : "bg-purple-500 hover:bg-purple-600 text-white border border-purple-400"
                  }`}
                >
                  {addingContribution ? (
                    <>
                      <FaSpinner className="text-sm animate-spin" />
                      {isUpdatingContribution ? "Updating..." : "Adding..."}
                    </>
                  ) : (
                    <>
                      <FaPlus className="text-sm" />
                      {isUpdatingContribution ? "Update Contribution" : "Add Contribution"}
                    </>
                  )}
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Upload Modal */}
        {showUploadModal && (
          <div
            className="fixed inset-0 flex items-center justify-center z-70 p-4"
            style={{ backgroundColor: "rgba(0, 0, 0, 0.3)" }}
          >
            <div
              className="absolute inset-0"
              onClick={closeUploadModal}
              style={{ cursor: "pointer" }}
            />
            <div
              className={`${modalBgClass} rounded-lg max-w-md w-full relative z-80 border ${
                isLight ? "border-yellow-200" : "border-slate-600 shadow-2xl"
              }`}
              onClick={(e) => e.stopPropagation()}
            >
              {/* Modal Header */}
              <div
                className={`p-4 border-b ${
                  isLight ? "border-yellow-200" : "border-slate-600"
                }`}
              >
                <div className="flex items-center justify-between">
                  <h3
                    className={`text-lg font-semibold ${
                      isLight ? "text-amber-800" : "text-slate-100"
                    }`}
                  >
                    Upload File
                  </h3>
                  <button
                    onClick={closeUploadModal}
                    className={`p-2 rounded-lg transition-all duration-200 shadow-sm hover:shadow-md ${
                      isLight
                        ? "text-gray-600 hover:text-gray-800 hover:bg-gray-100 bg-white border border-gray-300 hover:border-gray-400"
                        : "text-gray-300 hover:text-white hover:bg-gray-600 bg-gray-700 border border-gray-500 hover:border-gray-400"
                    }`}
                    title="Close upload modal"
                  >
                    <FaTimes className="text-sm flex-shrink-0" />
                  </button>
                </div>
              </div>

              {/* Modal Content */}
              <div className="p-4">
                {/* File Input */}
                <div className="mb-4">
                  <label
                    className={`block text-sm font-medium ${textClass} mb-2`}
                  >
                    Select File
                  </label>
                  <input
                    type="file"
                    onChange={handleFileChange}
                    className={`w-full px-3 py-2 rounded-md border text-sm ${
                      isLight
                        ? "bg-gray-50 text-gray-900 border-yellow-200"
                        : "bg-slate-700 text-slate-100 border-slate-600"
                    }`}
                  />
                  {selectedFile && (
                    <div
                      className={`mt-2 p-2 rounded-md text-sm ${
                        isLight
                          ? "bg-green-50 border border-green-200 text-green-800"
                          : "bg-green-900/20 border border-green-700 text-green-300"
                      }`}
                    >
                      <span className="font-medium">Selected file:</span>{" "}
                      {selectedFile.name}
                      <br />
                      <span className="text-xs opacity-75">
                        Size: {(selectedFile.size / 1024 / 1024).toFixed(2)} MB
                      </span>
                    </div>
                  )}
                </div>

                {/* Modal Footer */}
                <div className="flex justify-end gap-3 pt-4 border-t border-gray-200">
                  <button
                    onClick={closeUploadModal}
                    className={`px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 border shadow-sm hover:shadow-md ${
                      isLight
                        ? "border-gray-400 text-gray-700 hover:bg-gray-50 bg-white hover:border-gray-500"
                        : "border-slate-500 text-slate-300 hover:bg-slate-700 bg-slate-800 hover:border-slate-400"
                    }`}
                  >
                    Cancel
                  </button>
                  <button
                    onClick={handleUploadConfirm}
                    disabled={!selectedFile || uploading}
                    className={`px-4 py-2.5 rounded-lg font-semibold text-sm transition-all duration-200 shadow-sm hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-2 ${
                      isLight
                        ? "bg-blue-600 hover:bg-blue-700 text-white border border-blue-700"
                        : "bg-blue-600 hover:bg-blue-700 text-white border border-blue-500"
                    }`}
                  >
                    {uploading ? (
                      <>
                        <FaSpinner className="text-sm animate-spin" />
                        Uploading...
                      </>
                    ) : (
                      <>
                        <FaUpload className="text-sm" />
                        Upload File
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          </div>
        )}

        {/* Delete Employee Confirmation Modal */}
        {showDeleteConfirm && employeeToDelete && (
          <div className="fixed inset-0 flex items-center justify-center z-70 p-4">
            <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
              {/* Header */}
              <div className="flex items-center justify-between p-4 border-b border-gray-200">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-full bg-red-100">
                    <svg
                      className="w-5 h-5 text-red-600"
                      fill="none"
                      stroke="currentColor"
                      viewBox="0 0 24 24"
                    >
                      <path
                        strokeLinecap="round"
                        strokeLinejoin="round"
                        strokeWidth="2"
                        d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"
                      />
                    </svg>
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-gray-900">
                      Confirm Removal
                    </h3>
                    <p className="text-sm text-gray-500">
                      Remove employee from project
                    </p>
                  </div>
                </div>
              </div>

              {/* Content */}
              <div className="p-4">
                <p className="text-gray-700">
                  Are you sure you want to remove{" "}
                  <span className="font-semibold">
                    {employeeToDelete.employee_name ||
                      employeeToDelete.name ||
                      "this employee"}
                  </span>{" "}
                  from the project?
                </p>
              </div>

              {/* Footer */}
              <div className="flex justify-end gap-3 p-4 border-t border-gray-200">
                <button
                  onClick={() => setShowDeleteConfirm(false)}
                  className="px-4 py-2 bg-gray-300 text-gray-700 rounded-md hover:bg-gray-400 transition-colors"
                >
                  Cancel
                </button>
                <button
                  onClick={() => {
                    deleteEmployeeFromProject(employeeToDelete);
                    setShowDeleteConfirm(false);
                    setEmployeeToDelete(null);
                  }}
                  className="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-colors"
                >
                  Remove Employee
                </button>
              </div>
            </div>
          </div>
        )}

        {/* Success Popup */}
        {showSuccessPopup && (
          <div className="fixed inset-0 flex items-center justify-center z-80 p-4">
            <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 border-2 border-green-200">
              {/* Header */}
              <div className="flex items-center justify-between p-4 border-b border-green-200 bg-green-50">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-full bg-green-100">
                    <FaCheckCircle className="w-6 h-6 text-green-600" />
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-green-800">
                      Success!
                    </h3>
                    <p className="text-sm text-green-600">
                      {successMessage || "Operation completed successfully"}
                    </p>
                  </div>
                </div>
              </div>

              {/* Content */}
              <div className="p-4">
                <p className="text-gray-700 text-center">
                  {successSubMessage ? (
                    <>
                      The kickoff form for{" "}
                      <span className="font-semibold">{project?.project_name}</span>{" "}
                      has been uploaded successfully!
                    </>
                  ) : (
                    successMessage || "Operation completed successfully"
                  )}
                </p>
                {successSubMessage && (
                  <p className="text-gray-600 text-sm text-center mt-2">
                    {successSubMessage}
                  </p>
                )}
              </div>
            </div>
          </div>
        )}

        {/* Error Popup */}
        {showErrorPopup && (
          <div className="fixed inset-0 flex items-center justify-center z-80 p-4">
            <div className="bg-white rounded-lg shadow-xl max-w-md w-full mx-4 border-2 border-red-200">
              {/* Header */}
              <div className="flex items-center justify-between p-4 border-b border-red-200 bg-red-50">
                <div className="flex items-center gap-3">
                  <div className="p-2 rounded-full bg-red-100">
                    <FaExclamationTriangle className="w-6 h-6 text-red-600" />
                  </div>
                  <div>
                    <h3 className="text-lg font-semibold text-red-800">
                      Upload Failed
                    </h3>
                    <p className="text-sm text-red-600">Please try again</p>
                  </div>
                </div>
              </div>

              {/* Content */}
              <div className="p-4">
                <p className="text-gray-700 text-center">
                  There was an error uploading the form. Please check your file
                  and try again.
                </p>
              </div>
            </div>
          </div>
        )}
      </div>
    </>
  );
};

// Export the component for use in other parts of the application
export default ProjectDetailsModal;
