'use client';

import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Download } from 'lucide-react';

interface DataExportButtonProps {
  endpoint: string;
  params?: Record<string, string>;
}

export default function DataExportButton({ endpoint, params }: DataExportButtonProps) {
  const [loading, setLoading] = useState(false);

  const handleExport = async (format: 'csv' | 'json') => {
    setLoading(true);
    try {
      const query = new URLSearchParams({ format, ...params });
      const res = await fetch(`${endpoint}?${query.toString()}`);
      if (!res.ok) throw new Error('Export failed');

      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `export.${format}`;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      // Error handled silently — toast can be added later
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="flex gap-2">
      <Button
        variant="outline"
        size="sm"
        onClick={() => handleExport('csv')}
        disabled={loading}
      >
        <Download className="w-4 h-4 mr-1" />
        CSV
      </Button>
      <Button
        variant="outline"
        size="sm"
        onClick={() => handleExport('json')}
        disabled={loading}
      >
        <Download className="w-4 h-4 mr-1" />
        JSON
      </Button>
    </div>
  );
}
