import React, { useState } from 'react';
import { useTheme } from '../../contexts/ThemeContext';
import { FaUsers, FaEdit, FaTrash, FaChevronLeft, FaChevronRight, FaTimes } from 'react-icons/fa';
import { buildApiUrl, API_ENDPOINTS } from '../../utils/config';

const EmployeesTable = ({
  filteredEmployees,
  currentEmployees,
  currentPage,
  totalPages,
  startIndex,
  endIndex,
  goToPrevious,
  goToNext,
  searchTerm,
  setSearchTerm,
  onEditEmployee,
  onDeleteEmployee,
  projects = []
}) => {
  const { isLight } = useTheme();
  const [projectPopupOpen, setProjectPopupOpen] = useState(false);
  const [selectedProjectData, setSelectedProjectData] = useState(null);
  const [contributions, setContributions] = useState({});
  const [loadingContributions, setLoadingContributions] = useState(false);

  // Helper function to format project names for display
  const formatProjectNames = (projectNames) => {
    if (!projectNames || projectNames === 'no_projects') {
      return 'No Projects';
    }
    return projectNames;
  };

  // Helper function to parse project names into an array
  const parseProjectNames = (projectNames) => {
    if (!projectNames || projectNames === 'no_projects') {
      return [];
    }
    return projectNames.split(', ').filter(name => name.trim() !== '');
  };

  // Fetch contribution data for all projects
  const fetchContributions = async (employeeId, projectNames) => {
    if (!employeeId || !projectNames || projectNames.length === 0) {
      setContributions({});
      return;
    }

    setLoadingContributions(true);
    const contributionsMap = {};

    try {
      // Create promises for all projects
      const contributionPromises = projectNames.map(async (projectName) => {
        // Find project ID from project name
        const project = projects.find(p => p.project_name === projectName);
        if (!project || !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) {
              // Get the most recent contribution
              const contribution = data.data[0];
              contributionsMap[projectName] = contribution.contribution_percentage || 0;
            } else {
              contributionsMap[projectName] = 0;
            }
          } else {
            contributionsMap[projectName] = 0;
          }
        } catch (err) {
          console.error(`Error fetching contribution for project ${projectName}:`, err);
          contributionsMap[projectName] = 0;
        }
      });

      await Promise.all(contributionPromises);
      setContributions(contributionsMap);
    } catch (err) {
      console.error("Error fetching contributions:", err);
      setContributions({});
    } finally {
      setLoadingContributions(false);
    }
  };

  // Handle project name click
  const handleProjectNameClick = async (employee) => {
    const projectNames = parseProjectNames(employee.project_names);
    setSelectedProjectData({
      employeeName: employee.employee_name,
      employeeId: employee.employee_id,
      projectNames: projectNames
    });
    setProjectPopupOpen(true);
    // Fetch contributions when popup opens
    await fetchContributions(employee.employee_id, projectNames);
  };

  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 textClass = isLight 
    ? 'text-amber-700' 
    : 'text-gray-300';

  const buttonClass = isLight 
    ? 'bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white' 
    : 'bg-gradient-to-r from-gray-600 to-slate-600 hover:from-gray-500 hover:to-slate-500 text-white';

  return (
    <div className={`hidden md:block ${cardBgClass} rounded-xl overflow-hidden transition-all duration-300 ${
      isLight ? 'shadow-md hover:shadow-lg' : 'shadow-xl hover:shadow-2xl'
    }`}>
      <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: '12%' }}>Employee ID</th>
              <th className={`px-3 py-2 text-center font-semibold text-xs ${
                isLight ? 'text-amber-900' : 'text-gray-100'
              }`} style={{ width: '18%' }}>Employee Name</th>
              <th className={`px-3 py-2 text-center font-semibold text-xs ${
                isLight ? 'text-amber-900' : 'text-gray-100'
              }`} style={{ width: '15%' }}>Division</th>
              <th className={`px-3 py-2 text-center font-semibold text-xs ${
                isLight ? 'text-amber-900' : 'text-gray-100'
              }`} style={{ width: '12%' }}>Role</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: '13%' }}>Remarks</th>
              <th className={`px-3 py-2 text-center font-semibold text-xs ${
                isLight ? 'text-amber-900' : 'text-gray-100'
              }`} style={{ width: '10%' }}>Actions</th>
            </tr>
          </thead>
          <tbody className={isLight ? 'bg-white' : 'bg-gray-800'}>
            {filteredEmployees.length === 0 ? (
              <tr>
                <td colSpan="7" className={`p-12 text-center ${
                  isLight ? 'bg-white' : 'bg-gray-800'
                }`}>
                  <div className="flex flex-col items-center gap-3">
                    <FaUsers className={`text-4xl ${isLight ? 'text-gray-300' : 'text-gray-500'}`} />
                    <div className={`${textClass} text-lg`}>
                      {searchTerm ? 'No employees found matching your search.' : 'No employees found.'}
                    </div>
                    {searchTerm && (
                      <button 
                        onClick={() => setSearchTerm('')}
                        className={`px-4 py-2 ${buttonClass} rounded-lg text-sm transition-all duration-200 hover:scale-105`}
                      >
                        Clear Search
                      </button>
                    )}
                  </div>
                </td>
              </tr>
            ) : (
              currentEmployees.map((employee, index) => (
                <tr 
                  key={employee.employee_id} 
                  className={`border-b transition-colors duration-200 ${
                    isLight 
                      ? 'border-gray-200 hover:bg-yellow-50' 
                      : 'border-gray-600 hover:bg-gray-700'
                  } ${
                    index % 2 === 0 
                      ? (isLight ? 'bg-gray-50' : 'bg-gray-750') 
                      : (isLight ? 'bg-white' : 'bg-gray-800')
                  }`}
                >
                  <td className="px-2 py-2 text-center">
                    <div className={`font-mono text-xs truncate ${
                      isLight ? 'text-amber-800' : 'text-gray-200'
                    }`}>
                      {employee.employee_id}
                    </div>
                  </td>
                  <td className="px-2 py-2 text-center">
                    <div className={`text-xs truncate ${
                      isLight ? 'text-amber-700' : 'text-gray-200'
                    }`} title={employee.employee_name}>
                      {employee.employee_name}
                    </div>
                  </td>
                  <td className="px-2 py-2 text-center">
                    <div className={`text-xs truncate ${
                      isLight ? 'text-gray-800' : 'text-gray-200'
                    }`} title={employee.division_name || 'Not Assigned'}>
                      {employee.division_name || 'Not Assigned'}
                    </div>
                  </td>
                  <td className="px-2 py-2 text-center">
                    <div className={`text-xs truncate ${
                      isLight ? 'text-gray-800' : 'text-gray-200'
                    }`} title={employee.role_name || 'Not Assigned'}>
                      {employee.role_name || 'Not Assigned'}
                    </div>
                  </td>
                  <td className="px-2 py-2 text-center">
                    <div 
                      className={`text-xs truncate cursor-pointer hover:underline ${
                        isLight ? 'text-blue-700' : 'text-blue-400'
                      }`} 
                      title={`Click to view projects for ${employee.employee_name}`}
                      onClick={() => handleProjectNameClick(employee)}
                    >
                      {formatProjectNames(employee.project_names)}
                    </div>
                  </td>
                  <td className="px-2 py-2 text-center">
                    <div className={`text-xs truncate ${
                      isLight ? 'text-gray-600' : 'text-gray-300'
                    }`} title={employee.remarks}>
                      {employee.remarks || 'No remarks'}
                    </div>
                  </td>
                  <td className="px-2 py-2 text-center">
                    <div className="flex gap-1 justify-center">
                      {/* Only show edit/delete buttons if employee is not a director */}
                      {employee.role_name !== "Director" && employee.division_name !== "Directors" && (
                        <>
                          <button 
                            onClick={() => onEditEmployee(employee)}
                            className={`p-1.5 rounded-md transition-all duration-200 hover:scale-110 ${
                              isLight 
                                ? 'text-blue-600 hover:bg-blue-100 hover:shadow-sm' 
                                : 'text-blue-400 hover:bg-blue-900 hover:shadow-sm'
                            }`}
                            title="Edit Employee"
                          >
                            <FaEdit className="text-xs" />
                          </button>
                          <button 
                            onClick={() => onDeleteEmployee(employee)}
                            className={`p-1.5 rounded-md transition-all duration-200 hover:scale-110 ${
                              isLight 
                                ? 'text-red-600 hover:bg-red-100 hover:shadow-sm' 
                                : 'text-red-400 hover:bg-red-900 hover:shadow-sm'
                            }`}
                            title="Delete Employee"
                          >
                            <FaTrash className="text-xs" />
                          </button>
                        </>
                      )}
                      {/* Show message for directors */}
                      {(employee.role_name === "Director" || employee.division_name === "Directors") && (
                        <span className={`text-xs px-2 py-1 rounded ${
                          isLight 
                            ? 'text-gray-600' 
                            : 'text-gray-300'
                        }`}>
                          -
                        </span>
                      )}
                    </div>
                  </td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>

      {/* Desktop Pagination */}
      {totalPages > 1 && (
        <div className={`mt-0 px-3 py-2 border-t overflow-hidden ${
          isLight 
            ? 'bg-gray-50 border-gray-200' 
            : 'bg-gray-700 border-gray-600'
        }`}>
          <div className="flex justify-between items-center gap-2 min-w-0">
            {/* Page Info */}
            <div className={`text-xs flex-shrink-0 ${
              isLight ? 'text-gray-600' : 'text-gray-300'
            }`}>
              {startIndex + 1}-{Math.min(endIndex, filteredEmployees.length)} of {filteredEmployees.length}
            </div>

            {/* Pagination Controls */}
            <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>
      )}

      {/* Project Names Popup Modal */}
      {projectPopupOpen && (
        <div className="fixed inset-0 flex items-center justify-center z-50 p-4">
          <div className={`relative max-w-md w-full mx-4 rounded-lg shadow-xl max-h-[90vh] flex flex-col ${
            isLight ? 'bg-white' : 'bg-gradient-to-br from-gray-800 to-slate-800'
          }`}>
            {/* Header */}
            <div className={`flex items-center justify-between p-4 border-b flex-shrink-0 ${
              isLight ? 'border-amber-200' : 'border-gray-600'
            }`}>
              <div className="flex items-center gap-3">
                <div className={`p-2 rounded-full ${
                  isLight ? 'bg-gradient-to-r from-yellow-200 to-amber-200' : 'bg-gradient-to-r from-gray-600 to-slate-600'
                }`}>
                  <svg
                    className={`w-5 h-5 ${
                      isLight ? 'text-amber-700' : 'text-gray-200'
                    }`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth="2"
                      d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"
                    />
                  </svg>
                </div>
                <div>
                  <h3 className={`text-lg font-semibold ${
                    isLight ? 'text-amber-800' : 'text-gray-100'
                  }`}>
                    Projects
                  </h3>
                  <p className={`text-sm ${
                    isLight ? 'text-amber-600' : 'text-gray-300'
                  }`}>
                    {selectedProjectData?.employeeName}
                  </p>
                </div>
              </div>
              <button
                onClick={() => {
                  setProjectPopupOpen(false);
                  setContributions({});
                  setLoadingContributions(false);
                }}
                className={`p-1 rounded-full hover:bg-amber-100 transition-colors ${
                  isLight ? 'text-amber-500 hover:text-amber-700' : 'text-gray-400 hover:text-gray-200 hover:bg-gray-700'
                }`}
              >
                <FaTimes className="w-4 h-4" />
              </button>
            </div>

            {/* Content */}
            <div className={`p-4 flex-1 overflow-y-auto ${
              selectedProjectData?.projectNames.length > 5 ? 'max-h-[60vh]' : ''
            }`}>
              {selectedProjectData?.projectNames.length > 0 ? (
                <div className="space-y-3">
                  {loadingContributions ? (
                    <div className={`text-center py-4 ${isLight ? 'text-amber-600' : 'text-gray-400'}`}>
                      <div className="inline-block animate-spin rounded-full h-6 w-6 border-b-2 border-current"></div>
                      <p className="mt-2 text-sm">Loading contributions...</p>
                    </div>
                  ) : (
                    selectedProjectData.projectNames.map((projectName, index) => {
                      const contribution = contributions[projectName] || 0;
                      return (
                        <div
                          key={index}
                          className={`p-3 rounded-lg border ${
                            isLight 
                              ? 'bg-gradient-to-r from-yellow-50 to-amber-50 border-amber-200 text-amber-800' 
                              : 'bg-gradient-to-r from-gray-700 to-slate-700 border-gray-600 text-gray-200'
                          }`}
                        >
                          {/* Project Name */}
                          <div className="flex items-center gap-2 mb-2">
                            <div className={`w-2 h-2 rounded-full flex-shrink-0 ${
                              isLight ? 'bg-amber-500' : 'bg-blue-400'
                            }`}></div>
                            <span className="font-medium truncate">{projectName}</span>
                          </div>
                          {/* Contribution Progress Bar */}
                          <div className="flex items-center gap-2 mb-1">
                            <span className={`text-xs whitespace-nowrap ${
                              isLight ? 'text-amber-600' : 'text-gray-400'
                            }`}>
                              Contribution:
                            </span>
                            <div className={`w-24 h-2.5 rounded-full overflow-hidden ${
                              isLight ? 'bg-amber-100' : 'bg-gray-600'
                            }`}>
                              <div
                                className={`h-full transition-all duration-500 ${
                                  contribution >= 75
                                    ? isLight ? 'bg-green-500' : 'bg-green-400'
                                    : contribution >= 50
                                    ? isLight ? 'bg-yellow-500' : 'bg-yellow-400'
                                    : contribution >= 25
                                    ? isLight ? 'bg-orange-500' : 'bg-orange-400'
                                    : isLight ? 'bg-red-500' : 'bg-red-400'
                                }`}
                                style={{ width: `${contribution}%` }}
                              ></div>
                            </div>
                          </div>
                          {/* Percentage */}
                          <div className="flex justify-start">
                            <span className={`text-sm font-semibold ${
                              isLight ? 'text-amber-700' : 'text-gray-300'
                            }`}>
                              {contribution}%
                            </span>
                          </div>
                        </div>
                      );
                    })
                  )}
                </div>
              ) : (
                <div className={`text-center py-8 ${
                  isLight ? 'text-amber-500' : 'text-gray-400'
                }`}>
                  <svg
                    className={`w-12 h-12 mx-auto mb-3 ${
                      isLight ? 'text-amber-300' : 'text-gray-500'
                    }`}
                    fill="none"
                    stroke="currentColor"
                    viewBox="0 0 24 24"
                  >
                    <path
                      strokeLinecap="round"
                      strokeLinejoin="round"
                      strokeWidth="2"
                      d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"
                    />
                  </svg>
                  <p className="text-lg font-medium">No Projects Assigned</p>
                  <p className="text-sm">This employee is not currently assigned to any projects.</p>
                </div>
              )}
            </div>

            {/* Footer */}
            <div className={`flex justify-end gap-3 p-4 border-t flex-shrink-0 ${
              isLight ? 'border-amber-200' : 'border-gray-600'
            }`}>
              <button
                onClick={() => {
                  setProjectPopupOpen(false);
                  setContributions({});
                  setLoadingContributions(false);
                }}
                className={`px-4 py-2 rounded-md transition-colors ${
                  isLight 
                    ? 'bg-gradient-to-r from-yellow-500 to-amber-500 hover:from-yellow-600 hover:to-amber-600 text-white' 
                    : 'bg-gradient-to-r from-gray-600 to-slate-600 hover:from-gray-500 hover:to-slate-500 text-white'
                }`}
              >
                Close
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default EmployeesTable; 