import { cn } from '@/lib/utils';
import { STATUT_CLASSES, STATUT_LIBELLE, statutAffiche, type StatutAffiche } from '../format';
import type { FactureStatut, FactureType } from '../types';

/** Pastille de couleur, alignée sur la teinte du texte de chaque statut. */
const POINT: Record<StatutAffiche, string> = {
    brouillon: 'bg-slate-400',
    emise: 'bg-amber-500',
    payee: 'bg-emerald-500',
    annulee: 'bg-slate-300',
    convertie: 'bg-slate-400',
    en_retard: 'bg-rose-500',
};

interface StatusChipProps {
    statut: FactureStatut;
    /** Facture émise dont l'échéance est passée (calculé par le serveur). */
    enRetard?: boolean;
    /**
     * Sorte de pièce. Une proforma ou un avoir émis ne se PAIENT pas : ils ne
     * doivent jamais s'afficher « Non payée » comme une facture en attente.
     */
    type?: FactureType;
    className?: string;
}

/**
 * Statut AFFICHÉ d'une pièce : « En retard » prime sur « Non payée ». Partagé
 * par la liste et l'éditeur, pour qu'un même statut ait partout la même teinte.
 */
export function StatusChip({ statut, enRetard = false, type, className }: StatusChipProps) {
    const affiche = statutAffiche({ statut, en_retard: enRetard });
    const emiseSansPaiement = statut === 'emise' && type !== undefined && type !== 'facture';

    return (
        <span
            className={cn(
                'inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap ring-1 ring-inset',
                emiseSansPaiement ? 'bg-sky-50 text-sky-800 ring-sky-200' : STATUT_CLASSES[affiche],
                className,
            )}
        >
            <span className={cn('size-1.5 shrink-0 rounded-full', emiseSansPaiement ? 'bg-sky-500' : POINT[affiche])} aria-hidden />
            {emiseSansPaiement ? (type === 'avoir' ? 'Émis' : 'Émise') : STATUT_LIBELLE[affiche]}
        </span>
    );
}
