import {
    AlertDialog,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Spinner } from '@/components/ui/spinner';
import { useTranslation } from '@/hooks/use-translation';
import { router } from '@inertiajs/react';
import { Trash2 } from 'lucide-react';
import { useState } from 'react';
import { toast } from 'sonner';
import { fmtDate, fmtMontant } from '../format';
import type { FactureListe } from '../types';

interface Props {
    /** Brouillons cochés ET visibles : rien d'invisible ne part. */
    choisis: FactureListe[];
    onVider: () => void;
}

/** Au-delà, la liste du dialogue se résume en « + N autres ». */
const APERCU_MAX = 8;

/**
 * Barre de sélection de la liste des factures et sa confirmation : supprime
 * d'un bloc les BROUILLONS cochés. Une pièce émise ne se coche pas — elle
 * s'annule par un avoir (le serveur l'écarte de toute façon et le dit).
 */
export function SuppressionBrouillons({ choisis, onVider }: Props) {
    const { t } = useTranslation();
    const tr = (cle: string, fr: string, n?: number) => t('factures', cle, fr).replace(':n', String(n ?? choisis.length));

    const [confirmation, setConfirmation] = useState(false);
    const [envoi, setEnvoi] = useState(false);

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

    const supprimer = () => {
        router.post(
            route('factures.supprimer'),
            { ids: choisis.map((f) => f.id) },
            {
                preserveScroll: true,
                onStart: () => setEnvoi(true),
                onFinish: () => setEnvoi(false),
                // Le message (« 3 brouillons supprimés. ») arrive en flash avec la liste rechargée.
                onSuccess: () => {
                    setConfirmation(false);
                    onVider();
                },
                onError: (errors) =>
                    toast.error(errors.ids ?? Object.values(errors)[0] ?? tr('liste.supprimer_erreur', 'La suppression a échoué. Réessayez.')),
            },
        );
    };

    return (
        <>
            <div
                className="border-secondary/40 bg-secondary/5 flex flex-wrap items-center justify-between gap-2 rounded-lg border px-3 py-2 text-sm"
                role="region"
                aria-label={tr('liste.selection_n', ':n brouillon(s) sélectionné(s)')}
            >
                <span>
                    <span className="font-semibold tabular-nums">{choisis.length}</span>{' '}
                    {tr('liste.selection_libelle', 'brouillon(s) sélectionné(s)')}
                </span>
                <span className="flex items-center gap-2">
                    <Button type="button" variant="ghost" size="sm" onClick={onVider} disabled={envoi}>
                        {tr('liste.selection_vider', 'Tout désélectionner')}
                    </Button>
                    <Button type="button" variant="destructive" size="sm" onClick={() => setConfirmation(true)} disabled={envoi}>
                        <Trash2 className="size-4" aria-hidden />
                        {tr('liste.supprimer_n', 'Supprimer (:n)')}
                    </Button>
                </span>
            </div>

            <AlertDialog open={confirmation} onOpenChange={(ouvert) => !envoi && setConfirmation(ouvert)}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{tr('liste.supprimer_titre', 'Supprimer :n brouillon(s) ?')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {tr(
                                'liste.supprimer_texte',
                                "Un brouillon n'a pas encore de numéro : la numérotation ne bouge pas. Une fois supprimé, il disparaît de la liste.",
                            )}
                        </AlertDialogDescription>
                    </AlertDialogHeader>

                    <ul className="bg-muted/30 max-h-56 divide-y overflow-y-auto rounded-md border text-sm">
                        {choisis.slice(0, APERCU_MAX).map((f) => (
                            <li key={f.id} className="flex items-start justify-between gap-3 px-3 py-1.5">
                                <span className="min-w-0">
                                    <span className="block truncate font-medium">{f.client_nom}</span>
                                    <span className="text-muted-foreground block truncate text-xs">
                                        {fmtDate(f.date_facture)}
                                        {f.origine_libelle ? ` · ${f.origine_libelle}` : ''}
                                    </span>
                                </span>
                                <span className="shrink-0 tabular-nums">{fmtMontant(f.total_ttc, f.devise)}</span>
                            </li>
                        ))}
                        {choisis.length > APERCU_MAX && (
                            <li className="text-muted-foreground px-3 py-1.5 text-xs">
                                {tr('liste.supprimer_autres', '+ :n autre(s)', choisis.length - APERCU_MAX)}
                            </li>
                        )}
                    </ul>

                    <p className="text-muted-foreground text-xs">
                        {tr(
                            'liste.supprimer_liberes',
                            'Les versements et séjours portés par ces brouillons (relevé bancaire, rapport Airbnb, commission du mois) redeviennent facturables.',
                        )}
                    </p>

                    <AlertDialogFooter>
                        <AlertDialogCancel disabled={envoi}>{tr('liste.annuler', 'Annuler')}</AlertDialogCancel>
                        <Button type="button" variant="destructive" onClick={supprimer} disabled={envoi}>
                            {envoi && <Spinner size="sm" className="text-white" />}
                            {tr('liste.supprimer_confirmer', 'Supprimer :n brouillon(s)')}
                        </Button>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </>
    );
}
