import { Button } from '@/components/ui/button';
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard';
import { useTranslation } from '@/hooks/use-translation';
import { cn } from '@/lib/utils';
import type { LogementShowStay } from '@/types/logement-show';
import { Check, Copy } from 'lucide-react';
import { toast } from 'sonner';
import { NS, fill } from '../format';

interface Props {
    stay: LogementShowStay;
    /** Icône seule (ligne étroite) ou bouton avec libellé. */
    compact?: boolean;
}

/**
 * Copie le lien PUBLIC des instructions d'entrée d'un séjour (codes d'accès,
 * WiFi). Un séjour non soldé le dit à côté du bouton : on ne copie pas ce lien
 * à l'aveugle. Absent quand le séjour n'a pas de lien (logement sans
 * instructions, ou pas de droit sur les réservations).
 */
export function CopyInstructionsButton({ stay, compact = false }: Props) {
    const { t } = useTranslation();
    const { copiedKey, copy: copyText } = useCopyToClipboard();

    const url = stay.instructions_url;
    if (!url) {
        return null;
    }

    const copy = async () => {
        if (await copyText(url)) {
            toast.success(fill(t(NS, 'instructions_copied'), { date: stay.instructions_valid_until ?? '' }));
        } else {
            // Presse-papiers refusé (contexte non sécurisé, autorisation) : on montre le lien à copier à la main.
            toast.error(t(NS, 'instructions_copy_failed'), { description: url, duration: 15000 });
        }
    };

    const label = t(NS, 'instructions_copy');
    const Icon = copiedKey !== null ? Check : Copy;

    return (
        <span className="inline-flex items-center gap-1.5">
            {!stay.is_paid && (
                <span
                    className="rounded-full bg-amber-100 px-2 py-0.5 text-[11px] font-medium whitespace-nowrap text-amber-800 dark:bg-amber-900/30 dark:text-amber-300"
                    title={t(NS, 'instructions_unpaid_title')}
                >
                    {t(NS, 'instructions_unpaid')}
                </span>
            )}
            <Button
                type="button"
                variant="outline"
                size="sm"
                onClick={copy}
                className={cn('h-7 gap-1.5 px-2 text-xs', compact && 'w-7 px-0')}
                title={`${label} — ${stay.guest_name} · ${fill(t(NS, 'instructions_valid_until'), { date: stay.instructions_valid_until ?? '' })}`}
                aria-label={`${label} — ${stay.guest_name}`}
            >
                <Icon className={cn('h-3.5 w-3.5', copiedKey !== null && 'text-emerald-600 dark:text-emerald-400')} aria-hidden="true" />
                {!compact && label}
            </Button>
        </span>
    );
}
