import React, { useState } from 'react';
import { useTheme } from '../../contexts/ThemeContext';
import { FaSearch, FaUserTie, FaDownload, FaCheckCircle } from 'react-icons/fa';
import * as XLSX from 'xlsx';

const ProjectLeadsStats = ({ 
  totalProjectLeads, 
  searchTerm, 
  setSearchTerm,
  projectLeadsData,
  filteredProjectLeads
}) => {
  const { isLight } = useTheme();
  const [showSuccess, setShowSuccess] = useState(false);
  const [downloading, setDownloading] = useState(false);

  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';

  // Download project leads data to Excel
  const downloadProjectLeadsExcel = async () => {
    if (!filteredProjectLeads || filteredProjectLeads.length === 0) {
      alert('No project leads data available for download');
      return;
    }

    setDownloading(true);
    
    try {
      // Transform data for Excel export
      const excelData = filteredProjectLeads.map((project) => ({
        'Project ID': project.id,
        'Project Name': project.projectName,
        'Lead ID': project.leadId || 'Not Assigned',
        'Lead Name': project.leadName || 'Not Assigned',
        'Project Type': project.type || 'Not Assigned',
        'Status': project.status || 'Not Assigned',
        'Invoice Status': project.invoiceStatus || 'Not Assigned',
        'Priority': project.priority || 'Not Assigned'
      }));

      // Create worksheet
      const ws = XLSX.utils.json_to_sheet(excelData);
      
      // Auto-size columns
      const colWidths = [];
      excelData.forEach(row => {
        Object.keys(row).forEach((key, index) => {
          const cellValue = String(row[key] || '');
          colWidths[index] = Math.max(colWidths[index] || 0, cellValue.length);
        });
      });
      
      ws['!cols'] = colWidths.map(width => ({ width: Math.min(width + 2, 50) }));

      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Project Leads');

      // Generate filename with timestamp and search info
      const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-');
      let filename = `project_leads_${timestamp}`;
      
      if (searchTerm) {
        filename += `_search_${searchTerm.replace(/[^a-zA-Z0-9]/g, '_')}`;
      }
      
      filename += '.xlsx';

      // Download the file
      XLSX.writeFile(wb, filename);
      
      console.log(`Project leads data exported successfully: ${filename}`);
      console.log(`Exported ${filteredProjectLeads.length} project leads`);
      
      // Show success notification
      setShowSuccess(true);
      setTimeout(() => setShowSuccess(false), 3000);
    } catch (error) {
      console.error('Error downloading project leads data:', error);
      alert('Error downloading project leads data. Please try again.');
    } finally {
      setDownloading(false);
    }
  };

  return (
    <>
      <div className={`${cardBgClass} rounded-xl px-4 sm:px-6 py-3 sm:py-4 transition-all duration-300`}>
        <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4 lg:gap-6 min-w-0">
          {/* Total Project Leads - Modified for mobile layout */}
          <div className="flex items-center justify-between lg:justify-start gap-3 min-w-0 flex-shrink-0 w-full lg:w-auto">
            {/* Left side - Heading and icon */}
            <div className="flex items-center gap-3 min-w-0">
              <div className="text-blue-500 text-xl sm:text-2xl">
                <FaUserTie />
              </div>
              <div className="min-w-0 text-left">
                <p className={`${textClass} text-xs sm:text-sm uppercase tracking-wide`}>Total Project Leads</p>
                <p className={`${textClass} text-xs sm:text-sm`}>Project Leads</p>
              </div>
            </div>
            
            {/* Right side - Project Leads number (mobile) */}
            <div className="lg:hidden text-right">
              <p className={`text-xl sm:text-2xl font-bold ${headingClass}`}>{totalProjectLeads}</p>
            </div>
            
            {/* Desktop view - Project Leads number below heading */}
            <div className="hidden lg:block min-w-0">
              <p className={`text-xl sm:text-2xl font-bold ${headingClass}`}>{totalProjectLeads}</p>
            </div>
          </div>
          
          {/* Search and Export */}
          <div className="flex flex-col sm:flex-row items-stretch sm:items-center gap-3 min-w-0 w-full lg:w-auto">
            {/* Search */}
            <div className="relative w-full sm:flex-1 sm:max-w-xs lg:max-w-sm">
              <FaSearch className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 text-sm" />
              
              <input
                type="text"
                placeholder="Search project lead"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className={`w-full pl-10 pr-4 py-2 rounded-full transition-all duration-300 text-left outline-none border text-sm ${
                  isLight 
                    ? 'bg-white text-gray-900 placeholder-gray-500 border-gray-300' 
                    : 'bg-gray-700 text-gray-100 placeholder-gray-400 border-gray-600'
                }`}
              />
            </div>

            {/* Clear Button */}
            {searchTerm && (
              <button
                onClick={() => setSearchTerm('')}
                className={`px-4 py-2 rounded-full text-sm font-medium transition-all duration-200 hover:scale-105 ${
                  isLight 
                    ? 'bg-amber-500 hover:bg-amber-600 text-white' 
                    : 'bg-gray-600 hover:bg-gray-500 text-gray-200'
                }`}
              >
                Clear
              </button>
            )}

            {/* Export Button - Hidden on mobile */}
            <div className="relative group flex-shrink-0 self-center hidden md:block">
              <button
                onClick={downloadProjectLeadsExcel}
                disabled={!filteredProjectLeads || filteredProjectLeads.length === 0 || downloading}
                className={`w-8 h-8 rounded-full flex items-center justify-center transition-all duration-300 hover:scale-110 disabled:opacity-50 disabled:cursor-not-allowed ${
                  isLight
                    ? 'bg-green-500 hover:bg-green-600 text-white'
                    : 'bg-green-600 hover:bg-green-700 text-white'
                }`}
                title={downloading ? "Downloading..." : "Download Excel File"}
              >
                {downloading ? (
                  <div className="w-3 h-3 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                ) : (
                  <FaDownload className="text-xs" />
                )}
              </button>
              
              {/* Responsive Tooltip */}
              <div className={`absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-2 rounded-lg text-xs font-medium opacity-0 group-hover:opacity-100 transition-all duration-300 pointer-events-none z-30 ${
                isLight
                  ? 'bg-gray-900 text-white shadow-xl'
                  : 'bg-white text-gray-900 shadow-xl border border-gray-300'
              } whitespace-nowrap`}>
                {downloading ? "Downloading..." : "Download Excel"}
                {/* Tooltip Arrow */}
                <div className={`absolute top-full left-1/2 transform -translate-x-1/2 w-0 h-0 border-l-4 border-r-4 border-t-4 border-transparent ${
                  isLight
                    ? 'border-t-gray-900'
                    : 'border-t-white'
                }`}></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* Success Notification */}
      {showSuccess && (
        <div className={`fixed top-20 right-4 px-4 py-2 rounded-lg text-sm font-medium transition-all duration-300 z-40 ${
          isLight
            ? "bg-green-100 text-green-800 border border-green-200"
            : "bg-green-900/20 text-green-300 border border-green-700"
        }`}>
          <div className="flex items-center gap-2">
            <FaCheckCircle className="text-green-500" />
            <span>Download successful!</span>
          </div>
        </div>
      )}
    </>
  );
};

export default ProjectLeadsStats; 