import React, { useState, useEffect, useMemo } from "react";
import * as XLSX from "xlsx";
import { formatIST } from "../utils/timeUtils";
import { FaDownload } from "react-icons/fa";
import ProjectsHeader from "../components/Projects/ProjectsHeader";
import LoadingState from "../components/Projects/LoadingState";
import ErrorState from "../components/Projects/ErrorState";
import ProjectStats from "../components/Projects/ProjectStats";
import ProjectFilters from "../components/Projects/ProjectFilters";

import ProjectsTable from "../components/Projects/ProjectsTable";
import MobileProjectsView from "../components/Projects/MobileProjectsView";
import ProjectDetailsModal from "../components/Projects/ProjectDetailsModal";
import EditProjectModal from "../components/Projects/EditProjectModal";
import AddProjectModal from "../components/Projects/AddProjectModal";
import DeleteConfirmationModal from "../components/Projects/DeleteConfirmationModal";
import { buildApiUrl, API_ENDPOINTS } from "../utils/config";
import { useTheme } from "../contexts/ThemeContext";

/**
 * ProjectsPage Component
 * 
 * FIXED: PO Status column now shows values immediately after adding/editing projects
 * without requiring a page refresh. The solution stores the successful API endpoint
 * that includes PO Status data and uses it for all subsequent data refreshes.
 */

const ProjectsPage = () => {
  const { isLight } = useTheme();
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [searchTerm, setSearchTerm] = useState("");
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);

  // Filter states
  const [projectTypes, setProjectTypes] = useState([]);
  const [projectStatuses, setProjectStatuses] = useState([]);
  const [projectPriorities, setProjectPriorities] = useState([]);
  const [poStatuses, setPoStatuses] = useState([]);
  const [invoiceStatuses, setInvoiceStatuses] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [divisions, setDivisions] = useState([]);
  const [selectedType, setSelectedType] = useState("All");
  const [selectedStatus, setSelectedStatus] = useState("All");
  const [selectedPriority, setSelectedPriority] = useState("All");
  const [selectedPoStatus, setSelectedPoStatus] = useState("All");
  const [filtersLoading, setFiltersLoading] = useState(true);

  // Modal state
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [selectedProject, setSelectedProject] = useState(null);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  const [addLoading, setAddLoading] = useState(false);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [deleteLoading, setDeleteLoading] = useState(false);

  // Error popup state
  const [isErrorPopupOpen, setIsErrorPopupOpen] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  // Operation message for create, edit, delete operations
  const [operationMessage, setOperationMessage] = useState("");
  const [poStatusWarning, setPoStatusWarning] = useState("");

  // Fetch projects from API
  useEffect(() => {
    const fetchProjects = async () => {
      try {
        setLoading(true);
        // Try different endpoints to find one that includes PO Status
        let response = await fetch(
          buildApiUrl(API_ENDPOINTS.PROJECTS_FROM_VIEW)
        );
        
        // If that doesn't work, try the projects with lead details
        if (!response.ok) {
          response = await fetch(
            buildApiUrl(API_ENDPOINTS.PROJECTS_WITH_LEAD_DETAILS)
          );
        }
        
        // If that doesn't work, try the main projects endpoint
        if (!response.ok) {
          response = await fetch(
            buildApiUrl(API_ENDPOINTS.PROJECTS)
          );
        }
        
        // If that doesn't work, fall back to the original endpoint
        if (!response.ok) {
          response = await fetch(
            buildApiUrl(API_ENDPOINTS.PROJECTS_WITH_IDS)
          );
        }
        if (!response.ok) {
          throw new Error("Failed to fetch projects");
        }
        const data = await response.json();

        if (data.length > 0) {

          
          // Check if any project has PO Status
          const projectsWithPOStatus = data.filter(p => p.po_status || p.po_status_name);
          if (projectsWithPOStatus.length > 0) {
            setPoStatusWarning(""); // Clear warning if PO Status is available
          } else {
            console.warn('⚠️ No projects have PO Status data. This might indicate:');
            console.warn('1. The backend endpoint doesn\'t include PO Status');
            console.warn('2. PO Status field is not populated in the database');
            console.warn('3. PO Status is stored in a different table/field');
            setPoStatusWarning('PO Status data is not available from the current API endpoint. Please check the backend configuration.');
          }
        }
        setProjects(data);
        setError(null);
        
        // Store the successful endpoint URL for future refreshes
        localStorage.setItem('successfulProjectsEndpoint', response.url);
      } catch (err) {
        setError(err.message);
        console.error("Error fetching projects:", err);
      } finally {
        setLoading(false);
      }
    };

    fetchProjects();
  }, []);

  // Fetch filter data (types, statuses, priorities, invoice statuses, employees)
  useEffect(() => {
    const fetchFilterData = async () => {
      try {
        setFiltersLoading(true);

        // Fetch project types
        const typesResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.PROJECT_TYPE)
        );
        const typesData = typesResponse.ok ? await typesResponse.json() : [];

        // Fetch project statuses
        const statusesResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.PROJECT_STATUS)
        );
        const statusesData = statusesResponse.ok
          ? await statusesResponse.json()
          : [];

        // Fetch project priorities
        const prioritiesResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.PROJECT_PRIORITY)
        );
        const prioritiesData = prioritiesResponse.ok
          ? await prioritiesResponse.json()
          : [];

        // Fetch PO Statuses from API
        const poStatusResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.PO_STATUS)
        );
        const poStatusData = poStatusResponse.ok ? await poStatusResponse.json() : [];

        // Fetch invoice statuses
        const invoiceResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.INVOICE_STATUS)
        );
        const invoiceData = invoiceResponse.ok
          ? await invoiceResponse.json()
          : [];

        // Fetch employees
        const employeesResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.EMPLOYEES)
        );
        const employeesData = employeesResponse.ok
          ? await employeesResponse.json()
          : [];

        // Fetch divisions
        const divisionsResponse = await fetch(
          buildApiUrl(API_ENDPOINTS.DIVISIONS)
        );
        const divisionsData = divisionsResponse.ok
          ? await divisionsResponse.json()
          : [];

        setProjectTypes(typesData);
        setProjectStatuses(statusesData);
        setProjectPriorities(prioritiesData);
        setPoStatuses(poStatusData);
        setInvoiceStatuses(invoiceData);
        setEmployees(employeesData);
        setDivisions(divisionsData);
      } catch (err) {
        console.error("Error fetching filter data:", err);
      } finally {
        setFiltersLoading(false);
      }
    };

    fetchFilterData();
  }, []);

  const filteredProjects = useMemo(() => {
    return projects.filter((project) => {
      const matchesSearch =
        (project.project_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.project_lead_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.type_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.status_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.priority_level_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.project_id || "").toString().includes(searchTerm);

      const matchesType =
        selectedType === "All" ||
        (project.type_name || "").toLowerCase() === selectedType.toLowerCase();
      const matchesStatus =
        selectedStatus === "All" ||
        (project.status_name || "").toLowerCase() ===
          selectedStatus.toLowerCase();
      const matchesPriority =
        selectedPriority === "All" ||
        (project.priority_level_name || "").toLowerCase() ===
          selectedPriority.toLowerCase();

      const matchesPoStatus =
        selectedPoStatus === "All" ||
        (project.po_status_name || project.po_status || "").toLowerCase() ===
          selectedPoStatus.toLowerCase();

      return matchesSearch && matchesType && matchesStatus && matchesPriority && matchesPoStatus;
    });
  }, [projects, searchTerm, selectedType, selectedStatus, selectedPriority, selectedPoStatus]);

  // Pagination calculations
  const totalPages = Math.ceil(filteredProjects.length / itemsPerPage);
  const startIndex = (currentPage - 1) * itemsPerPage;
  const endIndex = startIndex + itemsPerPage;
  const currentProjects = filteredProjects.slice(startIndex, endIndex);

  // Handle project type and status filters from chart click
  useEffect(() => {
    const fromChart = localStorage.getItem('fromChart');
    const selectedProjectType = localStorage.getItem('selectedProjectType');
    const selectedProjectStatus = localStorage.getItem('selectedProjectStatus');
    
    if (fromChart === 'true') {
      if (selectedProjectType) {
        setSelectedType(selectedProjectType);
        // Clear localStorage to prevent re-applying on refresh
        localStorage.removeItem('fromChart');
        localStorage.removeItem('selectedProjectType');
      } else if (selectedProjectStatus) {
        setSelectedStatus(selectedProjectStatus);
        // Clear localStorage to prevent re-applying on refresh
        localStorage.removeItem('fromChart');
        localStorage.removeItem('selectedProjectStatus');
      }
    }
  }, []);

  // Reset to first page when search or filters change
  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm, selectedType, selectedStatus, selectedPriority, selectedPoStatus]);

  // Excel export function
  const exportToExcel = () => {
      const exportData = filteredProjects.map((project) => ({
    "Project ID": project.project_id,
    "Project Name": project.project_name,
    "Project Lead": project.project_lead_name || "Not Assigned",
    Type: project.type_name || "Not Assigned",
    Status: project.status_name || "Not Assigned",
    Priority: project.priority_level_name || "Not Assigned",
    "PO Status": project.po_status_name || project.po_status || "Not Set",
    Progress: `${project.percent_completed || 0}%`,
    "Start Date": project.project_start_date || "Not Set",
    Deadline: project.deadline || "Not Set",
    "Estimated Hours": project.estimated_hours || 0,
    "Actual Hours": project.actual_hours || 0,
    Remarks: project.remarks || "No remarks",
  }));

    // Add filter information if any filters are active
    const activeFilters = [];
    if (selectedType !== "All") activeFilters.push(`Type: ${selectedType}`);
    if (selectedStatus !== "All")
      activeFilters.push(`Status: ${selectedStatus}`);
    if (selectedPriority !== "All")
      activeFilters.push(`Priority: ${selectedPriority}`);
    if (selectedPoStatus !== "All")
      activeFilters.push(`PO Status: ${selectedPoStatus}`);
    if (searchTerm) activeFilters.push(`Search: "${searchTerm}"`);

    let filename = "projects.xlsx";
    if (activeFilters.length > 0) {
      filename = `projects_filtered_${formatIST(new Date()).replace(
        /[- :]/g,
        ""
      )}.xlsx`;
    }

    const worksheet = XLSX.utils.json_to_sheet(exportData);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, "Projects");
    XLSX.writeFile(workbook, filename);
  };

  // Download individual project form function - IMPROVED VERSION
  const downloadProjectForm = async (projectName) => {
    try {
      // For Safety Detection project, try to explicitly request Word format
      const isSafetyDetection = projectName.toLowerCase().includes('safety detection');
      let apiUrl = `${buildApiUrl(API_ENDPOINTS.KICKOFF_FORM)}/download-project-form/${encodeURIComponent(projectName)}`;
      
      if (isSafetyDetection) {
        // Try to add format parameter if the API supports it
        apiUrl += '?format=docx';
      }
      
      const response = await fetch(apiUrl, { 
        method: 'GET',
        headers: isSafetyDetection ? {
          'Accept': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document, application/octet-stream, */*'
        } : {}
      });

      if (!response.ok) {
        throw new Error('Failed to download project form');
      }

      // Get the content type and handle accordingly
      const contentType = response.headers.get('content-type');
      const contentDisposition = response.headers.get('content-disposition');

      let downloadBlob;
      let fileExtension;

      // First, try to get the response as a blob to preserve binary data
      const responseBlob = await response.blob();
      
      // Check if this is a Word document by multiple indicators
      // Special handling for "Safety Detection" project - always treat as Word document
      
      const isWordDocument = 
        isSafetyDetection || // Always treat Safety Detection as Word document
        (contentType && contentType.includes('application/vnd.openxmlformats-officedocument.wordprocessingml.document')) ||
        (contentType && contentType.includes('application/octet-stream')) ||
        (contentDisposition && contentDisposition.includes('.docx')) ||
        (contentDisposition && contentDisposition.includes('word')) ||
        (responseBlob.size > 1000 && responseBlob.type === 'application/octet-stream'); // Word docs are usually larger than 1KB

      if (isWordDocument) {
        // Force download as Word document
        downloadBlob = responseBlob;
        fileExtension = '.docx';

        
        // Ensure the blob has the correct MIME type for Word documents
        if (downloadBlob.type !== 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
          downloadBlob = new Blob([downloadBlob], { 
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
          });
        }
      } else if (contentType && contentType.includes('application/pdf')) {
        // PDF - use as-is
        downloadBlob = responseBlob;
        fileExtension = '.pdf';
      } else {
        // For all other types, try to detect if it's actually Word content
        const arrayBuffer = await responseBlob.arrayBuffer();
        const uint8Array = new Uint8Array(arrayBuffer);
        
        // Check for Word document signature (PK header - ZIP format)
        const isZipBased = uint8Array.length >= 4 && 
          uint8Array[0] === 0x50 && uint8Array[1] === 0x4B; // PK signature
        
        if (isZipBased) {
          // This is likely a Word document (ZIP-based format)
          downloadBlob = responseBlob;
          fileExtension = '.docx';

          
          // Ensure the blob has the correct MIME type for Word documents
          downloadBlob = new Blob([downloadBlob], { 
            type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
          });
        } else {
          // Convert to text format
          const textContent = await responseBlob.text();
          
          // Try to format JSON nicely if it's JSON
          let formattedContent = textContent;
          try {
            const jsonData = JSON.parse(textContent);
            formattedContent = `Project Form: ${projectName}\n\n${JSON.stringify(jsonData, null, 2)}`;
          } catch {
            // Not JSON, use as plain text
            formattedContent = `Project Form: ${projectName}\n\n${textContent}`;
          }
          
          // For Safety Detection project, try to force Word format even if we got text
          if (isSafetyDetection && textContent.length > 100) {
            // Create a simple Word-like structure (this is a fallback)
            const wordContent = `Project Form: ${projectName}\n\n${textContent}`;
            downloadBlob = new Blob([wordContent], { 
              type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' 
            });
            fileExtension = '.docx';
            } else {
              downloadBlob = new Blob([formattedContent], { type: 'text/plain' });
              fileExtension = '.txt';
            }
        }
      }

      // Create download link
      const url = window.URL.createObjectURL(downloadBlob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `${projectName.replace(/[^a-zA-Z0-9]/g, '_')}_form${fileExtension}`;
      
      // Set proper MIME type for the download
      if (fileExtension === '.docx') {
        a.type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
      }
      
      document.body.appendChild(a);
      a.click();
      
      // Cleanup
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
      
      

      
    } catch (error) {
      console.error('Download error:', error);
      

    }
  };

  // Action handlers
  const handleView = (project) => {
    setSelectedProject(project);
    setIsModalOpen(true);
  };

  const handleEdit = (project) => {
    setSelectedProject(project);
    setIsEditModalOpen(true);
  };

  const handleEditSave = async (formData) => {
    try {
      setEditLoading(true);
      setOperationMessage(""); // Clear previous messages

      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.PROJECT_BY_ID(formData.project_id)),
        {
          method: "PUT",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            ...formData,
            user_id: getCurrentUserId(),
          }),
        }
      );

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to update project");
      }

      // Refresh projects data using the same endpoint that was successful initially
      await refreshProjectsData();

      // Show success message
      setOperationMessage(
        `Project "${formData.project_name}" has been updated successfully!`
      );

      // Close the modal
      setIsEditModalOpen(false);
      setSelectedProject(null);
    } catch (error) {
      console.error("Error updating project:", error);
      // Show error in popup instead of inline message
      setErrorMessage(`Error updating project: ${error.message}`);
      setIsErrorPopupOpen(true);
    } finally {
      setEditLoading(false);
    }
  };

  const handleEditClose = () => {
    setIsEditModalOpen(false);
    setSelectedProject(null);
    setOperationMessage(""); // Clear operation message
  };

  const handleAddProject = () => {
    setIsAddModalOpen(true);
  };



  const handleAddSave = async (formData) => {
    try {
      setAddLoading(true);
      setOperationMessage(""); // Clear previous messages

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

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to create project");
      }

      // Refresh projects data using the same endpoint that was successful initially
      await refreshProjectsData();

      // Show success message
      setOperationMessage(
        `Project "${formData.project_name}" has been created successfully!`
      );

      // Close the modal
      setIsAddModalOpen(false);
    } catch (error) {
      console.error("Error creating project:", error);
      // Show error in popup instead of inline message
      setErrorMessage(`Error creating project: ${error.message}`);
      setIsErrorPopupOpen(true);
    } finally {
      setAddLoading(false);
    }
  };

  const handleAddClose = () => {
    setIsAddModalOpen(false);
    setOperationMessage(""); // Clear operation message
  };

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

  /**
   * Helper function to refresh projects using the same endpoint that was successful initially
   * 
   * This fixes the PO Status column issue where values weren't showing after adding/editing
   * projects. Instead of always using PROJECTS_WITH_IDS (which doesn't include PO Status),
   * we store the successful endpoint from the initial fetch and reuse it.
   */
  const refreshProjectsData = async () => {
    try {
      const successfulEndpoint = localStorage.getItem('successfulProjectsEndpoint');
      let response;
      
      if (successfulEndpoint) {
        // Use the same endpoint that was successful initially
        response = await fetch(successfulEndpoint);
      } else {
        // Fallback to the original endpoint if no stored endpoint
        response = await fetch(buildApiUrl(API_ENDPOINTS.PROJECTS_WITH_IDS));
      }
      
      if (response.ok) {
        const updatedProjects = await response.json();
        setProjects(updatedProjects);
        return true;
      }
      return false;
    } catch (error) {
      console.error("Error refreshing projects:", error);
      return false;
    }
  };

  const handleDelete = (project) => {
    setSelectedProject(project);
    setIsDeleteModalOpen(true);
  };

  const handleDeleteConfirm = async (project) => {
    try {
      setDeleteLoading(true);
      setOperationMessage(""); // Clear previous messages

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

      if (!response.ok) {
        const errorData = await response.json();
        throw new Error(errorData.error || "Failed to delete project");
      }

      // Remove the project from the local state
      setProjects((prevProjects) =>
        prevProjects.filter((p) => p.project_id !== project.project_id)
      );

      // Close all modals
      setIsDeleteModalOpen(false);
      handleCloseModal();

      // Show success message
      setOperationMessage(
        `Project "${project.project_name}" has been deleted successfully!`
      );
    } catch (error) {
      console.error("Error deleting project:", error);
      // Close the delete confirmation modal first
      setIsDeleteModalOpen(false);
      // Show specific error message for delete operations
      setErrorMessage("Remove employees from the project before deleting. This project has team members assigned to it.");
      setIsErrorPopupOpen(true);
    } finally {
      setDeleteLoading(false);
    }
  };

  const handleDeleteClose = () => {
    setIsDeleteModalOpen(false);
    setSelectedProject(null);
    setOperationMessage(""); // Clear operation message
  };

  const handleCloseModal = () => {
    setIsModalOpen(false);
    setSelectedProject(null);
  };

  // Function to close error popup
  const handleCloseErrorPopup = () => {
    setIsErrorPopupOpen(false);
    setErrorMessage("");
  };

  // Pagination functions
  const goToPage = (page) => setCurrentPage(page);
  const goToPrevious = () => setCurrentPage((prev) => Math.max(prev - 1, 1));
  const goToNext = () =>
    setCurrentPage((prev) => Math.min(prev + 1, totalPages));

  const totalProjects = projects.length;

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

  return (
    <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
      {/* Header */}
      <ProjectsHeader onAddProject={handleAddProject} />

      {/* Operation Message */}
      {operationMessage && (
        <div
          className={`rounded-lg p-4 ${
            operationMessage.includes("successfully")
              ? "bg-green-50 border border-green-200 text-green-800"
              : "bg-red-50 border border-red-200 text-red-800"
          }`}
        >
          <div className="flex items-center gap-2">
            <span>{operationMessage}</span>
            <button
              onClick={() => setOperationMessage("")}
              className="ml-auto text-lg font-semibold hover:opacity-70"
            >
              ×
            </button>
          </div>
        </div>
      )}

      {/* PO Status Warning */}
      {poStatusWarning && (
        <div className="rounded-lg p-4 bg-yellow-50 border border-yellow-200 text-yellow-800">
          <div className="flex items-center gap-2">
            <span>⚠️ {poStatusWarning}</span>
            <button
              onClick={() => setPoStatusWarning("")}
              className="ml-auto text-lg font-semibold hover:opacity-70"
            >
              ×
            </button>
          </div>
        </div>
      )}

      {/* Loading State */}
      {loading && <LoadingState />}

      {/* Error State */}
      {error && <ErrorState error={error} />}

      {/* Project Stats & Search */}
      {!loading && !error && (
        <ProjectStats
          totalProjects={totalProjects}
          searchTerm={searchTerm}
          setSearchTerm={setSearchTerm}
          exportToExcel={exportToExcel}
        />
      )}

      {/* Project Filters */}
      {!loading && !error && (
        <ProjectFilters
          projectTypes={projectTypes}
          projectStatuses={projectStatuses}
          projectPriorities={projectPriorities}
          poStatuses={poStatuses}
          selectedType={selectedType}
          selectedStatus={selectedStatus}
          selectedPriority={selectedPriority}
          selectedPoStatus={selectedPoStatus}
          onTypeChange={setSelectedType}
          onStatusChange={setSelectedStatus}
          onPriorityChange={setSelectedPriority}
          onPoStatusChange={setSelectedPoStatus}
          filtersLoading={filtersLoading}
        />
      )}

      {/* Projects Table and Mobile View */}
      {!loading && !error && (
        <>
          {/* Desktop Table View */}
          <ProjectsTable
            filteredProjects={filteredProjects}
            currentProjects={currentProjects}
            onView={handleView}
            currentPage={currentPage}
            totalPages={totalPages}
            goToPage={goToPage}
            goToPrevious={goToPrevious}
            goToNext={goToNext}
          />

          {/* Mobile Card View */}
          <MobileProjectsView
            currentProjects={currentProjects}
            currentPage={currentPage}
            totalPages={totalPages}
            goToPrevious={goToPrevious}
            goToNext={goToNext}
            onView={handleView}
          />
        </>
      )}

      {/* Project Details Modal */}
      <ProjectDetailsModal
        project={selectedProject}
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        onEdit={handleEdit}
        onDelete={handleDelete}
        downloadProjectForm={downloadProjectForm}
      />

      {/* Edit Project Modal */}
      <EditProjectModal
        isOpen={isEditModalOpen}
        onClose={handleEditClose}
        project={selectedProject}
        projectTypes={projectTypes}
        projectStatuses={projectStatuses}
        projectPriorities={projectPriorities}
        poStatuses={poStatuses}
        invoiceStatuses={invoiceStatuses}
        employees={employees}
        divisions={divisions}
        onSave={handleEditSave}
        loading={editLoading}
        />

      {/* Add Project Modal */}
      <AddProjectModal
        isOpen={isAddModalOpen}
        onClose={handleAddClose}
        projectTypes={projectTypes}
        projectStatuses={projectStatuses}
        projectPriorities={projectPriorities}
        poStatuses={poStatuses}
        invoiceStatuses={invoiceStatuses}
        employees={employees}
        divisions={divisions}
        onSave={handleAddSave}
        loading={addLoading}
      />

      {/* Delete Confirmation Modal */}
      <DeleteConfirmationModal
        isOpen={isDeleteModalOpen}
        onClose={handleDeleteClose}
        onConfirm={handleDeleteConfirm}
        project={selectedProject}
        loading={deleteLoading}
      />

      {/* Floating Download Button - Mobile Only */}
      <button
        onClick={exportToExcel}
        className={`fixed bottom-6 right-6 w-14 h-14 rounded-full transition-all duration-200 active:scale-95 hover:scale-110 flex items-center justify-center z-40 md:hidden ${
          isLight
            ? 'bg-green-400 hover:bg-green-500 active:bg-green-500 text-white'
            : 'bg-green-500 hover:bg-green-600 active:bg-green-600 text-white'
        }`}
        title="Download All Projects"
      >
        <FaDownload size={16} />
      </button>

      {/* Error Popup Modal */}
      {isErrorPopupOpen && (
        <div className="fixed inset-0 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-lg shadow-lg max-w-md w-full mx-4 border border-gray-200">
            {/* Header */}
            <div className="flex items-center gap-3 p-4 border-b border-gray-200">
              <div className="p-2 rounded-full bg-red-100">
                <svg
                  className="w-6 h-6 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="font-semibold text-gray-800">Error</h3>
                <p className="text-sm text-gray-500">Something went wrong</p>
              </div>
            </div>

            {/* Content */}
            <div className="p-4">
              <p className="text-gray-700 text-sm">
                {errorMessage}
              </p>
            </div>

            {/* Footer */}
            <div className="flex justify-end p-4 border-t border-gray-200">
              <button
                onClick={handleCloseErrorPopup}
                className="px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProjectsPage;
