import { useState } from 'react';
import { useTranslator } from '@/lib/i18n';
import { exportPdf, exportXlsx, type ExportColumn } from '@/lib/export';

interface Props<T> {
    filename: string;                 // without extension, e.g. "vendors"
    title: string;                    // PDF heading + sheet name, e.g. "Vendors"
    columns: ExportColumn<T>[];
    rows: T[];
    className?: string;
}

/**
 * Dropdown that exports `rows` as PDF or Excel using the given columns.
 * Disabled when there's nothing to export. Reused across the list pages.
 */
export function ExportMenu<T>({ filename, title, columns, rows, className }: Props<T>) {
    const t = useTranslator();
    const [open, setOpen] = useState(false);

    const headers = columns.map((c) => c.header);
    const buildRows = () => rows.map((r) => columns.map((c) => c.value(r)));

    function run(kind: 'pdf' | 'xlsx') {
        const data = { filename, title, headers, rows: buildRows() };
        (kind === 'pdf' ? exportPdf : exportXlsx)(data);
        setOpen(false);
    }

    return (
        <div className={`relative ${className ?? ''}`}>
            <button
                type="button"
                onClick={() => setOpen((o) => !o)}
                disabled={rows.length === 0}
                className="inline-flex items-center gap-1.5 border border-border rounded-lg px-3 py-2 text-sm text-muted-foreground hover:text-foreground hover:border-foreground/30 transition-colors disabled:opacity-50"
            >
                {t('common.export')}
                <span className="text-[10px] leading-none">▾</span>
            </button>
            {open && (
                <>
                    {/* click-away */}
                    <div className="fixed inset-0 z-40" onClick={() => setOpen(false)} />
                    <div className="absolute right-0 mt-1 z-50 min-w-[150px] bg-card border border-border rounded-lg shadow-lg py-1">
                        <button type="button" onClick={() => run('pdf')} className="w-full text-left px-3 py-2 text-sm hover:bg-muted">
                            {t('common.export_pdf')}
                        </button>
                        <button type="button" onClick={() => run('xlsx')} className="w-full text-left px-3 py-2 text-sm hover:bg-muted">
                            {t('common.export_excel')}
                        </button>
                    </div>
                </>
            )}
        </div>
    );
}
