import React, { useState, useEffect, useMemo } from "react";
import { useTheme } from "../contexts/ThemeContext";
import ProjectLeadsHeader from "../components/ProjectLeads/ProjectLeadsHeader";
import ProjectLeadsStats from "../components/ProjectLeads/ProjectLeadsStats";
import ProjectLeadsTable from "../components/ProjectLeads/ProjectLeadsTable";
import MobileProjectLeadsView from "../components/ProjectLeads/MobileProjectLeadsView";
import AssignLeadModal from "../components/ProjectLeads/AssignLeadModal";
import ProjectDetailsModal from "../components/Projects/ProjectDetailsModal";
import EditProjectLeadModal from "../components/ProjectLeads/EditProjectLeadModal";
import { FaSpinner, FaExclamationTriangle } from "react-icons/fa";
import { buildApiUrl, API_ENDPOINTS } from "../utils/config";

const ProjectLeadPage = ({ onSectionChange }) => {
  const { isLight } = useTheme();
  const [projectLeadsData, setProjectLeadsData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // Pagination state
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [searchTerm, setSearchTerm] = useState("");
  const [assignLeadModalOpen, setAssignLeadModalOpen] = useState(false);
  const [selectedProject, setSelectedProject] = useState(null);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [selectedProjectLead, setSelectedProjectLead] = useState(null);
  const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
  const [projectToDelete, setProjectToDelete] = useState(null);

  const fetchProjectLeads = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await fetch(
        buildApiUrl(API_ENDPOINTS.PROJECTS_WITH_LEAD_DETAILS)
      );

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

      const apiData = await response.json();

      // Map API data to format expected by ProjectLeadsTable
      // Include additional fields for detailed view
      const mappedData = apiData.map((project) => ({
        id: project.project_id,
        leadId: project.project_lead_emp_id,
        leadName: project.project_lead_name,
        projectName: project.project_name,
        type: project.type_name,
        status: project.status_name,
        invoiceStatus: project.invoice_status_name,
        priority: project.priority_level_name,
        // Additional fields for detailed view
        division_name: project.division_name,
        project_start_date: project.project_start_date,
        deadline: project.deadline,
        estimated_hours: project.estimated_hours,
        actual_hours: project.actual_hours,
        percent_completed: project.percent_completed,
        remarks: project.remarks,
        po_status_name: project.po_status_name || project.po_status
      }));

      setProjectLeadsData(mappedData);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchProjectLeads();
  }, []);

  // Filter project leads based on search term
  const filteredProjectLeads = useMemo(() => {
    return projectLeadsData.filter((project) => {
      const matchesSearch =
        (project.leadName || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.projectName || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.type || "").toLowerCase().includes(searchTerm.toLowerCase()) ||
        (project.status || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.invoiceStatus || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.priority || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.division_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.remarks || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.po_status_name || "")
          .toLowerCase()
          .includes(searchTerm.toLowerCase()) ||
        (project.id || "").toString().includes(searchTerm) ||
        (project.leadId || "").toString().includes(searchTerm);

      return matchesSearch;
    });
  }, [projectLeadsData, searchTerm]);

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

  // Reset to first page when search changes
  useEffect(() => {
    setCurrentPage(1);
  }, [searchTerm]);

  // 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));

  // Handle assign lead modal
  const handleAssignLead = () => {
    setAssignLeadModalOpen(true);
  };

  // Handle assign lead success
  const handleAssignLeadSuccess = async () => {
    await fetchProjectLeads();
  };

  // Handle edit project lead success
  const handleEditLeadSuccess = async () => {
    await fetchProjectLeads();
  };

  // Handle edit project lead
  const handleEdit = (project) => {
    try {
      if (!project) {
        console.error("No project data provided to handleEdit");
        return;
      }
      
      setSelectedProjectLead(project);
      setIsEditModalOpen(true);
    } catch (error) {
      console.error("Error opening edit modal:", error);
    }
  };

  // Handle delete project lead
  const handleDelete = (project) => {
    try {
      if (!project) {
        console.error("No project data provided to handleDelete");
        return;
      }
      
      setProjectToDelete(project);
      setIsDeleteModalOpen(true);
    } catch (error) {
      console.error("Error opening delete modal:", error);
    }
  };

  // Handle delete confirmation
  const handleDeleteConfirm = async () => {
    try {
      if (!projectToDelete) {
        console.error("No project to delete");
        return;
      }

      // Here you would typically make an API call to delete the project
      // For now, we'll just remove it from the local state
      setProjectLeadsData(prevData => 
        prevData.filter(project => project.id !== projectToDelete.id)
      );
      
      setIsDeleteModalOpen(false);
      setProjectToDelete(null);
      
      // Show success message or handle as needed
      console.log("Project deleted successfully");
    } catch (error) {
      console.error("Error deleting project:", error);
    }
  };

  // Handle delete modal close
  const handleDeleteClose = () => {
    setIsDeleteModalOpen(false);
    setProjectToDelete(null);
  };

  // Handle view project details
  const handleView = (project) => {
    try {
      if (!project) {
        console.error("No project data provided to handleView");
        return;
      }
      
      // Transform project data to match ProjectDetailsModal expected format
      // Use actual data where available, fallback to defaults only when necessary
      const transformedProject = {
        project_id: project.id,
        project_name: project.projectName || "Not Set",
        status_name: project.status || "Not Set",
        type_name: project.type || "Not Set",
        priority_level_name: project.priority || "Not Set",
        invoice_status_name: project.invoiceStatus || "Not Set",
        division_name: project.division_name || "Not Assigned",
        project_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,
        percent_completed: project.percent_completed || 0,
        project_lead_name: project.leadName || "Not Assigned",
        remarks: project.remarks || "No remarks available",
        po_status_name: project.po_status_name || "Not Set"
      };
      
      setSelectedProject(transformedProject);
      setIsViewModalOpen(true);
    } catch (error) {
      console.error("Error opening view modal:", error);
    }
  };

  if (loading) {
    return (
      <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
        <ProjectLeadsHeader onAssignLead={handleAssignLead} />
        <div
          className={`flex items-center justify-center py-12 ${
            isLight ? "text-amber-600" : "text-gray-300"
          }`}
        >
          <FaSpinner className="animate-spin text-2xl mr-3" />
          <span className="text-lg">Loading project leads...</span>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
        <ProjectLeadsHeader onAssignLead={handleAssignLead} />
        <div
          className={`flex flex-col items-center justify-center py-12 ${
            isLight ? "text-red-600" : "text-red-400"
          }`}
        >
          <FaExclamationTriangle className="text-3xl mb-3" />
          <h3 className="text-lg font-semibold mb-2">
            Error Loading Project Leads
          </h3>
          <p className="text-sm mb-4">{error}</p>
          <button
            onClick={fetchProjectLeads}
            className={`px-4 py-2 rounded-lg font-medium transition-colors ${
              isLight
                ? "bg-amber-500 hover:bg-amber-600 text-white"
                : "bg-blue-600 hover:bg-blue-700 text-white"
            }`}
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  if (projectLeadsData.length === 0) {
    return (
      <div className="space-y-3 max-w-full overflow-hidden px-2 sm:px-4 lg:px-6">
        <ProjectLeadsHeader onAssignLead={handleAssignLead} />
        <div
          className={`text-center py-12 ${
            isLight ? "text-amber-600" : "text-gray-300"
          }`}
        >
          <h3 className="text-lg font-semibold mb-2">No Projects Found</h3>
          <p className="text-sm">No project data is available at the moment.</p>
        </div>
      </div>
    );
  }

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

      {/* Project Leads Stats & Search */}
      {!loading && !error && (
        <ProjectLeadsStats
          totalProjectLeads={projectLeadsData.length}
          searchTerm={searchTerm}
          setSearchTerm={setSearchTerm}
          projectLeadsData={projectLeadsData}
          filteredProjectLeads={filteredProjectLeads}
        />
      )}

      {/* Project Leads Table and Mobile View */}
      {!loading && !error && (
        <>
          {/* Desktop Table View */}
          <ProjectLeadsTable
            projectLeadsData={filteredProjectLeads}
            currentProjectLeads={currentProjectLeads}
            onSectionChange={onSectionChange}
            currentPage={currentPage}
            totalPages={totalPages}
            goToPage={goToPage}
            goToPrevious={goToPrevious}
            goToNext={goToNext}
            onAssignLead={handleAssignLead}
            onEdit={handleEdit}
            onDelete={handleDelete}
            onRefresh={fetchProjectLeads}
          />

          {/* Mobile Card View */}
          <MobileProjectLeadsView
            currentProjectLeads={currentProjectLeads}
            currentPage={currentPage}
            totalPages={totalPages}
            goToPrevious={goToPrevious}
            goToNext={goToNext}
            onSectionChange={onSectionChange}
            searchTerm={searchTerm}
            setSearchTerm={setSearchTerm}
            onView={handleView}
            onEdit={handleEdit}
            onDelete={handleDelete}
          />
        </>
      )}

      {/* Assign Lead Modal */}
      <AssignLeadModal
        isOpen={assignLeadModalOpen}
        onClose={() => setAssignLeadModalOpen(false)}
        onSuccess={handleAssignLeadSuccess}
      />

      {/* Project Details Modal */}
      <ProjectDetailsModal
        isOpen={isViewModalOpen}
        onClose={() => setIsViewModalOpen(false)}
        project={selectedProject}
        onEdit={handleEdit}
        onDelete={handleDelete}
        showDeleteButton={false}
      />

      {/* Edit Project Lead Modal */}
      <EditProjectLeadModal
        isOpen={isEditModalOpen}
        onClose={() => setIsEditModalOpen(false)}
        projectLead={selectedProjectLead}
        onSuccess={handleEditLeadSuccess}
      />

      {/* Delete Confirmation Modal */}
      {isDeleteModalOpen && projectToDelete && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className={`rounded-lg p-6 max-w-md w-full ${
            isLight ? 'bg-white' : 'bg-gray-800'
          }`}>
            <h3 className={`text-lg font-semibold mb-4 ${
              isLight ? 'text-gray-900' : 'text-gray-100'
            }`}>
              Confirm Delete
            </h3>
            <p className={`mb-6 ${
              isLight ? 'text-gray-600' : 'text-gray-300'
            }`}>
              Are you sure you want to delete the project lead "{projectToDelete.projectName}"? This action cannot be undone.
            </p>
            <div className="flex gap-3 justify-end">
              <button
                onClick={handleDeleteClose}
                className={`px-4 py-2 rounded-lg font-medium transition-colors ${
                  isLight
                    ? 'bg-gray-200 hover:bg-gray-300 text-gray-700'
                    : 'bg-gray-600 hover:bg-gray-500 text-gray-200'
                }`}
              >
                Cancel
              </button>
              <button
                onClick={handleDeleteConfirm}
                className="px-4 py-2 rounded-lg font-medium bg-red-500 hover:bg-red-600 text-white transition-colors"
              >
                Delete
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ProjectLeadPage;
