import React, { useState } from 'react';

interface ExportButtonProps {
  data: Record<string, any>[];
  filename?: string;
  formats?: ('csv' | 'json')[];
}

function toCSV(data: Record<string, any>[]): string {
  if (data.length === 0) return '';

  // Flatten nested objects for CSV
  const flattenRow = (obj: Record<string, any>, prefix = ''): Record<string, string> => {
    const flat: Record<string, string> = {};
    for (const [key, value] of Object.entries(obj)) {
      const fullKey = prefix ? `${prefix}.${key}` : key;
      if (value && typeof value === 'object' && !Array.isArray(value)) {
        Object.assign(flat, flattenRow(value, fullKey));
      } else if (Array.isArray(value)) {
        flat[fullKey] = value.map((v) =>
          typeof v === 'object' ? JSON.stringify(v) : String(v)
        ).join('; ');
      } else {
        flat[fullKey] = value != null ? String(value) : '';
      }
    }
    return flat;
  };

  const rows = data.map((row) => flattenRow(row));
  const headers = Array.from(new Set(rows.flatMap((r) => Object.keys(r))));

  const escape = (val: string) => {
    if (val.includes(',') || val.includes('"') || val.includes('\n')) {
      return `"${val.replace(/"/g, '""')}"`;
    }
    return val;
  };

  const lines = [
    headers.map(escape).join(','),
    ...rows.map((row) => headers.map((h) => escape(row[h] || '')).join(',')),
  ];
  return lines.join('\n');
}

function download(content: string, filename: string, type: string) {
  const blob = new Blob([content], { type });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

export function ExportButton({ data, filename = 'reonomy-export', formats = ['csv', 'json'] }: ExportButtonProps) {
  const [showMenu, setShowMenu] = useState(false);

  const exportCSV = () => {
    download(toCSV(data), `${filename}.csv`, 'text/csv');
    setShowMenu(false);
  };

  const exportJSON = () => {
    download(JSON.stringify(data, null, 2), `${filename}.json`, 'application/json');
    setShowMenu(false);
  };

  if (data.length === 0) return null;

  return (
    <div className="relative inline-block">
      {formats.length === 1 ? (
        <button
          onClick={formats[0] === 'csv' ? exportCSV : exportJSON}
          className="btn-secondary flex items-center gap-1.5 text-sm"
        >
          <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
          Export {formats[0].toUpperCase()}
        </button>
      ) : (
        <>
          <button
            onClick={() => setShowMenu(!showMenu)}
            className="btn-secondary flex items-center gap-1.5 text-sm"
          >
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 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>
            Export
            <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
            </svg>
          </button>
          {showMenu && (
            <div className="absolute right-0 top-full mt-1 bg-white border border-gray-200 rounded-lg shadow-lg z-20 overflow-hidden min-w-[120px]">
              {formats.includes('csv') && (
                <button onClick={exportCSV} className="w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-50">
                  📄 Export CSV
                </button>
              )}
              {formats.includes('json') && (
                <button onClick={exportJSON} className="w-full px-4 py-2 text-sm text-left text-gray-700 hover:bg-gray-50">
                  📋 Export JSON
                </button>
              )}
            </div>
          )}
        </>
      )}
    </div>
  );
}
