import { cn } from '@/lib/utils';
import type { SendStatus } from '@/types/automatisations';
import { statusTone, TONE_CLASSES, type StatusTone } from './automatisations-format';

const NS = 'automatisations';

type Translate = (namespace: string, key: string, fallback?: string) => string;

/** Libellé d'un statut d'envoi, en appels LITTÉRAUX (le test des traductions les lit). */
export function statusLabel(status: SendStatus, t: Translate): string {
    switch (status) {
        case 'sent':
            return t(NS, 'status_sent', 'Envoyé');
        case 'pending_approval':
            return t(NS, 'status_pending_approval', 'À valider');
        case 'waiting_channel':
            return t(NS, 'status_waiting_channel', 'En attente du fil');
        case 'retry':
            return t(NS, 'status_retry', 'Nouvel essai');
        case 'failed':
            return t(NS, 'status_failed', 'Échec');
        case 'skipped':
            return t(NS, 'status_skipped', 'Écarté');
        case 'cancelled':
            return t(NS, 'status_cancelled', 'Annulé');
    }
}

export function StatusChip({ status, t, className }: { status: SendStatus; t: Translate; className?: string }) {
    return (
        <span
            className={cn(
                'inline-flex shrink-0 items-center rounded-full border px-2 py-0.5 text-[11px] font-medium whitespace-nowrap',
                TONE_CLASSES[statusTone(status)],
                className,
            )}
        >
            {statusLabel(status, t)}
        </span>
    );
}

/** Pastilles pleines de la légende : les fonds des puces sont trop pâles pour se lire seuls. */
const DOT_CLASSES: Record<StatusTone, string> = {
    green: 'bg-emerald-500',
    amber: 'bg-amber-500',
    gray: 'bg-gray-400',
    red: 'bg-red-500',
};

function Dot({ tone }: { tone: StatusTone }) {
    return <span className={cn('inline-block h-2 w-2 shrink-0 rounded-full', DOT_CLASSES[tone])} aria-hidden="true" />;
}

/** Légende des couleurs : elles portent un sens, il est écrit. */
export function StatusLegend({ t }: { t: Translate }) {
    const items: { tone: StatusTone; label: string }[] = [
        { tone: 'green', label: t(NS, 'legend_green', 'Envoyé') },
        { tone: 'amber', label: t(NS, 'legend_amber', 'En attente (validation, fil, nouvel essai)') },
        { tone: 'gray', label: t(NS, 'legend_gray', 'Écarté ou annulé : rien n’est parti') },
        { tone: 'red', label: t(NS, 'legend_red', 'Échec : à vérifier') },
    ];

    return (
        <div className="text-muted-foreground flex flex-wrap items-center gap-x-4 gap-y-1 text-xs">
            {items.map((item) => (
                <span key={item.tone} className="inline-flex items-center gap-1.5">
                    <Dot tone={item.tone} />
                    {item.label}
                </span>
            ))}
        </div>
    );
}
