import {
    AlertDialog,
    AlertDialogAction,
    AlertDialogCancel,
    AlertDialogContent,
    AlertDialogDescription,
    AlertDialogFooter,
    AlertDialogHeader,
    AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { formatRelative } from '@/lib/relative-time';
import { cn } from '@/lib/utils';
import type { SendRow } from '@/types/automatisations';
import { router } from '@inertiajs/react';
import { ExternalLink, Send, X } from 'lucide-react';
import { useState } from 'react';
import { fill, formatDateTimeShort, isUnknownResult, TONE_CLASSES } from './automatisations-format';
import type { Translate } from './labels';
import { StatusChip } from './StatusChip';

const NS = 'automatisations';

/** Borne du texte envoyé (ApproveAutomationSendRequest). */
const SEND_BODY_MAX = 4000;

interface Props {
    send: SendRow;
    canApprove: boolean;
    now: Date;
    locale: string;
    t: Translate;
}

/**
 * Un message qui attend un humain. Le texte COMPLET est modifiable ; le bouton
 * d'envoi NOMME sa destination (« Envoyer sur Airbnb », « Envoyer par e-mail »).
 *
 * Un échec au résultat INCONNU (le canal n'a pas répondu) demande une
 * confirmation avant de renvoyer : le premier envoi a peut-être abouti.
 */
export function PendingCard({ send, canApprove, now, locale, t }: Props) {
    const [body, setBody] = useState(send.body ?? '');
    const [busy, setBusy] = useState(false);
    const [confirmResend, setConfirmResend] = useState(false);

    const isFailure = send.status === 'failed' || send.status === 'retry';
    const unknown = send.status === 'failed' && isUnknownResult(send.reason);
    const empty = body.trim() === '';

    const destination =
        send.channel === 'email'
            ? t(NS, 'send_by_email', 'Envoyer par e-mail')
            : fill(t(NS, 'send_on', 'Envoyer sur :channel'), { channel: send.channelLabel ?? t(NS, 'channel_thread', 'le fil') });
    const primaryLabel = isFailure
        ? send.channel === 'email'
            ? t(NS, 'resend_by_email', 'Renvoyer par e-mail')
            : fill(t(NS, 'resend_on', 'Renvoyer sur :channel'), { channel: send.channelLabel ?? t(NS, 'channel_thread', 'le fil') })
        : destination;

    const approve = () => {
        setBusy(true);
        router.post(
            route('automatisations.sends.approve', send.id),
            { body },
            { preserveScroll: true, preserveState: true, onFinish: () => setBusy(false) },
        );
    };

    const dismiss = () => {
        setBusy(true);
        router.post(
            route('automatisations.sends.dismiss', send.id),
            {},
            { preserveScroll: true, preserveState: true, onFinish: () => setBusy(false) },
        );
    };

    return (
        <Card className="gap-0 py-0">
            <CardContent className="flex flex-col gap-3 p-4">
                <div className="flex flex-wrap items-start justify-between gap-2">
                    <div className="min-w-0">
                        <p className="font-medium">
                            {send.guestName}
                            {send.propertyName && <span className="text-muted-foreground font-normal"> · {send.propertyName}</span>}
                        </p>
                        <p className="text-muted-foreground text-xs">
                            {fill(t(NS, 'stay_dates', 'Séjour du :from au :to'), { from: send.checkIn ?? '—', to: send.checkOut ?? '—' })}
                            {' · '}
                            {send.channel === 'email'
                                ? t(NS, 'channel_by_email', 'Par e-mail')
                                : fill(t(NS, 'channel_on', 'Sur :channel'), { channel: send.channelLabel ?? t(NS, 'channel_thread', 'le fil') })}
                            {' · '}
                            {t(NS, 'rule_prefix', 'Règle :')} {send.ruleName}
                            {send.ruleDeleted && ` (${t(NS, 'rule_deleted', 'supprimée')})`}
                        </p>
                    </div>
                    <div className="flex shrink-0 items-center gap-2">
                        {send.scheduledAt && (
                            <Tooltip>
                                <TooltipTrigger asChild>
                                    <span tabIndex={0} className="text-muted-foreground cursor-help text-xs">
                                        {fill(t(NS, 'scheduled_relative', 'Prévu :when'), { when: formatRelative(send.scheduledAt, locale, now) })}
                                    </span>
                                </TooltipTrigger>
                                <TooltipContent className="bg-white text-xs text-gray-700">{formatDateTimeShort(send.scheduledAt)}</TooltipContent>
                            </Tooltip>
                        )}
                        <StatusChip status={send.status} t={t} />
                    </div>
                </div>

                {isFailure && send.reason && (
                    <p className={cn('rounded-md border px-2.5 py-1.5 text-xs font-medium', TONE_CLASSES.red)}>
                        {send.reason}
                        {unknown && (
                            <span className="block font-normal">
                                {t(NS, 'unknown_hint', 'Le message a peut-être été reçu : vérifiez le fil avant de renvoyer.')}
                            </span>
                        )}
                    </p>
                )}

                <Textarea
                    value={body}
                    onChange={(event) => setBody(event.target.value)}
                    maxLength={SEND_BODY_MAX}
                    readOnly={!canApprove}
                    aria-label={t(NS, 'message_label', 'Texte du message')}
                    className="min-h-28 text-sm"
                />

                <div className="flex flex-wrap items-center justify-between gap-2">
                    {send.inboxUrl ? (
                        <a
                            href={send.inboxUrl}
                            className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs underline"
                        >
                            <ExternalLink className="h-3.5 w-3.5" aria-hidden="true" />
                            {t(NS, 'open_inbox', 'Ouvrir dans la messagerie')}
                        </a>
                    ) : (
                        <span />
                    )}
                    {canApprove ? (
                        <div className="flex flex-wrap items-center gap-2">
                            <Button variant="outline" size="sm" onClick={dismiss} disabled={busy}>
                                <X className="h-4 w-4" />
                                {t(NS, 'dismiss', 'Écarter')}
                            </Button>
                            {send.ruleDeleted ? (
                                // Le serveur refuse l'envoi d'un message de règle supprimée :
                                // on ne propose pas un bouton qui ne peut qu'échouer.
                                <span className="text-muted-foreground text-xs">
                                    {t(NS, 'rule_deleted_no_resend', 'Règle supprimée : ce message ne peut plus partir.')}
                                </span>
                            ) : (
                                <Button
                                    size="sm"
                                    onClick={() => (unknown ? setConfirmResend(true) : approve())}
                                    disabled={busy || empty}
                                    title={empty ? t(NS, 'empty_body', 'Le message est vide.') : undefined}
                                >
                                    <Send className="h-4 w-4" />
                                    {primaryLabel}
                                </Button>
                            )}
                        </div>
                    ) : (
                        <span className="text-muted-foreground text-xs">
                            {t(NS, 'approve_read_only', 'Lecture seule : il faut le droit de valider les envois.')}
                        </span>
                    )}
                </div>
            </CardContent>

            <AlertDialog open={confirmResend} onOpenChange={setConfirmResend}>
                <AlertDialogContent>
                    <AlertDialogHeader>
                        <AlertDialogTitle>{t(NS, 'resend_confirm_title', 'Renvoyer malgré un résultat inconnu ?')}</AlertDialogTitle>
                        <AlertDialogDescription>
                            {t(
                                NS,
                                'resend_confirm_body',
                                'Le premier envoi a peut-être abouti. Ouvrez le fil et vérifiez : un message reçu deux fois est pire qu’un message manqué.',
                            )}
                        </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                        <AlertDialogCancel>{t(NS, 'cancel', 'Annuler')}</AlertDialogCancel>
                        <AlertDialogAction onClick={approve}>{t(NS, 'resend_confirm_action', 'J’ai vérifié, renvoyer')}</AlertDialogAction>
                    </AlertDialogFooter>
                </AlertDialogContent>
            </AlertDialog>
        </Card>
    );
}
