import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Separator } from '@/components/ui/separator';
import {
    User,
    CalendarDays,
    CreditCard,
    BedDouble,
    Users,
    UtensilsCrossed,
    Clock,
    Bed,
    Calendar,
    Trash2,
    Edit,
    XCircle
} from 'lucide-react';
import { ConfirmActionAlertButton } from '@/components/core/ConfirmActionAlertButton';
import { DeleteButton } from '@/components/core/DeleteButton';
import { useState } from 'react';
import { router } from '@inertiajs/react';
import { toast } from 'sonner';


/* ─────────────────────────────────────────────
   HEADER COMPONENT
───────────────────────────────────────────── */
function Header({ booking }: any) {
    return (
        <div className="flex justify-between items-start">
            <div>
                <div className="text-lg font-semibold">
                    {booking.reference}
                </div>
                <div className="text-xs text-muted-foreground">
                    Created {new Date(booking.created_at).toLocaleString()}
                </div>
            </div>

            <span className={`uppercase text-xs font-semibold ${booking.status === 'booked' ? 'text-blue-600 ' : booking.status === 'pending' ? 'text-yellow-600' : 'destructive'}`}  >   {booking.status}    </span>
        </div>
    );
}

/* ─────────────────────────────────────────────
   GUEST + STAY SECTION
───────────────────────────────────────────── */
function Meta({ booking, nights }: any) {
    const guest = booking.guest;

    function getStayDates(start: string, end: string) {
        const dates = [];
        const current = new Date(start);
        const last = new Date(end);

        while (current < last) {
            dates.push(new Date(current));
            current.setDate(current.getDate() + 1);
        }

        return dates;
    }

    return (
        <div className="flex gap-4  justify-between">

            {/* ───────────────── GUEST PROFILE ───────────────── */}
            <div className="space-y-2 h-fit w-fit flex-1">

                <div className="flex items-center gap-2 text-sm font-medium   bg-muted/80 px-2 pt-1  border-b pb-1 "><User className="w-4 h-4" />Guest Profile</div>
                <div className="space-y-2 text-sm">

                    <div>
                        <div className="font-semibold text-base">  {guest?.title ? `${guest.title} ` : ''}   {guest?.first_name} {guest?.last_name}  </div>
                        <div className="text-xs text-muted-foreground"> Ref: {guest?.reference} </div>
                    </div>

                    <div className="text-xs text-muted-foreground space-y-1 pl-3 border-l-3">
                        <div>{guest?.email || 'No email'}</div>
                        <div>{guest?.phone || 'No phone'}</div>
                        <div>{guest?.country || 'Unknown country'}</div>
                        {guest?.passport && <div> 🛂 Passport: {guest.passport}</div>}
                    </div>

                    {guest?.special_requests && (
                        <div className="mt-2 text-xs border-t pt-2 text-muted-foreground">
                            <span className="font-medium text-foreground">Special Requests:</span>
                            <div>{guest.special_requests}</div>
                        </div>
                    )}

                </div>
            </div>

            {/* ───────────────── STAY INFO ───────────────── */}
            <div className="space-y-2  h-fit flex-1 min-w-64">

                <div className="flex items-center gap-2 text-sm font-medium   bg-muted/80 px-2 pt-1  border-b pb-1">
                    <CalendarDays className="w-4 h-4" />
                    Stay Details
                </div>

                <div className="text-sm space-y-2">

                    <div className='flex gap-4 items-center justify-between'>
                        <div className="space-y-1">
                            <div className="text-muted-foreground text-xs">  Check-in  </div>
                            <div className="font-medium">{booking.check_in}</div>
                        </div>

                        <div className="font-semibold border px-2 text-xs rounded-full bg-primary/5 text-primary ">{nights}N</div>

                        <div className="space-y-1">  <div className="text-muted-foreground text-xs">  Check-out  </div>
                            <div className="font-medium">{booking.check_out}</div>
                        </div>
                    </div>


                </div>

                {/* ───────────────── DATE CHIPS STRIP ───────────────── */}
                <div className="space-y-2 pt-2">

                    <p className="text-xs font-medium text-muted-foreground">
                        Reserved Stay Timeline
                    </p>

                    <div className="flex flex-wrap gap-2">
                        {getStayDates(booking.check_in, booking.check_out).map((date, index) => (
                            <div key={index} className="px-2 py-1.5 rounded-sm border border-primary/20 bg-primary/10 text-primary text-xs dark:border-primary/60 dark:bg-primary/20 dark:text-primary-foreground "  >
                                {date.toLocaleDateString('en-US', { day: '2-digit', month: 'short' })}
                            </div>
                        ))}
                    </div>

                </div>
            </div>

        </div>
    );
}
/* ─────────────────────────────────────────────
   ROOMS SECTION (CORE)
───────────────────────────────────────────── */

function Rooms({ booking, nights }: any) {

    return (
        <div className="space-y-2 ">

            {/* HEADER */}
            <div className="flex items-center justify-between   bg-muted/80 px-2 pt-1  border-b pb-1">
                <div className="flex items-center gap-2 text-sm font-medium">
                    <BedDouble className="w-4 h-4" />
                    Rooms ({booking.rooms?.length})
                </div>

                <div className="text-xs text-muted-foreground">  {nights}N Stay  </div>
            </div>

            {/* ROOMS */}
            <div className="space-y-2">

                {booking.rooms?.map((room: any) => {

                    const roomOnlyTotal = room.room_daily_prices?.reduce(
                        (t: number, d: any) => t + Number(d.price),
                        0
                    );

                    return (
                        <div key={room.id} className=" space-y-2  border-b pb-2 "      >

                            {/* ───────── TOP ROW (COMPACT CORE INFO) ───────── */}
                            <div className="flex items-start justify-between gap-3">

                                {/* LEFT */}
                                <div className="flex gap-2 min-w-0">

                                    {/* <BedDouble className="w-4 h-4 mt-0.5 text-muted-foreground shrink-0" /> */}

                                    <div className="min-w-0">

                                        <div className="text-sm font-medium truncate">
                                            {room.room_title}
                                        </div>

                                        <div className="text-xs text-muted-foreground">
                                            Room #{room.room_number} · {room.adults}A {room.children}C
                                        </div>

                                    </div>

                                </div>

                                {/* RIGHT TOTAL */}
                                <div className="text-right shrink-0">
                                    <div className="text-xs text-muted-foreground">
                                        Total
                                    </div>
                                    <div className="text-sm font-semibold">
                                        {booking.base_currency} {Number(room.grand_total).toLocaleString()}
                                    </div>
                                </div>

                            </div>

                            <div className='space-y-2 border-l-3 pl-3'>
                                {/* ───────── DAILY PRICES (VERY COMPACT) ───────── */}
                                <div className="flex flex-wrap gap-1">

                                    {room.room_daily_prices?.map((d: any, i: number) => {
                                        const date = new Date(d.date);

                                        return (
                                            <div
                                                key={i}
                                                className="
                                                flex items-center gap-1
                                                px-2 py-0.5
                                                border rounded-sm
                                                bg-background
                                                text-xs
                                            "
                                            >
                                                <span className="text-muted-foreground">
                                                    {date.toLocaleDateString('en-US', { day: '2-digit', month: 'short' })}
                                                </span>

                                                <span className="text-primary font-medium">
                                                    {Number(d.price).toLocaleString()}
                                                </span>
                                            </div>
                                        );
                                    })}

                                </div>

                                {/* ───────── MEAL PACKAGE (IMPORTANT PART) ───────── */}
                                {room.meal_package && (
                                    <div className="text-xs space-y-1 ">

                                        <div className="flex justify-between">
                                            <div className="flex items-center gap-1 font-semibold">
                                                <UtensilsCrossed className="w-4 h-4 text-muted-foreground shrink-0" />
                                                {room.meal_package.title}
                                                {room.meal_package.is_variant_selected && (
                                                    <span className="text-muted-foreground ">
                                                        ({room.meal_package.variant.title})
                                                    </span>
                                                )}
                                            </div>

                                            <div className="text-muted-foreground">
                                                {booking.base_currency} {Number(room.meal_total).toLocaleString()}
                                            </div>
                                        </div>

                                        {/* SELECTED DAYS */}
                                        <div className="flex flex-wrap gap-1">

                                            {(room.meal_package.is_entire_stay
                                                ? []
                                                : room.meal_package.selected_days || []
                                            ).map((day: any, i: number) => {
                                                const date = new Date(day);

                                                return (
                                                    <span
                                                        key={i}
                                                        className="
                                                        px-1.5 py-0.5
                                                        border rounded-sm
                                                        bg-muted/20
                                                        text-xs
                                                    "
                                                    >
                                                        {date.toLocaleDateString('en-US', {
                                                            day: '2-digit',
                                                            month: 'short'
                                                        })}
                                                    </span>
                                                );
                                            })}

                                        </div>

                                    </div>
                                )}

                            </div>
                        </div>
                    );
                })}

            </div>
        </div>
    );
}



/* ─────────────────────────────────────────────
   PAYMENT 
───────────────────────────────────────────── */
function Payment({ booking }: any) {
    return (
        <div className="w-full  ">

            {/* PAYMENT */}
            <div className="space-y-2">
                <div className="flex items-center gap-2 text-sm font-medium bg-muted/80 px-2 pt-1  border-b pb-1">
                    <CreditCard className="w-4 h-4" />
                    Payment Summary
                </div>

                <div className="text-xs space-y-1.5">

                    {
                        booking.rooms.map((room: any, index: number) => <div className="flex justify-between border-b-2 border-dashed pb-1.5">
                            <span className="text-muted-foreground">Room ({room.room_number})</span>
                            <span>{booking.base_currency} {Number(room.grand_total).toLocaleString()}  </span>
                        </div>)
                    }

                    {
                        booking.price_data.map((adj: any, index: number) => <div className="flex justify-between border-b-2 border-dashed pb-1.5">
                            <span className="text-muted-foreground">{adj.name}</span>
                            <span>{booking.base_currency} {Number(adj.value).toLocaleString()}  </span>
                        </div>)
                    }

                    <div className="flex justify-between border-b-2  pb-1.5">
                        <span className="text-muted-foreground">Total</span>
                        <span>{booking.base_currency} {Number(booking.total_price).toLocaleString()}</span>
                    </div>

                    <div className="flex justify-between font-semibold ">
                        <span>Display Total</span>
                        <span>
                            {booking.display_currency} {Number(booking.display_total_price).toLocaleString()}
                        </span>
                    </div>
                </div>
            </div>

        </div>
    );
}

function BookingStatus({ booking, onAction }: any) {
    const currentStatus = booking?.status || "pending";

    // 1. Unified Status Flow + Dynamic Timestamps
    const steps = [
        { key: "pending", label: "Pending", time: booking?.created_at },
        { key: "booked", label: "Booked", time: booking?.booked_at },
        { key: "checked-in", label: "Checked In", time: booking?.checked_in_at },
        { key: "checked-out", label: "Checked Out", time: booking?.checked_out_at },
    ];

    // Find the index of where the booking currently sits in the pipeline
    const currentStatusIndex = steps.findIndex(s => s.key === currentStatus);

    return (
        <div className="space-y-5">

            {/* CANCELLED ALERT */}
            {currentStatus === "cancelled" ?
                <div className="flex items-center gap-2 p-2.5 rounded-lg bg-destructive/10 text-destructive text-xs font-medium">
                    <XCircle className="w-4 h-4 shrink-0" />

                    <span>
                        Booking cancelled
                        {booking?.cancelled_at &&
                            ` on ${new Date(
                                booking.cancelled_at
                            ).toLocaleString()}`
                        }
                    </span>
                </div>
                :
                <div className="relative flex justify-between items-start before:absolute before:top-3.5 before:left-0 before:right-0 before:h-0.5 before:bg-muted z-0">
                    {steps.map((step, index) => {
                        // 1. A step is completely DONE if its index is less than OR EQUAL to the current status index
                        const isDone = index <= currentStatusIndex;

                        // 2. The ACTIVE (pulse) step is the step immediately following the current completed status
                        // If everything is completed (e.g., checked-out), nothing pulses.
                        const isActive = index === currentStatusIndex + 1;

                        return (
                            <div key={step.key} className="flex flex-col items-center flex-1 z-10 text-center">
                                {/* Timeline Dot */}
                                <div
                                    className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-semibold transition-all
                                    ${isActive ? "bg-background border-2 border-primary text-primary ring-4 ring-primary/10 shadow-sm" : ""}
                                    ${isDone ? "bg-blue-600 border-2 border-muted-foreground/40 text-white" : ""}
                                    ${!isDone && !isActive ? "bg-background border-2 border-muted text-muted-foreground" : ""} `}
                                >
                                    {/* Done steps get a checkmark */}
                                    {isDone ? "✓" : ""}

                                    {/* The next incoming step pulses to attract attention */}
                                    {isActive && <div className="w-2 h-2 rounded-full bg-primary animate-pulse" />}
                                </div>

                                {/* Label Styling */}
                                <span className={`text-xs font-medium mt-1.5 transition-colors ${isActive ? "text-primary font-bold" : "text-muted-foreground"}`}>
                                    {step.label}
                                </span>

                                {/* Timestamp */}
                                {step.time && (
                                    <span className="text-[11px] text-muted-foreground/80 font-mono ">
                                        {new Date(step.time).toLocaleDateString(undefined, {
                                            month: 'short',
                                            day: 'numeric',
                                            hour: '2-digit',
                                            minute: '2-digit',
                                        })}
                                    </span>
                                )}
                            </div>
                        );
                    })}
                </div>
            }
        </div>
    );
}

function BookingControls({ booking, onAction, loading }: any) {

    const currentStatus = booking?.status || "pending";

    const actionMap: Record<string, any> = {
        pending: {
            label: "Confirm Booking",
            next: "booked",
            title: "Confirm Booking",
            description: "This will confirm the reservation and block room availability.",
            confirmText: "Confirm Booking",
            icon: "BadgeCheck",
        },

        booked: {
            label: "Check In Guest",
            next: "checked-in",
            title: "Check In Guest",
            description: "This will mark the guest as checked in.",
            confirmText: "Check In",
            icon: "LogIn",
        },

        "checked-in": {
            label: "Check Out Guest",
            next: "checked-out",
            title: "Check Out Guest",
            description: "This will complete the stay and check out the guest.",
            confirmText: "Check Out",
            icon: "LogOut",
        },
    };

    const primaryAction = actionMap[currentStatus];

    const isFinalState = ["checked-out", "cancelled"].includes(currentStatus);

    return (
        <div className="space-y-5">



            {/* CONTROLS */}
            <div className="flex items-center justify-between pt-4 border-t gap-4">

                {/* PRIMARY ACTIONS */}
                <div className="flex items-center gap-2 flex-1">

                    {primaryAction && (
                        <ConfirmActionAlertButton
                            title={primaryAction.title}
                            description={primaryAction.description}
                            icon={primaryAction.icon}
                            confirmText={primaryAction.confirmText}
                            variant="default"
                            loading={loading}
                            onConfirm={() =>
                                onAction?.(primaryAction.next)
                            }
                        />
                    )}

                    {/* CANCEL */}
                    {!isFinalState && (
                        <ConfirmActionAlertButton
                            title="Cancel Booking"
                            description="This will cancel the booking and release room availability."
                            icon="XCircle"
                            confirmText="Cancel Booking"
                            iconClassName='text-destructive bg-destructive/5'
                            variant="ghost"
                            alertVariant='destructive'
                            loading={loading}
                            onConfirm={() =>
                                onAction?.("cancelled")
                            }
                        />
                    )}

                    {/* FINAL STATES */}
                    {currentStatus === "checked-out" && (
                        <span className="text-xs font-medium px-2.5 py-1 rounded-full transition-colors  text-emerald-600 bg-emerald-50   dark:text-emerald-400 dark:bg-emerald-950/40 dark:border dark:border-emerald-800/50">    Stay Completed   </span>
                    )}
                </div>

                {/* MANAGEMENT */}
                <div className="flex items-center gap-2 border-l pl-3">

                    <Button size="icon-sm" variant="outline" title="Edit Booking" onClick={() => onAction?.("edit")}    >    <Edit className="w-4 h-4" />     </Button>

                    <DeleteButton deleteId={booking.id} model='bookings' title='Booking' />
                </div>
            </div>
        </div>
    );
}

/* ─────────────────────────────────────────────
                MAIN PAGE COMPONENT
                ───────────────────────────────────────────── */
export default function BookingDetails({ booking }: any) {

    const [loading, setLoading] = useState(false)

    const nights = booking
        ? (new Date(booking.check_out).getTime() -
            new Date(booking.check_in).getTime()) /
        (1000 * 60 * 60 * 24)
        : 0;



    if (!booking) {
        return (
            <Card className="border-dashed bg-muted/20 shadow-none">
                <CardContent className="flex flex-col items-center justify-center p-12 text-center max-w-xl w-full mx-auto min-h-75">
                    {/* Soft Icon Container */}
                    <div className="flex h-12 w-12 items-center justify-center rounded-xl bg-background border shadow-sm text-muted-foreground/80 mb-4 animate-fade-in">
                        <CalendarDays className="h-5 w-5" />
                    </div>

                    {/* Messaging Hierarchy */}
                    <h3 className="text-sm font-semibold text-foreground tracking-tight">
                        No Booking Selected
                    </h3>
                    <p className="text-xs text-muted-foreground mt-1 max-w-60 leading-normal">
                        Select a guest booking from the list to view timeline details, timestamps, and active status controls.
                    </p>
                </CardContent>
            </Card>
        );
    }

    const onAction = (action: string) => {

        setLoading(true)

        router.patch(`/dashboard/bookings/${booking.id}/status`, { status: action },
            {
                preserveScroll: true,

                onSuccess: () => { toast.success("Booking updated") },

                onError: (errors) => {
                    toast.error(Object.values(errors)[0] as string || "Failed to update booking");
                },

                onFinish: () => { setLoading(false); }
            }
        );
    }

    return (
        <div className="p-4 flex-1 space-y-6  bg-background/90 border rounded-sm 2xl:max-w-2xl">
            {/* <CardContent className="p-4 space-y-6"> */}

            <Header booking={booking} />
            <BookingStatus booking={booking} />
            <Meta booking={booking} nights={nights} />
            <Rooms booking={booking} nights={nights} />
            <Payment booking={booking} />
            <BookingControls booking={booking} onAction={onAction} loading={loading} />

            {/* </CardContent> */}
        </div>
    );
}
