/**
 * ExportButton Component
 * Dropdown button for exporting trading history in various formats
 */

import { useState, useRef, useEffect } from 'react';

// ============================================================================
// Types
// ============================================================================

export type ExportFormat = 'csv' | 'excel' | 'pdf' | 'json';

export interface ExportFilters {
  startDate?: string;
  endDate?: string;
  symbols?: string[];
  status?: 'open' | 'closed' | 'all';
  direction?: 'long' | 'short' | 'all';
}

interface ExportButtonProps {
  filters?: ExportFilters;
  className?: string;
}

// ============================================================================
// Icons
// ============================================================================

const DownloadIcon = ({ className = 'w-5 h-5' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
      d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
  </svg>
);

const ChevronDownIcon = ({ className = 'w-4 h-4' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
  </svg>
);

const SpinnerIcon = ({ className = 'w-4 h-4' }: { className?: string }) => (
  <svg className={`${className} animate-spin`} fill="none" viewBox="0 0 24 24">
    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
  </svg>
);

const CSVIcon = ({ className = 'w-5 h-5' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
      d="M9 17v-2m3 2v-4m3 4v-6m2 10H7a2 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>
);

const ExcelIcon = ({ className = 'w-5 h-5' }: { className?: string }) => (
  <svg className={className} viewBox="0 0 24 24" fill="currentColor">
    <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2zM6 4h7.5l4.5 4.5V20H6V4z" />
    <path d="M8 13l2.5 4h2L10 13l2.5-4h-2L8 13zm4 0l2.5 4h2L14 13l2.5-4h-2L12 13z" opacity="0.5" />
  </svg>
);

const PDFIcon = ({ className = 'w-5 h-5' }: { className?: string }) => (
  <svg className={className} viewBox="0 0 24 24" fill="currentColor">
    <path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2zM6 4h7.5l4.5 4.5V20H6V4z" />
    <path d="M10.5 11H9v6h1v-2h.5a2.5 2.5 0 0 0 0-5H10.5zm-.5 3v-2h.5a1 1 0 0 1 0 2H10z" opacity="0.8" />
  </svg>
);

const JSONIcon = ({ className = 'w-5 h-5' }: { className?: string }) => (
  <svg className={className} fill="none" viewBox="0 0 24 24" stroke="currentColor">
    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2}
      d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
  </svg>
);

// ============================================================================
// Constants
// ============================================================================

const API_BASE_URL = import.meta.env?.VITE_API_URL || '/api/v1';

const exportFormats = [
  { id: 'csv' as const, name: 'CSV', description: 'Comma-separated values', icon: CSVIcon },
  { id: 'excel' as const, name: 'Excel', description: 'Microsoft Excel format', icon: ExcelIcon },
  { id: 'pdf' as const, name: 'PDF', description: 'Printable PDF report', icon: PDFIcon },
  { id: 'json' as const, name: 'JSON', description: 'Raw JSON data', icon: JSONIcon },
];

// ============================================================================
// Component
// ============================================================================

export function ExportButton({ filters = {}, className = '' }: ExportButtonProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [exporting, setExporting] = useState<ExportFormat | null>(null);
  const [error, setError] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // Close dropdown when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }

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

  // Build query string from filters
  const buildQueryString = (): string => {
    const params = new URLSearchParams();

    if (filters.startDate) params.append('startDate', filters.startDate);
    if (filters.endDate) params.append('endDate', filters.endDate);
    if (filters.symbols?.length) params.append('symbols', filters.symbols.join(','));
    if (filters.status && filters.status !== 'all') params.append('status', filters.status);
    if (filters.direction && filters.direction !== 'all') params.append('direction', filters.direction);

    const queryString = params.toString();
    return queryString ? `?${queryString}` : '';
  };

  // Handle export
  const handleExport = async (format: ExportFormat) => {
    setExporting(format);
    setError(null);

    try {
      const token = localStorage.getItem('token');
      if (!token) {
        throw new Error('Please log in to export data');
      }

      const queryString = buildQueryString();
      const url = `${API_BASE_URL}/trading/history/export/${format}${queryString}`;

      const response = await fetch(url, {
        method: 'GET',
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });

      if (!response.ok) {
        if (response.status === 401) {
          throw new Error('Session expired. Please log in again.');
        }
        throw new Error(`Export failed: ${response.statusText}`);
      }

      // Get filename from Content-Disposition header or generate one
      const contentDisposition = response.headers.get('Content-Disposition');
      let filename = `trading-history.${format === 'excel' ? 'xlsx' : format}`;

      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
        if (filenameMatch) {
          filename = filenameMatch[1];
        }
      }

      // Download the file
      const blob = await response.blob();
      const downloadUrl = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = downloadUrl;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(downloadUrl);

      setIsOpen(false);
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Export failed');
      console.error('Export error:', err);
    } finally {
      setExporting(null);
    }
  };

  return (
    <div className={`relative ${className}`} ref={dropdownRef}>
      {/* Main Button */}
      <button
        type="button"
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 px-4 py-2 bg-slate-700 text-white rounded-lg hover:bg-slate-600 transition-colors"
      >
        <DownloadIcon className="w-4 h-4" />
        <span className="font-medium">Export</span>
        <ChevronDownIcon className={`w-4 h-4 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
      </button>

      {/* Dropdown Menu */}
      {isOpen && (
        <div className="absolute right-0 mt-2 w-64 bg-slate-800 border border-slate-700 rounded-lg shadow-xl z-50">
          {/* Header */}
          <div className="px-4 py-3 border-b border-slate-700">
            <p className="font-medium text-white">Export Format</p>
            <p className="text-xs text-slate-400 mt-1">Choose a format for your trading history</p>
          </div>

          {/* Error Message */}
          {error && (
            <div className="px-4 py-2 bg-red-500/10 border-b border-slate-700">
              <p className="text-sm text-red-400">{error}</p>
            </div>
          )}

          {/* Format Options */}
          <div className="py-2">
            {exportFormats.map((format) => (
              <button
                key={format.id}
                type="button"
                onClick={() => handleExport(format.id)}
                disabled={exporting !== null}
                className="w-full flex items-center gap-3 px-4 py-2.5 hover:bg-slate-700/50 transition-colors disabled:opacity-50"
              >
                <div className="flex-shrink-0 p-1.5 bg-slate-700 rounded">
                  {exporting === format.id ? (
                    <SpinnerIcon className="w-5 h-5 text-blue-400" />
                  ) : (
                    <format.icon className="w-5 h-5 text-slate-300" />
                  )}
                </div>
                <div className="flex-1 text-left">
                  <p className="font-medium text-white">{format.name}</p>
                  <p className="text-xs text-slate-400">{format.description}</p>
                </div>
                {exporting === format.id && (
                  <span className="text-xs text-blue-400">Exporting...</span>
                )}
              </button>
            ))}
          </div>

          {/* Footer */}
          <div className="px-4 py-2 border-t border-slate-700 bg-slate-800/50">
            <p className="text-xs text-slate-500">
              Export includes all trades matching current filters
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

export default ExportButton;
