import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import AppLayout from '@/layouts/app-layout';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, usePage } from '@inertiajs/react';
import {
    ArrowLeft,
    Banknote,
    Building2,
    Calendar,
    CheckCircle2,
    ChevronDown,
    ChevronUp,
    ClipboardList,
    CreditCard,
    ExternalLink,
    Hash,
    Landmark,
    Link2,
    ListChecks,
    MessageSquare,
    Receipt as ReceiptIcon,
    User as UserIcon,
    UserCheck,
    XCircle,
} from 'lucide-react';
import * as React from 'react';

interface Receipt {
    id: number;
    encrypted_id: string;
    date: string | null;
    amount: number;
    currency: string | null;
    payment_mode: string | null;
    note: string | null;
    signature_status: string | null;
    signed_at: string | null;
    signature_path: string | null;
    giver_name: string | null;
    receiver_name: string | null;
    created_by_name: string | null;
    created_at: string | null;
}

interface Ligne {
    id: number;
    encrypted_id: string;
    paid_at: string | null;
    created_at: string | null;
    amount: number;
    currency: string | null;
    payment_mode: string | null;
    check_number: string | null;
    bank: string | null;
    remark: string | null;
    signature_status: string | null;
    signed_at: string | null;
    client: { id: number; full_name: string } | null;
    property: { id: number; name: string } | null;
    reservation: { id: number; reservation_id: string | null; encrypted_id: string } | null;
    creator: string | null;
    recipient: string | null;
    receipt: Receipt | null;
}

interface PageProps {
    ligne: Ligne;
    [k: string]: unknown;
}

function frDate(value: string | null, withTime = false): string {
    if (!value) return '—';
    const d = new Date(value);
    if (Number.isNaN(d.getTime())) return value;
    const dd = String(d.getDate()).padStart(2, '0');
    const mm = String(d.getMonth() + 1).padStart(2, '0');
    const yy = d.getFullYear();
    const base = `${dd}/${mm}/${yy}`;
    if (!withTime) return base;
    const h = String(d.getHours()).padStart(2, '0');
    const min = String(d.getMinutes()).padStart(2, '0');
    const s = String(d.getSeconds()).padStart(2, '0');
    return `${base} ${h}:${min}:${s}`;
}

function fmtMoney(n: number, currency: string | null) {
    return n.toLocaleString('fr-TN', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' ' + (currency || 'TND');
}

function SignaturePill({ status, signedAt }: { status: string | null; signedAt: string | null }) {
    if (status === 'signed') {
        return (
            <span className="text-emerald-700 inline-flex items-center gap-1 rounded-full bg-emerald-50 px-2 py-0.5 text-xs font-medium">
                <CheckCircle2 className="h-3 w-3" />
                Signé{signedAt ? ` le ${frDate(signedAt, true)}` : ''}
            </span>
        );
    }
    if (status === 'cancelled') {
        return (
            <span className="text-red-700 inline-flex items-center gap-1 rounded-full bg-red-50 px-2 py-0.5 text-xs font-medium">
                <XCircle className="h-3 w-3" />
                Annulé
            </span>
        );
    }
    if (status === 'pending') {
        return (
            <span className="text-amber-700 inline-flex items-center gap-1 rounded-full bg-amber-50 px-2 py-0.5 text-xs font-medium">
                En attente de signature
            </span>
        );
    }
    return null;
}

function ModePill({ mode }: { mode: string | null }) {
    if (!mode) return null;
    const upper = mode.toUpperCase();
    const colors: Record<string, string> = {
        CASH:    'bg-emerald-50 text-emerald-700',
        CHÈQUE:  'bg-sky-50 text-sky-700',
        CHEQUE:  'bg-sky-50 text-sky-700',
        VIREMENT:'bg-indigo-50 text-indigo-700',
        TPE:     'bg-purple-50 text-purple-700',
        CARTE:   'bg-purple-50 text-purple-700',
        PAYMEE:  'bg-pink-50 text-pink-700',
    };
    const cls = colors[upper] ?? 'bg-slate-100 text-slate-700';
    return (
        <span className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium ${cls}`}>
            <CreditCard className="h-3 w-3" />
            {upper}
        </span>
    );
}

export default function Show() {
    const { ligne } = usePage<PageProps>().props;

    const breadcrumbs: BreadcrumbItem[] = [
        { title: 'Lignes des paiements', href: '/paiements/lignes' },
        { title: `Ligne #${ligne.id}`, href: `/paiements/lignes/${ligne.id}` },
    ];

    const hasTime = ligne.paid_at && !ligne.paid_at.endsWith('00:00:00');
    const paymentTime = hasTime ? frDate(ligne.paid_at ?? ligne.created_at, true).split(' ')[1] : null;

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`Recouvrement #${ligne.id}`} />

            <div className="flex h-full flex-1 flex-col gap-4 p-3 sm:p-4 lg:p-6">
                {/* Header bar */}
                <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                    <div className="flex items-center gap-3">
                        <Button variant="ghost" size="icon" asChild>
                            <Link href="/paiements/lignes">
                                <ArrowLeft className="h-5 w-5" />
                            </Link>
                        </Button>
                        <div>
                            <h1 className="text-2xl font-semibold tracking-tight">Recouvrement #{ligne.id}</h1>
                            <p className="text-muted-foreground text-sm">Détail de la ligne de paiement</p>
                        </div>
                    </div>
                    {ligne.reservation?.encrypted_id && (
                        <Button asChild variant="outline">
                            <a
                                href={`/releve-paiements/${ligne.reservation.encrypted_id}`}
                                target="_blank"
                                rel="noopener noreferrer"
                            >
                                <ListChecks className="mr-2 h-4 w-4" />
                                Voir tous les paiements de cette réservation
                            </a>
                        </Button>
                    )}
                </div>

                {/* Hero summary card — the headline numbers at a glance */}
                <Card className="border-secondary/30 bg-gradient-to-r from-emerald-50/40 via-white to-white">
                    <CardContent className="grid grid-cols-1 gap-6 px-6 py-5 sm:grid-cols-[1fr_auto_auto] sm:items-center">
                        <div>
                            <span className="text-muted-foreground text-xs uppercase tracking-wide">Montant payé</span>
                            <div className="text-emerald-700 text-3xl font-bold tabular-nums">
                                {fmtMoney(ligne.amount, ligne.currency)}
                            </div>
                            <div className="mt-1 flex flex-wrap items-center gap-2">
                                <ModePill mode={ligne.payment_mode} />
                                <SignaturePill status={ligne.signature_status} signedAt={ligne.signed_at} />
                            </div>
                        </div>
                        <div className="hidden sm:block sm:h-12 sm:w-px sm:bg-slate-200" />
                        <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-6">
                            <InlineStat
                                icon={<Calendar className="h-4 w-4" />}
                                label="Date du paiement"
                                value={frDate(ligne.paid_at ?? ligne.created_at)}
                                hint={paymentTime ?? undefined}
                            />
                            {ligne.reservation && (
                                <InlineStat
                                    icon={<Hash className="h-4 w-4" />}
                                    label="Réservation"
                                    value={
                                        <Link
                                            href={`/reservations/edit/${ligne.reservation.id}`}
                                            className="text-sky-700 inline-flex items-center gap-1 underline"
                                        >
                                            {ligne.reservation.reservation_id ?? ligne.reservation.id}
                                            <ExternalLink className="h-3 w-3" />
                                        </Link>
                                    }
                                />
                            )}
                        </div>
                    </CardContent>
                </Card>

                {/* ── Section: Informations du paiement ──────────────────────── */}
                <CollapsibleSection
                    title="Informations du paiement"
                    icon={<Banknote className="h-5 w-5 text-emerald-600" />}
                    defaultOpen
                >
                    <div className="grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2">
                        <Field
                            icon={<Calendar className="h-4 w-4" />}
                            label="Date"
                            value={frDate(ligne.paid_at ?? ligne.created_at)}
                        />
                        {paymentTime && <Field icon={<Calendar className="h-4 w-4" />} label="Heure" value={paymentTime} />}
                        <Field
                            icon={<Banknote className="h-4 w-4" />}
                            label="Montant"
                            value={
                                <span className="text-emerald-700 text-lg font-semibold tabular-nums">
                                    {fmtMoney(ligne.amount, ligne.currency)}
                                </span>
                            }
                        />
                        <Field
                            icon={<CreditCard className="h-4 w-4" />}
                            label="Mode de paiement"
                            value={<ModePill mode={ligne.payment_mode} />}
                        />
                        {(ligne.check_number || ligne.payment_mode?.toUpperCase().includes('CHÈQUE')) && (
                            <Field icon={<Hash className="h-4 w-4" />} label="N° chèque" value={ligne.check_number} />
                        )}
                        {(ligne.bank || ligne.payment_mode?.toUpperCase().includes('CHÈQUE') || ligne.payment_mode?.toUpperCase().includes('VIREMENT')) && (
                            <Field icon={<Landmark className="h-4 w-4" />} label="Banque" value={ligne.bank} />
                        )}
                        <Field
                            icon={<CheckCircle2 className="h-4 w-4" />}
                            label="Statut signature"
                            value={<SignaturePill status={ligne.signature_status} signedAt={ligne.signed_at} /> ?? '—'}
                        />
                        {ligne.remark && (
                            <Field
                                icon={<MessageSquare className="h-4 w-4" />}
                                label="Remarque"
                                value={ligne.remark}
                                className="sm:col-span-2"
                            />
                        )}
                    </div>
                </CollapsibleSection>

                {/* ── Section: Lien réservation ──────────────────────────────── */}
                <CollapsibleSection
                    title="Lien réservation"
                    icon={<Link2 className="h-5 w-5 text-sky-600" />}
                    defaultOpen
                >
                    <div className="grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2">
                        <Field
                            icon={<UserIcon className="h-4 w-4" />}
                            label="Client"
                            value={
                                ligne.client ? (
                                    <Link
                                        href={`/clients/show/${ligne.client.id}`}
                                        className="text-sky-700 inline-flex items-center gap-1 underline"
                                    >
                                        {ligne.client.full_name} <ExternalLink className="h-3 w-3" />
                                    </Link>
                                ) : null
                            }
                        />
                        <Field
                            icon={<Building2 className="h-4 w-4" />}
                            label="Logement"
                            value={
                                ligne.property ? (
                                    <Link
                                        href={`/logements/show/${ligne.property.id}`}
                                        className="text-sky-700 inline-flex items-center gap-1 underline"
                                    >
                                        {ligne.property.name} <ExternalLink className="h-3 w-3" />
                                    </Link>
                                ) : null
                            }
                        />
                        <Field
                            icon={<Hash className="h-4 w-4" />}
                            label="Réservation"
                            value={
                                ligne.reservation ? (
                                    <Link
                                        href={`/reservations/edit/${ligne.reservation.id}`}
                                        className="text-sky-700 inline-flex items-center gap-1 underline"
                                    >
                                        {ligne.reservation.reservation_id ?? ligne.reservation.id}
                                        <ExternalLink className="h-3 w-3" />
                                    </Link>
                                ) : null
                            }
                        />
                        <Field
                            icon={<ReceiptIcon className="h-4 w-4" />}
                            label="Reçu lié"
                            value={ligne.receipt ? `Reçu #${ligne.receipt.id}` : 'Aucun'}
                        />
                    </div>
                </CollapsibleSection>

                {/* ── Section: Reçu lié (only if a receipt exists) ───────────── */}
                {ligne.receipt && <ReceiptBreakdown receipt={ligne.receipt} />}

                {/* ── Section: Suivi ─────────────────────────────────────────── */}
                {/* Only shown when there's NO linked receipt — otherwise the
                    Reçu section already covers giver / receiver / créé par /
                    créé le and Suivi would be redundant. */}
                {!ligne.receipt && (
                    <CollapsibleSection
                        title="Suivi"
                        icon={<ClipboardList className="h-5 w-5 text-slate-600" />}
                        defaultOpen={false}
                    >
                        <div className="grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2">
                            <Field icon={<UserIcon className="h-4 w-4" />} label="Créé par" value={ligne.creator} />
                            <Field icon={<UserCheck className="h-4 w-4" />} label="Destinataire" value={ligne.recipient} />
                            <Field icon={<Calendar className="h-4 w-4" />} label="Créé le" value={frDate(ligne.created_at, true)} />
                        </div>
                    </CollapsibleSection>
                )}
            </div>
        </AppLayout>
    );
}

function ReceiptBreakdown({ receipt }: { receipt: Receipt }) {
    return (
        <CollapsibleSection
            title={`Reçu #${receipt.id}`}
            icon={<ReceiptIcon className="h-5 w-5 text-violet-600" />}
            headerAccessory={<SignaturePill status={receipt.signature_status} signedAt={receipt.signed_at} />}
            defaultOpen
        >
            <div className="grid grid-cols-1 gap-x-8 gap-y-4 sm:grid-cols-2">
                <Field
                    icon={<Banknote className="h-4 w-4" />}
                    label="Montant"
                    value={
                        <span className="text-violet-700 text-lg font-semibold tabular-nums">
                            {receipt.amount.toLocaleString('fr-TN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}{' '}
                            {receipt.currency ?? 'TND'}
                        </span>
                    }
                />
                <Field
                    icon={<CreditCard className="h-4 w-4" />}
                    label="Mode de paiement"
                    value={<ModePill mode={receipt.payment_mode} />}
                />
                <Field icon={<Calendar className="h-4 w-4" />} label="Date du reçu" value={frDate(receipt.date)} />
                <Field
                    icon={<CheckCircle2 className="h-4 w-4" />}
                    label="Statut signature"
                    value={<SignaturePill status={receipt.signature_status} signedAt={receipt.signed_at} /> ?? '—'}
                />
                <Field icon={<UserIcon className="h-4 w-4" />} label="Remis par" value={receipt.giver_name} />
                <Field icon={<UserCheck className="h-4 w-4" />} label="Remis à" value={receipt.receiver_name} />
                <Field icon={<UserIcon className="h-4 w-4" />} label="Créé par" value={receipt.created_by_name} />
                <Field icon={<Calendar className="h-4 w-4" />} label="Créé le" value={frDate(receipt.created_at, true)} />
                {receipt.note && (
                    <Field
                        icon={<MessageSquare className="h-4 w-4" />}
                        label="Note"
                        value={receipt.note}
                        className="sm:col-span-2"
                    />
                )}

                <div className="sm:col-span-2 flex flex-wrap gap-2 pt-2">
                    <Button asChild>
                        <a
                            href={`/recus/${receipt.encrypted_id}`}
                            target="_blank"
                            rel="noopener noreferrer"
                            className="inline-flex items-center"
                        >
                            <ExternalLink className="mr-2 h-4 w-4" />
                            Ouvrir le reçu
                        </a>
                    </Button>
                </div>
            </div>
        </CollapsibleSection>
    );
}

/**
 * Generic collapsible card section. Click the header to toggle the body.
 */
function CollapsibleSection({
    title,
    icon,
    headerAccessory,
    defaultOpen = true,
    children,
}: {
    title: string;
    icon?: React.ReactNode;
    headerAccessory?: React.ReactNode;
    defaultOpen?: boolean;
    children: React.ReactNode;
}) {
    const [open, setOpen] = React.useState(defaultOpen);
    return (
        <Card>
            <CardHeader
                className="cursor-pointer select-none transition-colors hover:bg-muted/30"
                onClick={() => setOpen((v) => !v)}
            >
                <CardTitle className="flex items-center justify-between gap-2">
                    <span className="flex flex-wrap items-center gap-2 text-base">
                        {icon}
                        {title}
                        {headerAccessory}
                    </span>
                    {open ? (
                        <ChevronUp className="text-muted-foreground h-5 w-5 shrink-0" />
                    ) : (
                        <ChevronDown className="text-muted-foreground h-5 w-5 shrink-0" />
                    )}
                </CardTitle>
            </CardHeader>
            {open && <CardContent>{children}</CardContent>}
        </Card>
    );
}

function InlineStat({
    icon,
    label,
    value,
    hint,
}: {
    icon: React.ReactNode;
    label: string;
    value: React.ReactNode;
    hint?: string;
}) {
    return (
        <div className="flex flex-col gap-0.5">
            <span className="text-muted-foreground inline-flex items-center gap-1.5 text-xs uppercase tracking-wide">
                {icon}
                {label}
            </span>
            <span className="text-base font-medium">{value ?? '—'}</span>
            {hint && <span className="text-muted-foreground text-xs">{hint}</span>}
        </div>
    );
}

function Field({
    icon,
    label,
    value,
    className = '',
}: {
    icon?: React.ReactNode;
    label: string;
    value: React.ReactNode;
    className?: string;
}) {
    const empty = value === null || value === undefined || value === '';
    return (
        <div className={`flex flex-col gap-1 ${className}`}>
            <span className="text-muted-foreground inline-flex items-center gap-1.5 text-xs uppercase tracking-wide">
                {icon}
                {label}
            </span>
            <span className={`break-words text-base ${empty ? 'text-muted-foreground/50' : ''}`}>
                {empty ? '—' : value}
            </span>
        </div>
    );
}
