import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { formatRelative } from '@/lib/relative-time';
import { cn } from '@/lib/utils';
import type { AutomationHealth } from '@/types/automatisations';
import { Activity, AlertTriangle, CircleOff, MailX } from 'lucide-react';
import { fill, formatDateTimeShort, lastRunState, linksBaseMismatch, TONE_CLASSES } from './automatisations-format';

const NS = 'automatisations';

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

interface Props {
    health: AutomationHealth;
    now: Date;
    locale: string;
    t: Translate;
}

/**
 * Bandeau d'état HONNÊTE : est-ce que quelque chose peut partir, là, maintenant ?
 *
 *  - serveur fermé (`enabled = false`) : gris, aucune règle ne s'exécute ;
 *  - planificateur jamais passé : rouge ; passé il y a plus de 90 min : ambre
 *    (il passe une fois par heure) ; sinon une mention discrète ;
 *  - repli e-mail fermé : une note — les réservations sans fil de messagerie
 *    seront écartées, avec leur motif.
 */
export function StatusBanner({ health, now, locale, t }: Props) {
    const state = lastRunState(health.lastRunAt, now);
    const linksBase = typeof window === 'undefined' ? null : linksBaseMismatch(health.linksBaseUrl, window.location.origin);
    const stats = health.lastRunStats;
    const statsLine = stats
        ? fill(t(NS, 'banner_last_run_stats', 'Préparés : :created · envoyés : :sent · à valider : :pending · échecs : :failed'), {
              created: stats.created ?? 0,
              sent: stats.sent ?? 0,
              pending: stats.pending_approval ?? 0,
              failed: stats.failed ?? 0,
          })
        : null;

    return (
        <div data-tour="automatisations-status" className="flex w-fit max-w-full flex-wrap items-center gap-2 text-xs">
            {!health.enabled && (
                <span className={cn('inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 font-medium', TONE_CLASSES.gray)}>
                    <CircleOff className="h-3.5 w-3.5" aria-hidden="true" />
                    {t(NS, 'banner_disabled', 'Envoi automatique désactivé sur ce serveur — aucune règle ne s’exécute')}
                </span>
            )}

            {state === 'never' ? (
                <span className={cn('inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 font-medium', TONE_CLASSES.red)}>
                    <Activity className="h-3.5 w-3.5" aria-hidden="true" />
                    {t(NS, 'banner_never_ran', 'Le planificateur n’a jamais tourné')}
                </span>
            ) : (
                <Tooltip>
                    <TooltipTrigger asChild>
                        <span
                            tabIndex={0}
                            className={cn(
                                'inline-flex cursor-help items-center gap-1.5 rounded-full border px-2.5 py-1',
                                state === 'stale' ? cn('font-medium', TONE_CLASSES.amber) : 'text-muted-foreground border-transparent',
                            )}
                        >
                            <Activity className="h-3.5 w-3.5" aria-hidden="true" />
                            {fill(t(NS, 'banner_last_run', 'Dernière exécution :when'), {
                                when: formatRelative(health.lastRunAt ?? '', locale, now),
                            })}
                        </span>
                    </TooltipTrigger>
                    <TooltipContent className="max-w-[260px] bg-white text-xs text-gray-700">
                        <p>{formatDateTimeShort(health.lastRunAt)}</p>
                        <p>
                            {t(
                                NS,
                                'banner_frequency',
                                'Le planificateur passe une fois par heure : un message part dans l’heure qui suit son heure prévue.',
                            )}
                        </p>
                        {statsLine && <p className="mt-1">{statsLine}</p>}
                    </TooltipContent>
                </Tooltip>
            )}

            {linksBase && (
                <span className={cn('inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 font-medium', TONE_CLASSES.amber)}>
                    <AlertTriangle className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
                    {fill(
                        t(
                            NS,
                            'banner_links_base_mismatch',
                            'Les liens des messages partiront de :base, pas de l’adresse de ce site — vérifiez APP_URL sur le serveur',
                        ),
                        { base: linksBase },
                    )}
                </span>
            )}

            {!health.emailEnabled && (
                <span className="text-muted-foreground inline-flex items-center gap-1.5 px-1">
                    <MailX className="h-3.5 w-3.5" aria-hidden="true" />
                    {t(NS, 'banner_email_disabled', 'E-mail de repli désactivé')}
                </span>
            )}
        </div>
    );
}
