import React from 'react';
import { useTheme } from '../../contexts/ThemeContext';
import { FaEye, FaUserTie, FaProjectDiagram, FaDownload } from 'react-icons/fa';
import PerformanceBadge from './PerformanceBadge';

const ProjectLeadCard = ({ projectLead, onView }) => {
  const { isLight } = useTheme();

  const cardBgClass = isLight 
    ? 'bg-white border border-yellow-200 shadow-md hover:shadow-lg active:shadow-md' 
    : 'bg-gradient-to-br from-gray-800 to-slate-800 border border-gray-700 shadow-lg hover:shadow-xl active:shadow-lg';
  
  const headingClass = isLight 
    ? 'text-amber-800' 
    : 'text-gray-100';
  
  const textClass = isLight 
    ? 'text-amber-700' 
    : 'text-gray-300';

  const handleView = () => {
    if (onView) onView(projectLead);
  };

  // Download project lead data as CSV
  const downloadProjectLeadData = () => {
    try {
      // Prepare CSV data
      const csvData = [
        ['Project ID', 'Project Name', 'Lead ID', 'Lead Name', 'Type', 'Status', 'Invoice Status', 'Priority'],
        [
          projectLead.id || '',
          projectLead.projectName || '',
          projectLead.leadId || '',
          projectLead.leadName || 'Not Assigned',
          projectLead.type || 'Not Assigned',
          projectLead.status || 'Not Assigned',
          projectLead.invoiceStatus || 'Not Assigned',
          projectLead.priority || 'Not Assigned'
        ]
      ];

      // 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 = `project_lead_${projectLead.id || 'data'}_${projectLead.projectName || '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 = [
          ['Project ID', 'Project Name', 'Lead ID', 'Lead Name', 'Type', 'Status', 'Invoice Status', 'Priority'],
          [
            projectLead.id || '',
            projectLead.projectName || '',
            projectLead.leadId || '',
            projectLead.leadName || 'Not Assigned',
            projectLead.type || 'Not Assigned',
            projectLead.status || 'Not Assigned',
            projectLead.invoiceStatus || 'Not Assigned',
            projectLead.priority || 'Not Assigned'
          ]
        ];
        
        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.');
      }
    }
  };

  return (
    <div
      className={`${cardBgClass} rounded-xl p-4 transition-all duration-200 ${
        isLight ? 'shadow-md hover:shadow-lg' : 'shadow-lg hover:shadow-xl'
      }`}
    >
      {/* Header Section with Lead Name */}
      <div className="mb-3">
        <div className="flex items-center gap-2 mb-2">
          <FaUserTie className={`text-lg ${isLight ? 'text-amber-600' : 'text-gray-400'}`} />
          <div className="flex-1 min-w-0">
          <h3 className={`font-bold text-base leading-tight ${
            isLight ? 'text-amber-800' : 'text-gray-100'
          }`} title={projectLead.leadName || 'Not Assigned'}>
            {projectLead.leadName || 'Not Assigned'}
          </h3>
          <div className="flex justify-between items-center">
          <span className={`text-xs font-mono ${
            isLight ? 'text-amber-600' : 'text-gray-300'
          }`}>
            Lead ID: {projectLead.leadId || 'N/A'}
          </span>
        </div>
          </div>
        </div>
      </div>

      {/* Project Information - Compact Layout */}
      <div className="space-y-2 mb-3">
        {/* Project Name */}
        <div className="flex items-center gap-2 mb-2">
          <FaProjectDiagram className={`text-lg ${isLight ? 'text-amber-600' : 'text-gray-400'} flex-shrink-0`} />
          <div className="flex-1 min-w-0">
            <h4 className={`font-medium text-sm truncate ${
              isLight ? 'text-amber-800' : 'text-gray-100'
            }`} title={projectLead.projectName}>
              {projectLead.projectName}
            </h4>
            <p className={`text-xs font-mono ${
              isLight ? 'text-amber-600' : 'text-gray-300'
            }`}>
              Project ID: {projectLead.id}
            </p>
          </div>
        </div>

        {/* Type */}
        <div className="flex justify-between items-center">
          <span className={`text-xs font-medium ${textClass}`}>Type</span>
          <span className={`text-xs px-2 py-1 rounded font-medium ${
            isLight 
              ? 'bg-blue-100 text-blue-800' 
              : 'bg-blue-800 text-blue-200'
          }`}>
            {projectLead.type || 'Not Assigned'}
          </span>
        </div>

        {/* Status */}
        <div className="flex justify-between items-center">
          <span className={`text-xs font-medium ${textClass}`}>Status</span>
          <span className={`text-xs px-2 py-1 rounded font-medium ${
            projectLead.status === 'Completed' 
              ? (isLight ? 'bg-green-100 text-green-800' : 'bg-green-800 text-green-200')
              : projectLead.status === 'Ongoing'
                ? (isLight ? 'bg-blue-100 text-blue-800' : 'bg-blue-800 text-blue-200')
                : projectLead.status === 'PO Received'
                  ? (isLight ? 'bg-yellow-100 text-yellow-800' : 'bg-yellow-800 text-yellow-200')
                  : projectLead.status === 'Opened'
                    ? (isLight ? 'bg-purple-100 text-purple-800' : 'bg-purple-800 text-purple-200')
                    : (isLight ? 'bg-gray-100 text-gray-800' : 'bg-gray-700 text-gray-200')
          }`}>
            {projectLead.status || 'Not Assigned'}
          </span>
        </div>

        {/* Invoice Status */}
        <div className="flex justify-between items-center">
          <span className={`text-xs font-medium ${textClass}`}>Invoice Status</span>
          <span className={`text-xs px-2 py-1 rounded font-medium ${
            projectLead.invoiceStatus === 'Submitted' 
              ? (isLight ? 'bg-green-100 text-green-800' : 'bg-green-800 text-green-200')
              : projectLead.invoiceStatus === 'Pending'
                ? (isLight ? 'bg-yellow-100 text-yellow-800' : 'bg-yellow-800 text-yellow-200')
                : projectLead.invoiceStatus === 'Not Submitted'
                  ? (isLight ? 'bg-red-100 text-red-800' : 'bg-red-800 text-red-200')
                  : (isLight ? 'bg-gray-100 text-gray-800' : 'bg-gray-700 text-gray-200')
          }`}>
            {projectLead.invoiceStatus || 'Not Assigned'}
          </span>
        </div>

        {/* Priority */}
        <div className="flex justify-between items-center">
          <span className={`text-xs font-medium ${textClass}`}>Priority</span>
          <PerformanceBadge performance={projectLead.priority} />
        </div>
      </div>

      {/* Action Button */}
      <div className="flex">
        {/* View Details Button */}
        <button 
          className={`w-full px-3 py-2 rounded-lg transition-all duration-200 active:scale-95 sm:hover:scale-105 flex items-center justify-center gap-2 text-xs font-medium touch-manipulation ${
            isLight 
              ? 'bg-amber-500 hover:bg-amber-600 active:bg-amber-700 text-white shadow-sm' 
              : 'bg-blue-600 hover:bg-blue-700 active:bg-blue-800 text-white shadow-md'
          }`}
          onClick={handleView}
          title="View Details"
        >
          <FaEye size={12} className="flex-shrink-0" />
          <span>View Details</span>
        </button>
      </div>

      {/* Floating Download Button - Sticky Bottom Right (Mobile Only) */}
      <button
        onClick={downloadProjectLeadData}
        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 Project Lead Data"
      >
        <FaDownload size={16} className="flex-shrink-0" />
      </button>
    </div>
  );
};

export default ProjectLeadCard;
