import { Button } from '@/components/ui/button';
import { useTranslation } from '@/hooks/use-translation';
import { Head, Link, router, usePage } from '@inertiajs/react';
import { ArrowLeft, ExternalLink, Printer } from 'lucide-react';

interface Statement {
    reservation_id: number;
    contract_id: string | null;
    client: string;
    property: string;
    property_public_name: string;
    check_in: string | null;
    check_out: string | null;
    currency: string;
    total_to_pay: string;
    already_paid: string;
    left_to_pay: string;
}

interface PaymentRow {
    id: number;
    date: string;
    amount: string;
    currency: string;
    original_amount?: string | null;
    original_currency?: string | null;
    payment_mode: string;
    remark: string | null;
    collected_by: string;
    signed_by: string | null;
    signature_status: string | null;
    receipt_encrypted_id: string | null;
}

interface Props {
    statement: Statement;
    payments: PaymentRow[];
    isAuthenticated: boolean;
    encryptedId: string;
    stampUrl: string;
    companyInfo: { companyName: string; matricule: string; ville: string; address: string; zip_code: string };
}

const modeLabel = (m: string, locale: string) => {
    const fr: Record<string, string> = { CASH: 'Espèces', CHÈQUE: 'Chèque', VIREMENT: 'Virement', PAYMEE: 'Paymee', TPE: 'TPE' };
    const en: Record<string, string> = { CASH: 'Cash', CHÈQUE: 'Cheque', VIREMENT: 'Transfer', PAYMEE: 'Paymee', TPE: 'POS' };
    return (locale === 'en' ? en : fr)[m] ?? m;
};

const signatureChip = (status: string | null, locale: string) => {
    if (status === 'signed') {
        return (
            <span className="rounded-full bg-green-100 px-2 py-0.5 text-xs font-medium text-green-700">{locale === 'en' ? 'Signed' : 'Signé'}</span>
        );
    }
    if (status === 'pending') {
        return (
            <span className="rounded-full bg-amber-100 px-2 py-0.5 text-xs font-medium text-amber-700">
                {locale === 'en' ? 'Pending' : 'En attente'}
            </span>
        );
    }
    return <span className="text-muted-foreground text-xs">—</span>;
};

export default function ReleveStatement() {
    const { statement, payments, isAuthenticated, stampUrl, companyInfo } = usePage<Props>().props;
    const { locale } = useTranslation();
    const fr = locale !== 'en';

    return (
        <>
            <Head title={fr ? 'Relevé des paiements' : 'Payment statement'} />

            {/* Print-only styles: hide app chrome */}
            <style>{`
                @media print {
                    body { background: white !important; }
                    [data-slot="sidebar"], header { display: none !important; }
                    main { padding: 0 !important; }
                }
            `}</style>

            {isAuthenticated && (
                <div style={{ maxWidth: '900px', margin: '0 auto' }} className="px-4 pt-4 print:hidden">
                    <div className="flex items-center justify-between">
                        <Button size="sm" variant="ghost" onClick={() => router.visit(`/recouvrements/${statement.reservation_id}`)}>
                            <ArrowLeft className="mr-1 h-4 w-4" />
                            {fr ? 'Retour à la réservation' : 'Back to reservation'}
                        </Button>
                        <Button size="sm" variant="outline" onClick={() => window.print()}>
                            <Printer className="mr-1 h-4 w-4" />
                            {fr ? 'Imprimer' : 'Print'}
                        </Button>
                    </div>
                </div>
            )}

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

                {/* Title */}
                <h2 className="mb-1 text-center text-2xl font-bold">{fr ? 'Relevé des paiements' : 'Payment statement'}</h2>
                <p className="mb-6 text-center text-sm text-gray-500">
                    {fr ? 'Récapitulatif des sommes encaissées pour la réservation' : 'Summary of amounts collected for the reservation'}
                </p>

                {/* Reservation block */}
                <div className="mb-6 grid gap-2 rounded-md border border-gray-200 bg-gray-50 p-4 text-sm sm:grid-cols-2">
                    <div>
                        <span className="text-gray-600">{fr ? 'Logement' : 'Property'}: </span>
                        <span className="font-medium">{statement.property || '—'}</span>
                        {statement.property_public_name && statement.property_public_name !== statement.property && (
                            <span className="ml-1 text-xs text-gray-500">({statement.property_public_name})</span>
                        )}
                    </div>
                    <div>
                        <span className="text-gray-600">{fr ? 'Client' : 'Client'}: </span>
                        <span className="font-medium">{statement.client}</span>
                    </div>
                    {(statement.check_in || statement.check_out) && (
                        <div className="sm:col-span-2">
                            <span className="text-gray-600">{fr ? 'Séjour' : 'Stay'}: </span>
                            <span className="font-medium">
                                {statement.check_in ?? '?'} → {statement.check_out ?? '?'}
                            </span>
                        </div>
                    )}
                    {statement.contract_id && (
                        <div className="sm:col-span-2">
                            <span className="text-gray-600">{fr ? 'N° de contrat' : 'Contract #'}: </span>
                            <span className="font-medium">{statement.contract_id}</span>
                        </div>
                    )}
                </div>

                {/* Totals */}
                <div className="mb-6 grid gap-2 rounded-md border bg-white p-4 text-sm sm:text-base">
                    <div className="flex items-center justify-between">
                        <span className="text-gray-600">{fr ? 'Total à payer' : 'Total to pay'}</span>
                        <span className="font-medium">
                            {statement.total_to_pay} {statement.currency}
                        </span>
                    </div>
                    <div className="flex items-center justify-between">
                        <span className="text-gray-600">{fr ? 'Déjà encaissé' : 'Already collected'}</span>
                        <span className="font-medium">
                            {statement.already_paid} {statement.currency}
                        </span>
                    </div>
                    <div className="mt-1 flex items-center justify-between border-t pt-2 text-base font-semibold">
                        <span>{fr ? 'Reste à encaisser' : 'Balance due'}</span>
                        <span className={Number(statement.left_to_pay) > 0 ? 'text-amber-700' : 'text-green-700'}>
                            {statement.left_to_pay} {statement.currency}
                        </span>
                    </div>
                </div>

                {/* Payments table */}
                <h3 className="mb-2 text-lg font-semibold">{fr ? 'Détail des encaissements' : 'Payment breakdown'}</h3>

                {payments.length === 0 ? (
                    <p className="text-sm text-gray-500">
                        {fr ? 'Aucun paiement enregistré pour cette réservation.' : 'No payment recorded for this reservation yet.'}
                    </p>
                ) : (
                    <div className="overflow-hidden rounded-md border">
                        <table className="w-full text-sm">
                            <thead className="bg-muted/50 text-left">
                                <tr>
                                    <th className="text-muted-foreground px-3 py-2 font-medium">{fr ? 'Date' : 'Date'}</th>
                                    <th className="text-muted-foreground px-3 py-2 font-medium">{fr ? 'Montant' : 'Amount'}</th>
                                    <th className="text-muted-foreground px-3 py-2 font-medium">{fr ? 'Mode' : 'Method'}</th>
                                    <th className="text-muted-foreground px-3 py-2 font-medium">{fr ? 'Reçu par' : 'Collected by'}</th>
                                    <th className="text-muted-foreground px-3 py-2 font-medium">{fr ? 'Signé par' : 'Signed by'}</th>
                                    <th className="text-muted-foreground px-3 py-2 font-medium">{fr ? 'Note' : 'Note'}</th>
                                    <th className="text-muted-foreground px-3 py-2 font-medium">{fr ? 'Statut' : 'Status'}</th>
                                    <th className="text-muted-foreground px-3 py-2 text-right font-medium print:hidden">{fr ? 'Reçu' : 'Receipt'}</th>
                                </tr>
                            </thead>
                            <tbody className="divide-border divide-y">
                                {payments.map((p) => (
                                    <tr key={p.id}>
                                        <td className="px-3 py-2 whitespace-nowrap">{p.date}</td>
                                        <td className="px-3 py-2 font-semibold tabular-nums">
                                            {p.amount} <span className="text-muted-foreground text-xs font-normal">{p.currency}</span>
                                        </td>
                                        <td className="px-3 py-2">{modeLabel(p.payment_mode, locale)}</td>
                                        <td className="px-3 py-2">{p.collected_by}</td>
                                        <td className="px-3 py-2">{p.signed_by ?? '—'}</td>
                                        <td className="text-muted-foreground max-w-[180px] truncate px-3 py-2">{p.remark ?? '—'}</td>
                                        <td className="px-3 py-2">{signatureChip(p.signature_status, locale)}</td>
                                        <td className="px-3 py-2 text-right print:hidden">
                                            {p.receipt_encrypted_id ? (
                                                <Link
                                                    href={route('recus.show', p.receipt_encrypted_id)}
                                                    className="text-primary inline-flex items-center gap-1 text-xs hover:underline"
                                                >
                                                    {fr ? 'Voir' : 'View'} <ExternalLink className="h-3 w-3" />
                                                </Link>
                                            ) : (
                                                <span className="text-muted-foreground text-xs">—</span>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                            <tfoot>
                                <tr className="bg-muted/30 border-t">
                                    <td className="px-3 py-2 font-semibold" colSpan={1}>
                                        {fr ? 'Total' : 'Total'}
                                    </td>
                                    <td className="px-3 py-2 font-bold tabular-nums">
                                        {statement.already_paid}{' '}
                                        <span className="text-muted-foreground text-xs font-normal">{statement.currency}</span>
                                    </td>
                                    <td colSpan={6}></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                )}

                {/* Mandataire signature & stamp */}
                <div className="mt-10 flex justify-center">
                    <div className="text-center">
                        <p className="mb-2 text-sm font-semibold">
                            {(fr ? 'Pour ' : 'For ') + (companyInfo?.companyName || 'TheLandlord')}
                        </p>
                        <img
                            src={stampUrl}
                            alt={fr ? 'Signature & cachet' : 'Signature & stamp'}
                            style={{ maxHeight: '120px' }}
                            className="mx-auto"
                        />
                        <p className="mt-1 text-xs text-gray-500">{fr ? 'Signature et cachet' : 'Signature and stamp'}</p>
                        {companyInfo?.matricule && (
                            <p className="text-xs text-gray-500">M.F: {companyInfo.matricule}</p>
                        )}
                    </div>
                </div>

                {/* 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>
        </>
    );
}
