import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { OwnerStayBadge } from '@/components/owner-stay-badge';
import AppLayout from '@/layouts/app-layout';
import { ActivityHistoryButton } from '@/pages/activity/components/ActivityHistoryButton';
import { type BreadcrumbItem } from '@/types';
import { Head, Link, usePage } from '@inertiajs/react';
import { AlertTriangle, ArrowLeft, ArrowRight, Building2, Mail, Pencil, Phone, Users } from 'lucide-react';

type ReservationShow = {
    id: number;
    reference: string | null;
    status: string;
    is_cancelled: boolean;
    source: string;
    is_local: boolean;
    is_owner_reservation: boolean;
    guest_name: string;
    guest_phone: string | null;
    guest_email: string | null;
    guests_number: number | null;
    property_id: number | null;
    property_name: string | null;
    property_internal_name: string | null;
    check_in: string;
    check_out: string;
    arrival_time: string | null;
    nights: number;
    arrives_today: boolean;
    currency: string | null;
    payment_status: string | null;
    created_date: string;
    last_editor: string | null;
};

type Finance = {
    billed_to_guest: number;
    collected: number;
    left_to_pay: number;
    contract_currency: string | null;
    contract_amount: number | null;
    amount: number;
    tva: number;
    ht: number;
    cleaning_fee: number;
    service_fee: number;
    commission_base: number;
    commission: number;
    commission_rate: number | null;
    owner_payout: number;
    nights: number;
    charges_per_night: number;
    fx_gap: number;
};

type PageProps = {
    reservation: ReservationShow;
    finance: Finance | null;
};

const breadcrumbs: BreadcrumbItem[] = [
    { title: 'Réservations', href: '/reservations' },
    { title: 'Fiche réservation', href: '#' },
];

const money = (value: number, currency = 'TND') =>
    `${new Intl.NumberFormat('fr-FR', { minimumFractionDigits: 3, maximumFractionDigits: 3 }).format(value)} ${currency}`;

function SectionTitle({ children }: { children: React.ReactNode }) {
    return <h2 className="text-muted-foreground mb-4 text-xs font-medium tracking-wider uppercase">{children}</h2>;
}

function Info({ label, children }: { label: string; children: React.ReactNode }) {
    return (
        <div>
            <p className="text-muted-foreground mb-1 text-xs">{label}</p>
            <div className="text-sm font-medium">{children}</div>
        </div>
    );
}

/**
 * Une ligne de la cascade financière. `operator` porte le signe (− ou =) pour
 * que la suite se lise comme un calcul et pas comme une liste de champs.
 */
function Line({
    label,
    value,
    operator,
    subtotal = false,
    accent = false,
    hint,
}: {
    label: string;
    value: string;
    operator?: '−' | '=';
    subtotal?: boolean;
    accent?: boolean;
    hint?: string;
}) {
    return (
        <div className={`flex items-baseline justify-between gap-4 py-2.5 ${subtotal ? 'border-t' : ''}`}>
            <div className="flex min-w-0 items-baseline gap-2">
                <span className={`text-muted-foreground w-3 shrink-0 text-sm ${operator === '=' ? 'font-medium' : ''}`}>{operator ?? ''}</span>
                <div className="min-w-0">
                    <span className={`text-sm ${accent ? 'text-primary font-medium' : subtotal ? 'font-medium' : 'text-muted-foreground'}`}>
                        {label}
                    </span>
                    {hint && <span className="text-muted-foreground ml-2 text-xs">{hint}</span>}
                </div>
            </div>
            <span className={`shrink-0 text-sm tabular-nums ${accent ? 'text-primary font-medium' : subtotal ? 'font-medium' : ''}`}>
                {value}
            </span>
        </div>
    );
}

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

    const arrival = reservation.arrival_time ? `${reservation.check_in} à ${reservation.arrival_time}` : reservation.check_in;

    return (
        <AppLayout breadcrumbs={breadcrumbs}>
            <Head title={`Réservation — ${reservation.guest_name}`} />

            <div className="flex h-full flex-1 flex-col gap-5 p-3 lg:p-5">
                <div className="flex flex-wrap items-center gap-3">
                    <Button asChild variant="outline" size="icon">
                        <Link href="/reservations" aria-label="Retour aux réservations">
                            <ArrowLeft className="h-4 w-4" />
                        </Link>
                    </Button>
                    <div className="min-w-0 flex-1">
                        <h1 className="truncate text-xl font-medium">Détails de la réservation</h1>
                        {reservation.reference && <p className="text-muted-foreground mt-0.5 text-xs">N° {reservation.reference}</p>}
                    </div>
                    <Badge variant={reservation.is_cancelled ? 'destructive' : 'default'}>{reservation.status}</Badge>
                    {reservation.payment_status && <Badge variant="outline">{reservation.payment_status}</Badge>}
                    {/* TL-293 — le journal d'activité filtré sur ce séjour (absent sans accès au journal). */}
                    <ActivityHistoryButton subject={`Reservation:${reservation.id}`} dataTour="reservation-show-history" />
                    <Button asChild variant="outline" size="sm">
                        <Link href={`/reservations/edit/${reservation.id}`}>
                            <Pencil className="h-4 w-4" />
                            Modifier
                        </Link>
                    </Button>
                </div>

                {reservation.arrives_today && !reservation.is_cancelled && (
                    <div className="border-warning/40 bg-warning/10 flex items-center gap-2 rounded-xl border px-4 py-2.5">
                        <AlertTriangle className="text-warning h-4 w-4 shrink-0" />
                        <span className="text-sm font-medium">
                            Arrivée aujourd'hui
                            {reservation.arrival_time ? ` à partir de ${reservation.arrival_time}` : ''}
                        </span>
                    </div>
                )}

                <div className="grid gap-5 xl:grid-cols-3">
                    <div className="flex flex-col gap-5 xl:col-span-2">
                        <Card data-tour="reservation-show-info">
                            <CardContent>
                                <SectionTitle>Informations</SectionTitle>
                                <div className="grid gap-5 sm:grid-cols-2">
                                    <Info label="Client">
                                        <span className="flex flex-wrap items-center gap-1.5">
                                            {reservation.guest_name}
                                            {reservation.is_owner_reservation && <OwnerStayBadge size="sm" />}
                                        </span>
                                    </Info>
                                    <Info label="Logement">
                                        <span className="flex items-start gap-1.5">
                                            <Building2 className="text-muted-foreground mt-0.5 h-3.5 w-3.5 shrink-0" />
                                            <span>
                                                {reservation.property_id && reservation.property_name ? (
                                                    <Link href={`/logements/show/${reservation.property_id}`} className="hover:underline">
                                                        {reservation.property_name}
                                                    </Link>
                                                ) : (
                                                    (reservation.property_name ?? 'Logement non identifié')
                                                )}
                                                {reservation.property_internal_name && (
                                                    <span className="text-muted-foreground block text-xs font-normal">
                                                        {reservation.property_internal_name}
                                                    </span>
                                                )}
                                            </span>
                                        </span>
                                    </Info>
                                    <Info label="Arrivée">{arrival}</Info>
                                    <Info label="Départ">{reservation.check_out}</Info>
                                    <Info label="Nuits">{reservation.nights}</Info>
                                    <Info label="Source">{reservation.source}</Info>
                                    <Info label="Voyageurs">
                                        <span className="flex items-center gap-1.5">
                                            <Users className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
                                            {reservation.guests_number ?? 'non précisé'}
                                        </span>
                                    </Info>
                                    {reservation.guest_phone && (
                                        <Info label="Téléphone">
                                            <a href={`tel:${reservation.guest_phone}`} className="flex items-center gap-1.5 hover:underline">
                                                <Phone className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
                                                {reservation.guest_phone}
                                            </a>
                                        </Info>
                                    )}
                                    {reservation.guest_email && (
                                        <Info label="Email">
                                            <a href={`mailto:${reservation.guest_email}`} className="flex items-center gap-1.5 hover:underline">
                                                <Mail className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
                                                <span className="truncate">{reservation.guest_email}</span>
                                            </a>
                                        </Info>
                                    )}
                                </div>
                            </CardContent>
                        </Card>

                        <Card data-tour="reservation-show-finance">
                            <CardContent>
                                <SectionTitle>Détail financier</SectionTitle>

                                {finance ? (
                                    <>
                                        {finance.contract_currency && finance.contract_currency !== 'TND' && finance.contract_amount !== null && (
                                            <div className="bg-muted/50 mb-3 flex items-center gap-2 rounded-lg px-3 py-2 text-xs">
                                                <span className="text-muted-foreground">Contrat en devise</span>
                                                <span className="font-medium tabular-nums">
                                                    {money(finance.contract_amount, finance.contract_currency)}
                                                </span>
                                                <ArrowRight className="text-muted-foreground h-3 w-3" />
                                                <span className="font-medium tabular-nums">{money(finance.amount)}</span>
                                                <span className="text-muted-foreground">au taux propriétaire</span>
                                            </div>
                                        )}

                                        <Line label="Montant du contrat" value={money(finance.amount)} subtotal />
                                        <Line label="TVA" value={money(finance.tva)} operator="−" />
                                        <Line label="Montant HT" value={money(finance.ht)} operator="=" subtotal />
                                        <Line label="Frais de ménage" value={money(finance.cleaning_fee)} operator="−" />
                                        <Line label="Service fee" value={money(finance.service_fee)} operator="−" />
                                        <Line label="Base commissionnable" value={money(finance.commission_base)} operator="=" subtotal />
                                        <Line
                                            label="Commission The Landlord"
                                            hint={finance.commission_rate !== null ? `${finance.commission_rate} %` : undefined}
                                            value={money(finance.commission)}
                                            operator="−"
                                        />
                                                        <Line
                                            label="Loyer net propriétaire"
                                            value={money(finance.owner_payout)}
                                            operator="="
                                            subtotal
                                            accent
                                        />

                                        <div className="text-muted-foreground mt-3 border-t pt-3 text-xs">
                                            Prix / nuit : <span className="tabular-nums">{money(finance.charges_per_night)}</span> sur{' '}
                                            {finance.nights} nuit{finance.nights > 1 ? 's' : ''} (base commissionnable)
                                        </div>
                                    </>
                                ) : (
                                    <p className="text-muted-foreground text-sm">
                                        Décomposition indisponible — le paramétrage de cette réservation est incomplet.
                                    </p>
                                )}
                            </CardContent>
                        </Card>
                    </div>

                    <div className="flex flex-col gap-5" data-tour="reservation-show-money">
                        {finance && (
                            <>
                                {/* Deux accents de marque seulement, sur les deux chiffres
                                    qu'on vient chercher : ce que touche le propriétaire, et
                                    ce que doit encore le client. */}
                                <Card className="border-l-primary border-l-4">
                                    <CardContent>
                                        <SectionTitle>Loyer net propriétaire</SectionTitle>
                                        <p className="text-primary text-3xl font-medium tabular-nums">{money(finance.owner_payout)}</p>
                                        <p className="text-muted-foreground mt-2 text-xs">
                                            Après TVA, ménage, service fee et commission.
                                        </p>
                                    </CardContent>
                                </Card>

                                <Card className="border-l-secondary border-l-4">
                                    <CardContent>
                                        <SectionTitle>Encaissement client</SectionTitle>
                                        <div className="flex flex-col">
                                            <Line label="Facturé au client" value={money(finance.billed_to_guest)} subtotal />
                                            <Line label="Déjà encaissé" value={money(finance.collected)} />
                                            <Line label="Reste à payer" value={money(finance.left_to_pay)} operator="=" subtotal />
                                        </div>
                                        {finance.fx_gap !== 0 && (
                                            <p className="text-muted-foreground mt-3 border-t pt-3 text-xs">
                                                Écart de <span className="tabular-nums">{money(finance.fx_gap)}</span> avec le montant du
                                                contrat ci-contre : le client est facturé au taux client, le propriétaire calculé au taux
                                                propriétaire.
                                            </p>
                                        )}
                                    </CardContent>
                                </Card>
                            </>
                        )}

                        <Card>
                            <CardContent>
                                <SectionTitle>Suivi</SectionTitle>
                                <div className="flex flex-col gap-3">
                                    <Info label="Créée le">{reservation.created_date}</Info>
                                    {reservation.last_editor && <Info label="Dernière modification">{reservation.last_editor}</Info>}
                                    <Info label="Origine">{reservation.is_local ? 'Saisie dans le manager' : reservation.source}</Info>
                                </div>
                            </CardContent>
                        </Card>
                    </div>
                </div>
            </div>
        </AppLayout>
    );
}
