import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useTranslation } from '@/hooks/use-translation';
import { Head, router, usePage } from '@inertiajs/react';
import { ArrowRight, Mail, Printer } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import SignaturePad from 'react-signature-canvas';
import { toast } from 'sonner';

interface ReservationInfo {
    id: number;
    contract_id: string | null;
    client: string;
    property: string;
    check_in: string | null;
    check_out: string | null;
}

interface TeamMember { id: number; name: string; has_pin: boolean }

interface ReceiptProps {
    receipt: {
        id: number; date: string; amount: string; currency: string;
        payment_mode: string; note: string | null; signature_status: string | null;
        signature_attempts?: number;
    };
    encryptedId: string;
    giverName: string;
    receiverName: string | null;
    signatureUrl: string | null;
    signedAt: string | null;
    receiptBlocked: boolean;
    receiptBlockedAt: string | null;
    isAuthenticated: boolean;
    reservationInfo: ReservationInfo | null;
    receivers?: TeamMember[];
    stampUrl: string;
    companyInfo: { companyName: string; matricule: string; ville: string; address: string; zip_code: string };
    errors?: Record<string, string>;
    flash?: { type: string; message: string };
}

export default function ReceiptShow() {
    const {
        receipt, encryptedId, giverName, receiverName, signatureUrl, signedAt,
        receiptBlocked, receiptBlockedAt, isAuthenticated, reservationInfo, receivers, stampUrl, companyInfo, errors, flash,
    } = usePage<ReceiptProps>().props;
    const { t, locale } = useTranslation();
    const dateLocale = locale === 'en' ? 'en-US' : 'fr-FR';
    const modeLabel = (m: string) =>
        ({
            CASH: t('recus', 'mode_prose_cash', 'en espèces'),
            CHÈQUE: t('recus', 'mode_prose_cheque', 'par chèque'),
            VIREMENT: t('recus', 'mode_prose_transfer', 'par virement'),
            PAYMEE: t('recus', 'mode_prose_paymee', 'via Paymee'),
            TPE: t('recus', 'mode_prose_tpe', 'par TPE'),
        }[m] ?? m);

    const sigPadRef = useRef<SignaturePad>(null);
    const sigWrapRef = useRef<HTMLDivElement>(null);
    const [pin, setPin] = useState('');
    const [localError, setLocalError] = useState('');
    const [submitting, setSubmitting] = useState(false);
    const [emailOpen, setEmailOpen] = useState(false);
    const [emailTo, setEmailTo] = useState('');
    const [emailSending, setEmailSending] = useState(false);
    // Receiver picker state — used when the receipt is pending but no receiver
    // has been assigned yet (e.g. created via the Encaisser "avec signature" mode).
    const [pickedReceiverId, setPickedReceiverId] = useState<string>('');
    const [assigningReceiver, setAssigningReceiver] = useState(false);

    const needsSignature   = receipt.signature_status === 'pending' && !!receiverName;
    const needsReceiver    = receipt.signature_status === 'pending' && !receiverName && Array.isArray(receivers);

    const assignReceiver = () => {
        if (!pickedReceiverId || assigningReceiver) return;
        setAssigningReceiver(true);
        router.patch(route('recus.set-receiver', encryptedId), { receiver_user_id: Number(pickedReceiverId) }, {
            onFinish: () => setAssigningReceiver(false),
        });
    };

    useEffect(() => {
        if (flash?.type === 'success') toast.success(flash.message);
        else if (flash?.type === 'error') toast.error(flash.message);
    }, [flash]);

    // Dynamic signature pad: keep canvas backing store in sync with rendered size,
    // account for DPI, preserve in-progress strokes across resizes.
    useEffect(() => {
        if (!needsSignature || receiptBlocked) return;
        const wrap = sigWrapRef.current;
        const pad = sigPadRef.current;
        if (!wrap || !pad) return;

        const fit = () => {
            const canvas = pad.getCanvas();
            const ratio = Math.max(window.devicePixelRatio || 1, 1);
            const wasEmpty = pad.isEmpty();
            const dataUrl = wasEmpty ? null : pad.toDataURL();
            const width = wrap.clientWidth;
            const height = wrap.clientHeight;
            canvas.width = width * ratio;
            canvas.height = height * ratio;
            canvas.style.width = `${width}px`;
            canvas.style.height = `${height}px`;
            const ctx = canvas.getContext('2d');
            ctx?.scale(ratio, ratio);
            pad.clear();
            if (dataUrl) pad.fromDataURL(dataUrl, { width, height });
        };

        fit();
        const ro = new ResizeObserver(fit);
        ro.observe(wrap);
        window.addEventListener('orientationchange', fit);
        return () => {
            ro.disconnect();
            window.removeEventListener('orientationchange', fit);
        };
    }, [needsSignature, receiptBlocked]);

    const handleSign = () => {
        setLocalError('');
        if (!/^\d{4}$/.test(pin)) { setLocalError(t('recus', 'err_pin_format', 'Code PIN à 4 chiffres requis.')); return; }
        if (sigPadRef.current?.isEmpty()) { setLocalError(t('recus', 'err_signature_required', 'Signature requise.')); return; }
        const dataUrl = sigPadRef.current?.getCanvas().toDataURL('image/png');
        setSubmitting(true);
        router.post(route('recus.sign', encryptedId), { pin, signature: dataUrl }, {
            preserveScroll: true,
            onFinish: () => { setSubmitting(false); setPin(''); },
            onSuccess: () => sigPadRef.current?.clear(),
        });
    };

    const handleEmail = (e: React.FormEvent) => {
        e.preventDefault();
        setEmailSending(true);
        router.post(route('recus.email', encryptedId), { email: emailTo }, {
            preserveScroll: true,
            onFinish: () => setEmailSending(false),
            onSuccess: () => setEmailOpen(false),
        });
    };

    return (
        <>
            <Head title={t('recus', 'head_title', 'Reçu de Paiement')} />

            {isAuthenticated && (
                <div style={{ maxWidth: '800px', margin: '0 auto' }} className="px-4 pt-4 print:hidden">
                    <div className="flex justify-end gap-2">
                        <Button
                            size="sm"
                            onClick={() => {
                                if (window.history.length > 1) {
                                    window.history.back();
                                } else {
                                    router.visit(route('recus.index'));
                                }
                            }}
                        >
                            {t('recus', 'continue', 'Continuer')} <ArrowRight className="ml-1 h-4 w-4" />
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => window.print()}>
                            <Printer className="mr-1 h-4 w-4" /> {t('recus', 'print', 'Imprimer')}
                        </Button>
                        <Dialog open={emailOpen} onOpenChange={setEmailOpen}>
                            <DialogTrigger asChild>
                                <Button size="sm" variant="outline">
                                    <Mail className="mr-1 h-4 w-4" /> {t('recus', 'send_email', 'Envoyer par email')}
                                </Button>
                            </DialogTrigger>
                            <DialogContent className="max-w-md">
                                <form onSubmit={handleEmail}>
                                    <DialogHeader><DialogTitle>{t('recus', 'send_email_title', 'Envoyer le reçu par email')}</DialogTitle></DialogHeader>
                                    <div className="mt-4">
                                        <Label>{t('recus', 'email_label', 'Adresse email')}</Label>
                                        <Input type="email" value={emailTo} onChange={e => setEmailTo(e.target.value)} required placeholder={t('recus', 'email_placeholder', 'destinataire@example.com')} />
                                        {errors?.email && <p className="mt-1 text-sm text-red-600">{errors.email}</p>}
                                    </div>
                                    <DialogFooter className="mt-4">
                                        <Button type="submit" disabled={emailSending}>{emailSending ? t('recus', 'sending', 'Envoi...') : t('recus', 'send', 'Envoyer')}</Button>
                                    </DialogFooter>
                                </form>
                            </DialogContent>
                        </Dialog>
                    </div>
                </div>
            )}

            <div className="my-4 rounded-lg bg-white p-4 shadow-md sm:p-10" style={{ maxWidth: '800px', margin: '0 auto' }}>
                {/* Logo */}
                <div className="mb-6 flex justify-center">
                    <img src="/Logo.png" alt="The Landlord" style={{ maxHeight: '100px' }} />
                </div>

                {/* Date */}
                <div style={{ textAlign: 'right', marginBottom: '20px' }}>
                    {t('recus', 'show_city_prefix', 'Tunis,')}{' '}
                    <strong>{new Date(receipt.date).toLocaleString(dateLocale, { year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit' })}</strong>
                </div>

                {/* Title */}
                <h2 className="mb-4 text-center text-2xl font-bold">{t('recus', 'head_title', 'Reçu de Paiement')}</h2>

                {/* Body */}
                <div style={{ lineHeight: 1.8 }}>
                    <p>
                        {locale === 'en' ? (
                            <>
                                I, the undersigned <strong>{giverName}</strong>, declare having handed over the sum of{' '}
                                <strong>{receipt.amount} {receipt.currency}</strong> <strong>{modeLabel(receipt.payment_mode)}</strong>
                                {receiverName && <> to <strong>{receiverName}</strong></>}.
                            </>
                        ) : (
                            <>
                                Je soussigné(e) <strong>{giverName}</strong>, déclare avoir remis la somme de{' '}
                                <strong>{receipt.amount} {receipt.currency}</strong> <strong>{modeLabel(receipt.payment_mode)}</strong>
                                {receiverName && <> à <strong>{receiverName}</strong></>}.
                            </>
                        )}
                    </p>
                    {receipt.note && (
                        <p className="mt-2">
                            <span className="text-gray-600">{t('recus', 'show_object_label', 'Objet :')} </span>{receipt.note}
                        </p>
                    )}
                    {reservationInfo && (
                        <div className="mt-4 rounded-md border border-gray-200 bg-gray-50 p-3 text-sm">
                            <p className="mb-2 font-semibold">
                                {t('recus', 'show_reservation_title', 'Réservation associée')}
                            </p>
                            <div className="grid gap-1 sm:grid-cols-2">
                                {reservationInfo.property && (
                                    <div>
                                        <span className="text-gray-600">{t('recus', 'show_reservation_property', 'Logement')}: </span>
                                        <span className="font-medium">{reservationInfo.property}</span>
                                    </div>
                                )}
                                <div>
                                    <span className="text-gray-600">{t('recus', 'show_reservation_client', 'Client')}: </span>
                                    <span className="font-medium">{reservationInfo.client}</span>
                                </div>
                                {(reservationInfo.check_in || reservationInfo.check_out) && (
                                    <div className="sm:col-span-2">
                                        <span className="text-gray-600">{t('recus', 'show_reservation_dates', 'Dates')}: </span>
                                        <span className="font-medium">
                                            {reservationInfo.check_in ?? '?'} → {reservationInfo.check_out ?? '?'}
                                        </span>
                                    </div>
                                )}
                                {reservationInfo.contract_id && (
                                    <div className="sm:col-span-2">
                                        <span className="text-gray-600">{t('recus', 'show_reservation_contract', 'N° de contrat')}: </span>
                                        <span className="font-medium">{reservationInfo.contract_id}</span>
                                    </div>
                                )}
                            </div>
                        </div>
                    )}
                </div>

                {/* Signature section — two-column layout matching the contract:
                    LEFT  → company cachet (mandataire)
                    RIGHT → receiver's signature (or signing pad / empty line) */}
                <section className="mt-10 flex flex-col items-start justify-between gap-10 md:flex-row">
                    {/* LEFT: company cachet / agent signature */}
                    <div className="text-center">
                        <h3 className="mb-2 text-base font-semibold text-black">
                            Signature et cachet du mandataire
                        </h3>
                        <img
                            src={stampUrl}
                            alt="Cachet de la société"
                            className="mx-auto h-48 w-64 object-contain"
                        />
                        {companyInfo?.companyName && (
                            <p className="mt-2 text-xs font-medium text-gray-700">{companyInfo.companyName}</p>
                        )}
                        {companyInfo?.matricule && (
                            <p className="text-xs text-gray-500">M.F: {companyInfo.matricule}</p>
                        )}
                    </div>

                    {/* RIGHT: receiver signature — shown when there's someone
                        meant to sign, has already signed, OR we still need to
                        pick a receiver for a pending receipt (created via the
                        Encaisser "avec signature" flow). */}
                    {(receiverName || signatureUrl || needsReceiver) && (
                    <div className="text-center">
                        <h3 className="mb-2 text-base font-semibold text-black">
                            {receiverName
                                ? t('recus', 'show_signature_of', 'Signature du receveur — :name').replace(':name', receiverName)
                                : 'Signature du receveur'}
                        </h3>
                        {needsReceiver && (
                            <div className="mt-2 rounded-md border border-emerald-300 bg-emerald-50 p-4 text-left print:hidden">
                                <p className="mb-3 text-sm font-medium text-emerald-900">
                                    À qui ce reçu est-il destiné ? Choisissez un membre de l'équipe pour collecter sa signature.
                                </p>
                                <div className="mb-3 max-w-sm">
                                    <Label className="mb-1 block text-xs text-emerald-800">Receveur</Label>
                                    <select
                                        value={pickedReceiverId}
                                        onChange={(e) => setPickedReceiverId(e.target.value)}
                                        className="h-10 w-full rounded-md border border-emerald-200 bg-white px-2 text-sm"
                                    >
                                        <option value="">— Choisir un receveur —</option>
                                        {(receivers ?? []).map((r) => (
                                            <option key={r.id} value={r.id}>{r.name}</option>
                                        ))}
                                    </select>
                                    {(receivers ?? []).length === 0 && (
                                        <p className="mt-1 text-xs text-amber-700">
                                            Aucun membre n'a de PIN défini. Allez dans Équipe → Utilisateurs pour en ajouter.
                                        </p>
                                    )}
                                    {errors?.receiver_user_id && (
                                        <p className="mt-1 text-xs text-red-600">{errors.receiver_user_id}</p>
                                    )}
                                </div>
                                <Button
                                    type="button"
                                    onClick={assignReceiver}
                                    disabled={!pickedReceiverId || assigningReceiver}
                                    className="bg-emerald-700 text-white hover:bg-emerald-800"
                                >
                                    {assigningReceiver ? 'Assignation…' : 'Assigner le receveur'}
                                </Button>
                            </div>
                        )}
                        {signedAt && (
                            <p className="mb-2 text-sm text-gray-600">
                                {t('recus', 'show_signed_at', 'Signé le :')} {signedAt}
                            </p>
                        )}

                        {needsSignature ? (
                            <div className="mt-2 rounded-md border border-amber-300 bg-amber-50 p-4 text-left print:hidden">
                                <p className="mb-3 text-sm font-medium text-amber-900">
                                    {t('recus', 'show_sign_prompt', ':name — saisissez votre code PIN et signez ci-dessous pour confirmer la réception.').replace(':name', receiverName ?? '')}
                                </p>
                                {receiptBlocked ? (
                                    <div className="space-y-2">
                                        <p className="text-sm font-medium text-red-700">
                                            {t('recus', 'show_blocked_banner', 'Reçu bloqué — :attempts tentatives de signature frauduleuses détectées le :at.')
                                                .replace(':attempts', String(receipt.signature_attempts ?? 5))
                                                .replace(
                                                    ':at',
                                                    receiptBlockedAt
                                                        ? new Date(receiptBlockedAt).toLocaleString(dateLocale, {
                                                              hour: '2-digit',
                                                              minute: '2-digit',
                                                              day: '2-digit',
                                                              month: '2-digit',
                                                          })
                                                        : '—',
                                                )}
                                        </p>
                                        <p className="text-sm text-red-600">
                                            {t('recus', 'show_blocked_for_receiver', "Quelqu'un a tenté de signer ce reçu à votre place et a été bloqué. Si vous n'avez pas reconnu cette tentative, prévenez l'administration.")}
                                        </p>
                                    </div>
                                ) : (
                                    <>
                                        <div className="mb-3 max-w-[200px]">
                                            <Label>{t('recus', 'show_pin_label', 'Code PIN')}</Label>
                                            <Input
                                                type="password"
                                                inputMode="numeric" pattern="\d{4}" maxLength={4}
                                                autoComplete="one-time-code"
                                                value={pin}
                                                onChange={e => setPin(e.target.value.replace(/\D/g, '').slice(0, 4))}
                                                className="text-center text-lg tracking-widest"
                                            />
                                            {errors?.pin && <p className="mt-1 text-sm text-red-600">{errors.pin}</p>}
                                        </div>
                                        <div ref={sigWrapRef} className="relative h-48 w-full overflow-hidden rounded-md border border-gray-300 bg-white touch-none">
                                            <SignaturePad
                                                ref={sigPadRef}
                                                canvasProps={{ className: 'block h-full w-full', style: { touchAction: 'none' } }}
                                            />
                                        </div>
                                        {errors?.signature && <p className="mt-1 text-sm text-red-600">{errors.signature}</p>}
                                        {localError && <p className="mt-1 text-sm text-red-600">{localError}</p>}
                                        <div className="mt-3 flex gap-2">
                                            <Button type="button" variant="outline" onClick={() => sigPadRef.current?.clear()}>{t('recus', 'show_clear', 'Effacer')}</Button>
                                            <Button type="button" onClick={handleSign} disabled={submitting}>
                                                {submitting ? t('recus', 'show_saving', 'Enregistrement...') : t('recus', 'show_confirm_sign', 'Confirmer & signer')}
                                            </Button>
                                        </div>
                                    </>
                                )}
                            </div>
                        ) : signatureUrl ? (
                            <img src={signatureUrl} alt="Signature" className="mx-auto h-48 w-64 rounded border border-gray-400 object-contain" />
                        ) : (
                            <div className="mx-auto mt-12 h-16 w-64 border-b border-gray-400" />
                        )}
                    </div>
                    )}
                </section>

                {/* Footer */}
                <div className="mt-10 border-t pt-4 text-center text-sm text-gray-600">
                    <p><strong>The Landlord</strong></p>
                    <p>Code T.V.A : 1631526MA000</p>
                    <p>Email : <a href="mailto:contact@thelandlord.tn">contact@thelandlord.tn</a></p>
                    <p>Téléphone : +216 58 59 59 00</p>
                </div>
            </div>
        </>
    );
}

