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

const EmployeeCard = ({ employee, onEdit, onDelete, onEditEmployee, onDeleteEmployee, projects = [] }) => {
  const { isLight } = useTheme();
  const [projectPopupOpen, setProjectPopupOpen] = useState(false);
  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;
  };

  // Download employee data as CSV
  const downloadEmployeeData = () => {
    try {
      // Prepare CSV data
      const csvData = [
        ['Employee ID', 'Employee Name', 'Division', 'Role', 'Projects', 'Remarks'],
        [
          employee.employee_id || '',
          employee.employee_name || '',
          employee.division_name || 'Not Assigned',
          employee.role_name || 'Not Assigned',
          employee.project_names || 'No Projects',
          employee.remarks || ''
        ]
      ];

      // Convert to CSV string with proper escaping
      const csvContent = csvData
        .map(row => 
          row.map(cell => {
            // Escape quotes and wrap in quotes if contains comma, quote, or newline
            const escaped = String(cell).replace(/"/g, '""');
            return `"${escaped}"`;
          }).join(',')
        )
        .join('\n');

      // Add BOM for Excel compatibility
      const BOM = '\uFEFF';
      const csvWithBOM = BOM + csvContent;

      // Create blob with proper MIME type
      const blob = new Blob([csvWithBOM], { 
        type: 'text/csv;charset=utf-8;' 
      });

      // Create download link
      const downloadLink = document.createElement('a');
      downloadLink.href = URL.createObjectURL(blob);
      downloadLink.download = `employee_${employee.employee_id || 'data'}_${employee.employee_name || 'export'}.csv`;
      downloadLink.style.cssText = 'position:fixed;top:-100px;left:-100px;opacity:0;pointer-events:none;';
      
      // Append to DOM and trigger download
      document.body.appendChild(downloadLink);
      downloadLink.click();
      
      // Cleanup
      setTimeout(() => {
        document.body.removeChild(downloadLink);
        URL.revokeObjectURL(downloadLink.href);
      }, 200);

      // Success feedback
      console.log('Download initiated successfully');
      
    } catch (error) {
      console.error('Download error:', error);
      // Fallback: try to open in new tab
      try {
        const csvData = [
          ['Employee ID', 'Employee Name', 'Division', 'Role', 'Projects', 'Remarks'],
          [
            employee.employee_id || '',
            employee.employee_name || '',
            employee.division_name || 'Not Assigned',
            employee.role_name || 'Not Assigned',
            employee.project_names || 'No Projects',
            employee.remarks || ''
          ]
        ];
        
        const csvContent = csvData
          .map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(','))
          .join('\n');
        
        const blob = new Blob([csvContent], { type: 'text/csv' });
        const url = URL.createObjectURL(blob);
        window.open(url, '_blank');
        
        setTimeout(() => URL.revokeObjectURL(url), 1000);
      } catch (fallbackError) {
        console.error('Fallback download also failed:', fallbackError);
        alert('Download failed. Please try again.');
      }
    }
  };

  // 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 names click
  const handleProjectNamesClick = async () => {
    const projectNames = parseProjectNames(employee.project_names);
    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';

  return (
    <div
      className={`${cardBgClass} rounded-xl p-4 sm:p-5 transition-all duration-200 relative ${
        isLight ? 'shadow-md hover:shadow-lg' : 'shadow-lg hover:shadow-xl'
      }`}
    >
      <div className="flex justify-between items-start mb-3">
        <div className="flex-1 min-w-0">
          <h3 className={`font-semibold text-lg truncate ${
            isLight ? 'text-amber-800' : 'text-gray-100'
          }`} title={employee.employee_name}>
            {employee.employee_name}
          </h3>
          <p className={`text-sm font-mono ${
            isLight ? 'text-amber-600' : 'text-gray-300'
          }`}>
            ID: {employee.employee_id}
          </p>
        </div>
        <div className="flex gap-1 flex-shrink-0 self-center relative z-20" style={{ pointerEvents: 'auto' }}>
          {/* Only show edit/delete buttons if employee is not a director */}
          {employee.role_name !== "Director" && employee.division_name !== "Directors" ? (
            <>
              <button 
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  console.log('Edit button clicked for employee:', employee);
                  try {
                    if (onEditEmployee) {
                      console.log('Calling onEditEmployee');
                      onEditEmployee(employee);
                    } else if (onEdit) {
                      console.log('Calling onEdit');
                      onEdit(employee);
                    } else {
                      console.log('No edit function available');
                    }
                  } catch (error) {
                    console.error('Error in edit button click handler:', error);
                  }
                }}
                className={`p-2 rounded-lg transition-all duration-200 cursor-pointer select-none flex items-center justify-center w-10 h-10 ${
                  isLight 
                    ? 'text-blue-600 hover:bg-blue-100 active:bg-blue-200' 
                    : 'text-blue-400 hover:bg-blue-900 active:bg-blue-800'
                }`}
                title="Edit Employee"
              >
                <FaEdit className="text-sm flex-shrink-0" />
              </button>
              <button 
                onClick={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                  console.log('Delete button clicked for employee:', employee);
                  try {
                    if (onDeleteEmployee) {
                      console.log('Calling onDeleteEmployee');
                      onDeleteEmployee(employee);
                    } else if (onDelete) {
                      console.log('Calling onDelete');
                      onDelete(employee);
                    } else {
                      console.log('No delete function available');
                    }
                  } catch (error) {
                    console.error('Error in delete button click handler:', error);
                  }
                }}
                className={`p-2 rounded-lg transition-all duration-200 cursor-pointer select-none flex items-center justify-center w-10 h-10 ${
                  isLight 
                    ? 'text-red-600 hover:bg-red-100 active:bg-red-200' 
                    : 'text-red-400 hover:bg-red-900 active:bg-red-800'
                }`}
                title="Delete Employee"
              >
                <FaTrash className="text-sm flex-shrink-0" />
              </button>
            </>
          ) : (
            /* Show protected status for directors */
            <div className={`px-3 py-2 rounded-lg text-xs font-medium ${
              isLight 
                ? 'text-amber-800' 
                : 'text-amber-300'
            }`}>
              -
            </div>
          )}
        </div>
      </div>

      <div className="grid grid-cols-1 gap-2">
        <div className="flex justify-between items-center">
          <span className={`text-sm font-medium ${textClass}`}>Division:</span>
          <span className={`text-sm px-2 py-1 rounded ${
            isLight 
              ? 'bg-blue-100 text-blue-800' 
              : 'bg-blue-800 text-blue-200'
          }`}>
            {employee.division_name || 'Not Assigned'}
          </span>
        </div>
        <div className="flex justify-between items-center">
          <span className={`text-sm font-medium ${textClass}`}>Role:</span>
          <span className={`text-sm px-2 py-1 rounded ${
            isLight 
              ? 'bg-green-100 text-green-800' 
              : 'bg-green-800 text-green-200'
          }`}>
            {employee.role_name || 'Not Assigned'}
          </span>
        </div>
        <div className="flex justify-between items-start">
          <span className={`text-sm font-medium ${textClass} flex-shrink-0`}>Projects:</span>
          <span 
            className={`text-sm px-2 py-1 rounded text-right ml-2 ${
              isLight 
                ? 'bg-purple-100 text-purple-800 cursor-pointer' 
                : 'bg-purple-800 text-purple-200 cursor-pointer'
            }`}
            onClick={handleProjectNamesClick}
          >
            {formatProjectNames(employee.project_names)}
          </span>
        </div>
        {employee.remarks && (
          <div className="mt-2">
            <span className={`text-sm font-medium ${textClass}`}>Remarks:</span>
            <p className={`text-sm mt-1 ${
              isLight ? 'text-gray-600' : 'text-gray-300'
            }`}>
              {employee.remarks}
            </p>
          </div>
        )}
      </div>

      {/* Floating Download Button - Sticky Bottom Right (Mobile Only) */}
      <button
        onClick={downloadEmployeeData}
        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 Employee Data"
      >
        <FaDownload size={16} className="flex-shrink-0" />
      </button>
      {/* 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'
                  }`}>
                    {employee.employee_name}
                  </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 ${
              parseProjectNames(employee.project_names).length > 5 ? 'max-h-[60vh]' : ''
            }`}>
              {parseProjectNames(employee.project_names).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>
                  ) : (
                    parseProjectNames(employee.project_names).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.586a1 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 EmployeeCard; 