import React, { useState, useRef, useEffect } from 'react';
import { Download, FileText, FileJson, FileSpreadsheet, File, ChevronDown } from 'lucide-react';
import { exportData, formatDataForExport, ExportFormat } from '../utils/exportUtils';
import { toast } from 'react-toastify';

type ExportRow = Record<string, unknown>;

interface ExportButtonProps<T extends ExportRow = ExportRow> {
  data: ReadonlyArray<T>;
  filename: string;
  title?: string;
  customHeaders?: Record<string, string>;
  className?: string;
  disabled?: boolean;
}

const ExportButton = <T extends ExportRow>({
  data,
  filename,
  title,
  customHeaders,
  className = '',
  disabled = false
}: ExportButtonProps<T>) => {
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isOpen]);

  const handleExport = async (format: ExportFormat) => {
    try {
      if (!data || data.length === 0) {
        toast.error('No data available to export');
        return;
      }

      const { headers, formattedData } = formatDataForExport(data, customHeaders);
      
      exportData({
        format,
        filename,
        title: title || filename,
        headers,
        data: formattedData as ReadonlyArray<T>
      });

      toast.success(`Data exported successfully as ${format.toUpperCase()}!`);
      setIsOpen(false);
    } catch (error: unknown) {
      const message = error instanceof Error ? error.message : 'Failed to export data';
      toast.error(message);
    }
  };

  const exportOptions = [
    {
      format: 'csv' as ExportFormat,
      label: 'CSV',
      icon: FileText,
      description: 'Comma-separated values',
      color: 'from-blue-500 to-blue-600'
    },
    {
      format: 'xlsx' as ExportFormat,
      label: 'Excel',
      icon: FileSpreadsheet,
      description: 'Microsoft Excel format',
      color: 'from-emerald-500 to-emerald-600'
    },
    {
      format: 'pdf' as ExportFormat,
      label: 'PDF',
      icon: File,
      description: 'Portable Document Format',
      color: 'from-rose-500 to-rose-600'
    },
    {
      format: 'json' as ExportFormat,
      label: 'JSON',
      icon: FileJson,
      description: 'JavaScript Object Notation',
      color: 'from-purple-500 to-purple-600'
    }
  ];

  return (
    <div className={`relative ${className}`} ref={dropdownRef}>
      <button
        onClick={() => !disabled && setIsOpen(!isOpen)}
        disabled={disabled || !data || data.length === 0}
        className={`
          group relative flex items-center gap-2 px-5 py-2.5
          bg-gradient-to-r from-emerald-600 via-emerald-600 to-emerald-700
          text-white rounded-xl font-semibold
          shadow-lg hover:shadow-xl
          transition-all duration-300
          disabled:opacity-50 disabled:cursor-not-allowed
          ${isOpen ? 'ring-4 ring-emerald-200' : ''}
        `}
      >
        <Download className="w-5 h-5 transition-transform duration-300 group-hover:scale-110" />
        <span>Export Data</span>
        <ChevronDown className={`w-4 h-4 transition-transform duration-300 ${isOpen ? 'rotate-180' : ''}`} />
        <div className="absolute inset-0 bg-gradient-to-r from-emerald-400 to-emerald-500 rounded-xl opacity-0 group-hover:opacity-20 transition-opacity duration-300"></div>
      </button>

      {isOpen && (
        <>
          <div 
            className="fixed inset-0 z-40" 
            onClick={() => setIsOpen(false)}
          />
          <div className="absolute right-0 mt-2 w-72 z-50 bg-white rounded-2xl shadow-2xl border border-gray-100 overflow-hidden animate-fade-in">
            <div className="p-4 bg-gradient-to-r from-emerald-50 to-emerald-100 border-b border-emerald-200">
              <h3 className="text-sm font-bold text-emerald-900 uppercase tracking-wider">
                Export Format
              </h3>
              <p className="text-xs text-emerald-700 mt-1">
                Choose your preferred format
              </p>
            </div>
            <div className="py-2">
              {exportOptions.map((option, index) => {
                const Icon = option.icon;
                return (
                  <button
                    key={option.format}
                    onClick={() => handleExport(option.format)}
                    className={`
                      w-full flex items-center gap-4 px-4 py-3.5
                      text-left transition-all duration-200
                      hover:bg-gradient-to-r hover:from-gray-50 hover:to-emerald-50
                      group relative
                      ${index !== exportOptions.length - 1 ? 'border-b border-gray-100' : ''}
                    `}
                  >
                    <div className={`
                      p-2.5 rounded-xl
                      bg-gradient-to-br ${option.color}
                      text-white shadow-lg
                      group-hover:scale-110 transition-transform duration-200
                    `}>
                      <Icon className="w-5 h-5" />
                    </div>
                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2">
                        <span className="font-semibold text-gray-900 group-hover:text-emerald-700 transition-colors">
                          {option.label}
                        </span>
                      </div>
                      <p className="text-xs text-gray-500 mt-0.5">
                        {option.description}
                      </p>
                    </div>
                    <div className="opacity-0 group-hover:opacity-100 transition-opacity">
                      <div className="w-2 h-2 bg-emerald-500 rounded-full"></div>
                    </div>
                  </button>
                );
              })}
            </div>
            <div className="px-4 py-3 bg-gradient-to-r from-gray-50 to-emerald-50 border-t border-gray-100">
              <p className="text-xs text-gray-600 text-center">
                <span className="font-semibold">{data?.length || 0}</span> records available
              </p>
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default ExportButton;

