import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { formatRelative } from '@/lib/relative-time';
import { cn } from '@/lib/utils';
import type { PaginatedResponse } from '@/types';
import type { SendRow, SendStatus } from '@/types/automatisations';
import { router } from '@inertiajs/react';
import { ChevronLeft, ChevronRight, History } from 'lucide-react';
import { useState } from 'react';
import { fill, formatDateTimeShort } from './automatisations-format';
import type { Translate } from './labels';
import { SendDetailDialog } from './SendDetailDialog';
import { StatusChip, statusLabel, StatusLegend } from './StatusChip';

const NS = 'automatisations';

/** Statuts filtrables : tout sauf « à valider », qui a son onglet. */
const FILTERABLE: SendStatus[] = ['sent', 'waiting_channel', 'retry', 'failed', 'skipped', 'cancelled'];

interface Props {
    history: PaginatedResponse<SendRow>;
    status: SendStatus | null;
    now: Date;
    locale: string;
    t: Translate;
}

/**
 * Tout ce qui s'est passé, le plus récent en haut. Une ligne se balaie
 * (statut, voyageur, logement, règle, canal, quand) ; son détail — résultat,
 * déroulé, message reçu, liens — s'ouvre au clic (SendDetailDialog).
 */
export function HistoryTab({ history, status, now, locale, t }: Props) {
    const [open, setOpen] = useState<SendRow | null>(null);

    const visit = (params: Record<string, string>) => {
        router.get(
            route('automatisations.index'),
            { tab: 'history', ...params },
            { preserveState: true, preserveScroll: true, only: ['history', 'filters', 'tab'] },
        );
    };

    const filter = (next: SendStatus | null) => visit(next ? { status: next } : {});

    const goToPage = (page: number) => visit({ ...(status ? { status } : {}), page: String(page) });

    return (
        <div className="flex flex-col gap-3">
            {/* Puces puis légende, chacune sur sa ligne : côte à côte, les puces passaient
                à la ligne par deux à 1280 px — des boutons orphelins. */}
            <div className="flex flex-col gap-2">
                <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t(NS, 'history_filter', 'Filtrer par statut')}>
                    <button
                        type="button"
                        aria-pressed={status === null}
                        onClick={() => filter(null)}
                        className={cn(
                            'rounded-full border px-3 py-1 text-xs',
                            status === null
                                ? 'border-primary bg-primary text-primary-foreground'
                                : 'text-muted-foreground hover:bg-muted border-dashed',
                        )}
                    >
                        {t(NS, 'history_all', 'Tous')}
                    </button>
                    {FILTERABLE.map((value) => (
                        <button
                            key={value}
                            type="button"
                            aria-pressed={status === value}
                            onClick={() => filter(status === value ? null : value)}
                            className={cn(
                                'rounded-full border px-3 py-1 text-xs',
                                status === value
                                    ? 'border-primary bg-primary text-primary-foreground'
                                    : 'text-muted-foreground hover:bg-muted border-dashed',
                            )}
                        >
                            {statusLabel(value, t)}
                        </button>
                    ))}
                </div>
                <StatusLegend t={t} />
            </div>

            {history.data.length === 0 ? (
                <Card>
                    <CardContent className="flex flex-col items-center gap-2 py-12 text-center">
                        <History className="text-muted-foreground h-8 w-8" aria-hidden="true" />
                        <p className="text-muted-foreground max-w-md text-sm">
                            {status
                                ? t(NS, 'history_empty_filtered', 'Aucun message avec ce statut.')
                                : t(
                                      NS,
                                      'history_empty',
                                      'Aucun message pour l’instant. Chaque message préparé, envoyé ou écarté par une règle apparaîtra ici avec son motif.',
                                  )}
                        </p>
                    </CardContent>
                </Card>
            ) : (
                <ul className="divide-y rounded-lg border">
                    {history.data.map((send) => {
                        const when = send.sentAt ?? send.updatedAt;

                        return (
                            <li key={send.id}>
                                <button
                                    type="button"
                                    onClick={() => setOpen(send)}
                                    className="hover:bg-muted/40 flex w-full flex-col gap-1 px-3 py-2.5 text-left sm:flex-row sm:items-center sm:gap-3"
                                >
                                    <span className="flex shrink-0 items-center gap-2 sm:w-36">
                                        <StatusChip status={send.status} t={t} />
                                    </span>
                                    <span className="min-w-0 flex-1">
                                        <span className="block truncate text-sm">
                                            <span className="font-medium">{send.guestName}</span>
                                            {send.propertyName && <span className="text-muted-foreground"> · {send.propertyName}</span>}
                                        </span>
                                        <span className="text-muted-foreground block truncate text-xs">
                                            {send.ruleName}
                                            {send.channelLabel && ` · ${send.channelLabel}`}
                                            {send.reason && ` · ${send.reason}`}
                                        </span>
                                    </span>
                                    <span className="text-muted-foreground shrink-0 text-xs" title={formatDateTimeShort(when)}>
                                        {when ? formatRelative(when, locale, now) : ''}
                                    </span>
                                </button>
                            </li>
                        );
                    })}
                </ul>
            )}

            {history.last_page > 1 && (
                <div className="flex items-center justify-between gap-2 text-xs">
                    <span className="text-muted-foreground tabular-nums">
                        {fill(t(NS, 'history_range', ':from–:to sur :total'), { from: history.from ?? 0, to: history.to ?? 0, total: history.total })}
                    </span>
                    <div className="flex items-center gap-1">
                        <Button
                            variant="outline"
                            size="sm"
                            disabled={history.current_page <= 1}
                            onClick={() => goToPage(history.current_page - 1)}
                            aria-label={t(NS, 'previous', 'Précédent')}
                        >
                            <ChevronLeft className="h-4 w-4" />
                        </Button>
                        <Button
                            variant="outline"
                            size="sm"
                            disabled={history.current_page >= history.last_page}
                            onClick={() => goToPage(history.current_page + 1)}
                            aria-label={t(NS, 'next', 'Suivant')}
                        >
                            <ChevronRight className="h-4 w-4" />
                        </Button>
                    </div>
                </div>
            )}

            <SendDetailDialog send={open} onClose={() => setOpen(null)} t={t} />
        </div>
    );
}
