import { ChevronDown, Download } from 'lucide-react';
import {
    DropdownMenu,
    DropdownMenuContent,
    DropdownMenuItem,
    DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { cn } from '@/lib/utils';

const formats = [
    { value: 'xlsx', label: 'Excel (.xlsx)' },
    { value: 'pdf', label: 'PDF' },
    { value: 'csv', label: 'CSV' },
] as const;

/**
 * Download the current report, with its filters, as Excel, PDF or CSV
 * (AMCSMS §25).
 */
export default function ExportMenu({
    label = 'Download',
    query = {},
    className,
}: {
    label?: string;
    query?: Record<string, string>;
    className?: string;
}) {
    const urlFor = (format: string) => {
        const params = new URLSearchParams(window.location.search);
        params.delete('page');
        Object.entries(query).forEach(([name, value]) =>
            params.set(name, value),
        );
        params.set('format', format);

        return `${window.location.pathname}?${params}`;
    };

    return (
        <DropdownMenu>
            <DropdownMenuTrigger asChild>
                <button
                    type="button"
                    className={cn(
                        'inline-flex h-9 items-center gap-1.5 rounded-md border border-input bg-white px-3 text-sm font-semibold text-ink-700 hover:bg-surface-50 print:hidden',
                        className,
                    )}
                >
                    <Download className="size-4" />
                    {label}
                    <ChevronDown className="size-3.5 text-ink-400" />
                </button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
                {formats.map((format) => (
                    <DropdownMenuItem key={format.value} asChild>
                        <a href={urlFor(format.value)}>{format.label}</a>
                    </DropdownMenuItem>
                ))}
            </DropdownMenuContent>
        </DropdownMenu>
    );
}
