'use client';

import { useState } from 'react';

interface ExportMenuProps {
  sessionId: string;
  disabled?: boolean;
}

export default function ExportMenu({ sessionId, disabled }: ExportMenuProps) {
  const [open, setOpen] = useState(false);
  const [exporting, setExporting] = useState<string | null>(null);

  const handleExport = async (format: string) => {
    setExporting(format);
    try {
      if (format === 'copy') {
        const res = await fetch(`/api/export/copy`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ session_id: sessionId }),
        });
        const data = await res.json();
        await navigator.clipboard.writeText(data.text);
        alert('Copied to clipboard!');
      } else {
        const res = await fetch(`/api/export/${format}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ session_id: sessionId }),
        });
        const blob = await res.blob();
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `output.${format === 'excel' ? 'xlsx' : format}`;
        a.click();
        URL.revokeObjectURL(url);
      }
    } catch (e) {
      console.error('Export failed:', e);
    } finally {
      setExporting(null);
      setOpen(false);
    }
  };

  const formats = [
    { key: 'copy', label: '📋 Copy to Clipboard', ext: '' },
    { key: 'docx', label: '📄 Word Document', ext: '.docx' },
    { key: 'excel', label: '📊 Excel Spreadsheet', ext: '.xlsx' },
    { key: 'pdf', label: '📕 PDF Document', ext: '.pdf' },
  ];

  return (
    <div className="relative">
      <button
        onClick={() => setOpen(!open)}
        disabled={disabled}
        className="px-4 py-2 bg-dark text-white rounded-lg text-sm hover:bg-dark/90 disabled:opacity-50"
      >
        📥 Export
      </button>
      {open && (
        <div className="absolute right-0 top-full mt-1 bg-white border rounded-lg shadow-lg py-1 w-56 z-20">
          {formats.map((f) => (
            <button
              key={f.key}
              onClick={() => handleExport(f.key)}
              disabled={exporting !== null}
              className="w-full text-left px-4 py-2 hover:bg-gray-50 text-sm disabled:opacity-50"
            >
              {exporting === f.key ? 'Exporting...' : f.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}
