import React, { useState } from "react";
import { useTheme } from "../../contexts/ThemeContext";
import {
  FaChevronLeft,
  FaChevronRight,
  FaProjectDiagram,
} from "react-icons/fa";
import LeadActions from "./LeadActions";
import ProjectDetailsModal from "../Projects/ProjectDetailsModal";
import EditProjectLeadModal from "./EditProjectLeadModal";
import { buildApiUrl, API_ENDPOINTS } from "../../utils/config";

const ProjectLeadsTable = ({
  projectLeadsData,
  currentProjectLeads,
  currentPage,
  totalPages,
  goToPrevious,
  goToNext,
  onRefresh,
}) => {
  const { isLight } = useTheme();
  const [selectedProject, setSelectedProject] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  const [selectedProjectLead, setSelectedProjectLead] = useState(null);

  const cardBgClass = isLight
    ? "bg-white border border-yellow-200 shadow-md hover:shadow-lg"
    : "bg-gradient-to-br from-gray-800 to-slate-800 border border-gray-700 shadow-lg hover:shadow-xl";

  const headingClass = isLight ? "text-amber-800" : "text-gray-100";

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

  // Transform project leads data to match ProjectDetailsModal expected format
  const transformProjectData = (projectLead) => {
    if (!projectLead) {
      console.warn("No project data provided to transformProjectData");
      return null;
    }
    
    try {
      return {
        project_id: projectLead.id || projectLead.project_id,
        project_name: projectLead.projectName || projectLead.project_name,
        status_name: projectLead.status || projectLead.status_name,
        type_name: projectLead.type || projectLead.type_name,
        priority_level_name: projectLead.priority || projectLead.priority_level_name,
        invoice_status_name: projectLead.invoiceStatus || projectLead.invoice_status_name,
        // Add other required fields with default values
        division_name: projectLead.division || projectLead.division_name || "Not Assigned",
        project_start_date: projectLead.startDate || projectLead.project_start_date || null,
        deadline: projectLead.deadline || null,
        estimated_hours: projectLead.estimatedHours || projectLead.estimated_hours || 0,
        actual_hours: projectLead.actualHours || projectLead.actual_hours || 0,
        percent_completed: projectLead.percentCompleted || projectLead.percent_completed || 0,
        project_lead_name: projectLead.leadName || projectLead.project_lead_name || "Not Assigned",
        remarks: projectLead.remarks || "No remarks available",
        po_status_name: projectLead.po_status_name || projectLead.po_status || "Not Set"
      };
    } catch (error) {
      console.error("Error transforming project data:", error);
      return null;
    }
  };

  const handleView = (project) => {
    try {
      if (!project) {
        console.error("No project data provided to handleView");
        return;
      }
      
      console.log("Original project data:", project);
      const transformedProject = transformProjectData(project);
      if (!transformedProject) {
        console.error("Failed to transform project data");
        return;
      }
      
      console.log("Transformed project data:", transformedProject);
      console.log("PO Status in transformed data:", transformedProject.po_status_name);
      
      setSelectedProject(transformedProject);
      setIsModalOpen(true);
    } catch (error) {
      console.error("Error opening modal:", error);
    }
  };

  const handleEdit = (project) => {
    try {
      console.log("Edit project:", project);
      setSelectedProjectLead(project);
      setIsEditModalOpen(true);
      setIsModalOpen(false);
    } catch (error) {
      console.error("Error editing project:", error);
    }
  };

  const handleEditSuccess = () => {
    setIsEditModalOpen(false);
    setSelectedProjectLead(null);
    // Refresh the data by calling the parent's refresh function
    if (onRefresh) {
      onRefresh();
    }
  };

  const handleEditClose = () => {
    setIsEditModalOpen(false);
    setSelectedProjectLead(null);
  };

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

  // Handle project form download
  const handleDownloadProjectForm = async (projectName) => {
    try {
      if (!projectName) {
        console.error("No project name provided for download");
        alert("Project name is required for download");
        return;
      }

      console.log(`Downloading project form for: ${projectName}`);

      // Find the project in the current data to get the project ID
      const project = projectLeadsData.find(p => p.projectName === projectName);
      
      if (!project) {
        console.error("Project not found in current data");
        alert("Project not found. Please refresh and try again.");
        return;
      }

      const projectId = project.id;
      console.log(`Project ID for download: ${projectId}`);
      console.log("Available projects in projectLeadsData:", projectLeadsData.map(p => ({ id: p.id, name: p.projectName })));

      // Build the download URL using the download-project-form endpoint
      const downloadUrl = `${buildApiUrl(API_ENDPOINTS.KICKOFF_FORM)}/download-project-form/${projectId}`;
      
      console.log("Downloading from URL:", downloadUrl);

      // Try to download the file
      const response = await fetch(downloadUrl);
      
      if (!response.ok) {
        if (response.status === 404) {
          alert("No kickoff form available for this project.");
          return;
        } else {
          throw new Error(`Download failed with status: ${response.status}`);
        }
      }

      // Get the file blob
      const blob = await response.blob();
      
      // Create a temporary link element to trigger the download
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = `kickoff_form_${projectName}.docx`;
      
      // Append to body, click, and remove
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      // Clean up the object URL
      URL.revokeObjectURL(link.href);
      
      console.log(`Download completed for project: ${projectName} (ID: ${projectId})`);
    } catch (error) {
      console.error("Error downloading project form:", error);
      
      // Provide more specific error messages
      if (error.message.includes('404')) {
        alert("No kickoff form available for this project.");
      } else if (error.message.includes('500')) {
        alert("Server error occurred. Please try again later.");
      } else {
        alert("Error downloading project form. Please try again.");
      }
    }
  };

  return (
    <div className="hidden lg:block">
      <div className={`${cardBgClass} rounded-xl overflow-hidden transition-all duration-300`}>
        <div className="overflow-hidden">
          <table className="w-full table-fixed">
            <thead className={`${
              isLight 
                ? 'bg-gradient-to-r from-yellow-200 to-amber-200 text-amber-900' 
                : 'bg-gradient-to-r from-gray-600 to-slate-600 text-gray-100'
            }`}>
              <tr>
                <th className={`px-3 py-2 text-center font-semibold text-xs ${
                  isLight ? 'text-amber-900' : 'text-gray-100'
                }`} style={{ width: '20%' }}>Project Lead</th>
                <th className={`px-3 py-2 text-center font-semibold text-xs ${
                  isLight ? 'text-amber-900' : 'text-gray-100'
                }`} style={{ width: '20%' }}>Project Name</th>
                <th className={`px-3 py-2 text-center font-semibold text-xs ${
                  isLight ? 'text-amber-900' : 'text-gray-100'
                }`} style={{ width: '12%' }}>Type</th>
                <th className={`px-3 py-2 text-center font-semibold text-xs ${
                  isLight ? 'text-amber-900' : 'text-gray-100'
                }`} style={{ width: '12%' }}>Status</th>
                <th className={`px-3 py-2 text-center font-semibold text-xs ${
                  isLight ? 'text-amber-900' : 'text-gray-100'
                }`} style={{ width: '12%' }}>Invoice Status</th>
                <th className={`px-3 py-2 text-center font-semibold text-xs ${
                  isLight ? 'text-amber-900' : 'text-gray-100'
                }`} style={{ width: '12%' }}>Priority</th>
                <th className={`px-3 py-2 text-center font-semibold text-xs ${
                  isLight ? 'text-amber-900' : 'text-gray-100'
                }`} style={{ width: '12%' }}>Actions</th>
              </tr>
            </thead>
            <tbody className={isLight ? 'bg-white' : 'bg-gray-800'}>
              {currentProjectLeads.map((project, index) => (
                <tr
                  key={project.id || index}
                  className={`${
                    isLight
                      ? "bg-white hover:bg-yellow-50"
                      : "bg-gray-800 hover:bg-gray-700"
                  } transition-colors duration-150`}
                >
                  <td className="px-3 py-2 whitespace-nowrap text-center">
                    <div className="flex flex-col items-center">
                      <div className={`text-sm font-medium ${headingClass}`}>
                        {project.leadName || "Not Assigned"}
                      </div>
                      <div className={`text-sm ${textClass}`}>
                        ID: {project.leadId || "N/A"}
                      </div>
                    </div>
                  </td>
                  <td className="px-3 py-2 whitespace-nowrap text-center">
                    <div className={`text-sm font-medium ${headingClass}`}>
                      {project.projectName}
                    </div>
                    <div className={`text-sm ${textClass}`}>
                      ID: {project.id}
                    </div>
                  </td>
                  <td className="px-3 py-2 whitespace-nowrap text-center">
                    <span
                      className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                        isLight
                          ? "bg-blue-100 text-blue-800"
                          : "bg-blue-900 text-blue-200"
                      }`}
                    >
                      {project.type || "N/A"}
                    </span>
                  </td>
                  <td className="px-3 py-2 whitespace-nowrap text-center">
                    <span
                      className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                        project.status === "Completed"
                          ? "bg-green-100 text-green-800"
                          : project.status === "Ongoing"
                          ? "bg-blue-100 text-blue-800"
                          : project.status === "PO Received"
                          ? "bg-yellow-100 text-yellow-800"
                          : project.status === "Opened"
                          ? "bg-purple-100 text-purple-800"
                          : "bg-gray-100 text-gray-800"
                      }`}
                    >
                      {project.status || "N/A"}
                    </span>
                  </td>
                  <td className="px-3 py-2 whitespace-nowrap text-center">
                    <span
                      className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                        isLight
                          ? "bg-green-100 text-green-800"
                          : "bg-green-900 text-green-200"
                      }`}
                    >
                      {project.invoiceStatus || "N/A"}
                    </span>
                  </td>
                  <td className="px-3 py-2 whitespace-nowrap text-center">
                    <span
                      className={`inline-flex px-2 py-1 text-xs font-semibold rounded-full ${
                        isLight
                          ? "bg-purple-100 text-purple-800"
                          : "bg-purple-900 text-purple-200"
                      }`}
                    >
                      {project.priority || "N/A"}
                    </span>
                  </td>
                  <td className="px-3 py-2 whitespace-nowrap text-center">
                    <LeadActions
                      project={project}
                      onView={handleView}
                      isLight={isLight}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Pagination */}
        <div className={`px-6 py-3 border-t ${isLight ? "border-yellow-200" : "border-gray-700"}`}>
          <div className="flex flex-col sm:flex-row justify-between items-center gap-3">
            <div className="flex items-center">
              <span className={`text-sm ${textClass}`}>
                Showing {currentProjectLeads.length > 0 ? (currentPage - 1) * 10 + 1 : 0} to {Math.min(currentPage * 10, projectLeadsData.length)} of{" "}
                {projectLeadsData.length} results
              </span>
            </div>
            <div className="flex items-center justify-center gap-2">
              {/* Previous Button */}
              <button
                onClick={goToPrevious}
                disabled={currentPage === 1}
                className={`flex items-center justify-center gap-1 px-3 py-2 rounded-lg text-sm ${
                  currentPage === 1
                    ? (isLight ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-gray-600 text-gray-500 cursor-not-allowed')
                    : (isLight ? 'bg-white hover:bg-gray-100 text-gray-700 shadow-sm' : 'bg-gray-600 hover:bg-gray-500 text-gray-200')
                }`}
              >
                <FaChevronLeft className="text-xs flex-shrink-0" />
                <span>Prev</span>
              </button>

              {/* Current Page */}
              <div className={`px-3 py-2 rounded-lg font-medium text-sm ${
                isLight ? 'bg-amber-500 text-white' : 'bg-gray-300 text-gray-900'
              }`}>
                {currentPage}
              </div>

              {/* Next Button */}
              <button
                onClick={goToNext}
                disabled={currentPage === totalPages}
                className={`flex items-center justify-center gap-1 px-3 py-2 rounded-lg text-sm ${
                  currentPage === totalPages
                    ? (isLight ? 'bg-gray-100 text-gray-400 cursor-not-allowed' : 'bg-gray-600 text-gray-500 cursor-not-allowed')
                    : (isLight ? 'bg-white hover:bg-gray-100 text-gray-700 shadow-sm' : 'bg-gray-600 hover:bg-gray-500 text-gray-200')
                }`}
              >
                <span>Next</span>
                <FaChevronRight className="text-xs flex-shrink-0" />
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* Project Details Modal */}
      <ProjectDetailsModal
        isOpen={isModalOpen}
        onClose={handleCloseModal}
        project={selectedProject}
        onEdit={handleEdit}
        onDelete={() => {
          // Handle delete if needed
          console.log("Delete functionality not implemented for project leads");
        }}
        downloadProjectForm={handleDownloadProjectForm}
        showDeleteButton={false}
      />

      {/* Edit Project Lead Modal */}
      <EditProjectLeadModal
        isOpen={isEditModalOpen}
        onClose={handleEditClose}
        projectLead={selectedProjectLead}
        onSuccess={handleEditSuccess}
      />
    </div>
  );
};

export default ProjectLeadsTable;
