
import { SearchSideCard } from "@/components/(public)/home/SearchRoom";
import Price from "@/components/(public)/Price";
import UiCardFooter from "@/components/(public)/UiCardFooter";
import UiProgressBar from "@/components/(public)/UiProgressBar";
import UiSideDetailsCard from "@/components/(public)/UiSideDetailsCard";
import { Button } from "@/components/ui/button";
import PageLayout from "@/layouts/home/page-layout";
import { CheckoutBookingInput, RoomSelected } from "@/types/home/bookings";
import { SearchRoom } from "@/types/home/client-side";
import { RoomCapacitiesType } from "@/types/home/room";
import { calBooking, calBookingSubTotal, calMealPackageTotal, calPriceAdjustment, calRoomOnlyTotal, calRoomTotal } from "@/utils/client/calBooking";
import { router, useForm } from "@inertiajs/react";
import { Minus, Plus, Trash2, User, Users, X } from "lucide-react";
import { useEffect } from "react";
import { toast } from "sonner";



function ReserveCard({ booking, onClick }: { booking: CheckoutBookingInput, onClick: () => void }) {


    const total_adults = booking?.rooms.reduce((sum, r) => sum + r.adults, 0);
    const total_children = booking?.rooms.reduce((sum, r) => sum + r.children, 0);



    return <UiSideDetailsCard>
        <SearchSideCard adults={total_adults || 0} children={total_children || 0} searchBtn />
        <div className=" border-neutral-200 mt-6">

            {
                booking?.rooms?.map((room, index) => <div key={index} className="flex border-t-2 border-dashed justify-between text-sm py-2 text-neutral-600">
                    <span>Room 0{index + 1} <span className='text-sm'>({room.title})</span></span>
                    <span><Price value={calRoomTotal(room, booking.nights)} /></span>
                </div>)
            }


            {/* 📊 Subtotal */}
            {
                booking.rooms.length > 1 && <div className="flex justify-between text-sm py-2  pb-6 border-t-2 border-dashed  font-semibold text-neutral-800">
                    <span>Subtotal</span>
                    <span>
                        <Price value={calBookingSubTotal(booking)} />
                    </span>
                </div>
            }

            {/* 💰 Price Adjustments */}
            {booking?.price_data?.map(item => {

                const isDiscount = item.direction === 'subtract';

                return (
                    <div key={item.id} className={`flex justify-between text-sm py-2  border-t-2 border-dashed   ${isDiscount ? 'text-green-600' : 'text-neutral-600'} `}  >
                        {/* Left side */}
                        <span className="flex items-center gap-1">
                            {item.name}
                            {item.value_type === 'percentage' && <span className="text-xs text-neutral-400">({Number(item.value)}%)</span>}
                            {item.value_type === 'fixed' && <span className="text-xs text-neutral-400">(fixed)</span>}
                        </span>

                        {/* Right side */}
                        <span className="font-medium">
                            {item.direction === 'add' ? '+' : '-'}{" "}
                            {<Price value={Math.abs(calPriceAdjustment(item, calBookingSubTotal(booking)))} />}
                        </span>
                    </div>
                );
            })}


        </div>


        <UiCardFooter price={booking?.total_price || 0} subTitle="booking" buttonTitle="Reserve Now" onClick={onClick} />
    </UiSideDetailsCard>

}

function SummaryRoomCard({ search, room, updateAdults, updateChildren, showDetails }: { search: SearchRoom, room: RoomSelected, updateAdults: (roomId: number, delta: number) => void, updateChildren: (roomId: number, delta: number) => void, showDetails: (slug: string, room_number: string) => void }) {


    const meal_total = calMealPackageTotal(room.meal_package, search.nights, room.adults + room.children)

    return <div className=" bg-white rounded-none border p-6 ">
        <div className="flex gap-6 ">

            <img src={room?.image_url ? room.image_url : '/images/placeholders/room-placeholder.jpg'} className="h-52 aspect-video rounded-xs object-cover " alt={room.title} />


            <div className="flex-1 space-y-2 flex flex-col justify-between">
                <div className="flex justify-center flex-col  items-start">
                    <span className="text-xs text-neutral-600">DELUXE ROOM</span>
                    <span className="font-semibold text-lg">{room.title}</span>
                </div>
                {/* <h3 className="font-semibold text-lg">{room.title}</h3> */}
                {/* Adults */}
                <div className="space-y-2 text-sm">
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4 text-neutral-800">
                            <Users size={16} className="text-main" />
                            <span className="font-medium ">Adults</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <Button onClick={() => updateAdults(room.room_id, -1)} variant='outline' size='icon-sm' className="flex cursor-pointer shadow-xs text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition"><Minus /></Button>
                            <span className="px-2 font-medium min-w-6 text-center">{room.adults}</span>
                            <Button onClick={() => updateAdults(room.room_id, 1)} variant='outline' size='icon-sm' className="flex cursor-pointer shadow-xs text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition"><Plus /></Button>
                        </div>
                    </div>

                    {/* Children */}
                    <div className="flex items-center justify-between">
                        <div className="flex items-center gap-4  text-neutral-800">
                            <User size={16} className="text-main" />
                            <span className="font-medium t">Children</span>
                        </div>
                        <div className="flex items-center gap-2">
                            <Button onClick={() => updateChildren(room.room_id, -1)} variant='outline' size='icon-sm' className="flex  cursor-pointer shadow-xs text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition"><Minus /></Button>
                            <span className="px-2 t font-medium min-w-6 text-center">{room.children}</span>
                            <Button onClick={() => updateChildren(room.room_id, 1)} variant='outline' size='icon-sm' className="flex cursor-pointer shadow-xs text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition"><Plus /></Button>
                        </div>
                    </div>
                </div>

                <div className="flex justify-between text-sm items-end">
                    <div className="flex justify-center flex-col  items-start">
                        <span className="text-xs text-neutral-600">price</span>
                        <span className="font-medium text-sm">Room Only</span>
                    </div>
                    <span><Price value={calRoomOnlyTotal(room.room_daily_prices)} /></span>
                </div>

                {room.meal_package && (
                    <div className="flex justify-between  text-sm items-end">
                        {/* <span className="text-gray-600">{room.meal_package.title}</span> */}
                        <div className="flex justify-center flex-col  items-start">
                            <span className="text-xs text-neutral-600">Meal Package</span>
                            <span className="font-medium text-sm">{room.meal_package.title} x ({room.adults + room.children} guests)</span>
                        </div>
                        <span><Price value={meal_total} /></span>
                    </div>
                )}


            </div>
        </div>

        {room.addons.length > 0 && <p className="text-sm mt-4">Enhance Your Stay (Add-Ons for Room)</p>}

        {/* Price Breakdown */}
        <div className="text-sm space-y-4 py-4">

            {room.addons.map((a) => (
                <div key={a.id} className="flex justify-between items-center">
                    <div className="flex gap-4 items-center">
                        {/* <ImageIconBox is_icon={a.is_icon} value={a.icon_value} className="w-5 h-5 text-main" /> */}
                        <div className="flex justify-center flex-col  items-start">
                            <span className="text-xs text-neutral-600">{a.calculation_type}</span>
                            <span className="font-medium text-sm">{a.title} x ({room.adults} adults)</span>
                        </div>
                    </div>
                    <div className="flex gap-4 items-center justify-end">
                        <span><Price value={a.price} /></span>
                        <Button onClick={() => router.post('/booking/remove-room', { room_id: room.room_id })} className="text-destructive rounded-full" variant='outline' size='icon-xs'><X /></Button>

                    </div>
                </div>
            ))}
        </div>
        {/* Total Section */}
        <div className="border-t flex pt-4 justify-between items-end">
            <div className="flex justify-end flex-col  items-start">
                <span className="text-xs text-neutral-600">Total Room Price</span>
                <h2 className="text-xl font-bold text-neutral-900">
                    <span><Price value={calRoomTotal(room, search.nights)} /></span>
                    <span className="text-sm font-normal text-neutral-500"> / Room</span>
                </h2>
            </div>
            <div className=" flex gap-2">
                <Button variant='outline' onClick={() => showDetails(room.slug, room.room_number)} className=" cursor-pointer border text-sm py-2 px-4 rounded-md hover:bg-gray-50 transition">  View Details </Button>
                <Button onClick={() => router.post('/booking/remove-room', { room_id: room.room_id })} className="text-destructive  cursor-pointer" variant='outline' size='icon'><Trash2 /></Button>
            </div>
        </div>
    </div>
}

export default function SummaryPage({ search, booking, room_capacities }: { search: SearchRoom, booking: CheckoutBookingInput, room_capacities: RoomCapacitiesType[] }) {


    const { data, setData, post } = useForm(booking);

    console.log(data);


    const getCapacity = (roomId: number) => {
        const room = room_capacities.find(r => r.id === roomId);

        return {
            maxAdults: room?.max_adults ?? 2,
            maxChildren: room?.max_children ?? 1,
        };
    };

    const updateAdults = (roomId: number, delta: number) => {

        const updatedRooms = data.rooms.map(r => {

            if (r.room_id !== roomId) return r;

            const { maxAdults } = getCapacity(roomId);
            const newValue = r.adults + delta;

            return {
                ...r,
                adults: Math.min(maxAdults, Math.max(1, newValue)),
            };
        });

        setData(calBooking({
            ...data,
            rooms: updatedRooms,
        }));
    };

    const updateChildren = (roomId: number, delta: number) => {

        const updatedRooms = data.rooms.map(r => {

            if (r.room_id !== roomId) return r;

            const { maxChildren } = getCapacity(roomId);
            const newValue = r.children + delta;

            return {
                ...r,
                children: Math.min(maxChildren, Math.max(0, newValue)),
            };
        });

        setData(calBooking({
            ...data,
            rooms: updatedRooms,
        }));
    };


    const saveAndCheckout = () => {

        post('/booking/save-summary', {
            onError: () => toast.error('Please check again all details!')
        });
    };

    const saveAndRoomDetails = (slug: string, room_number: string) => {

        post(`/booking/save-summary/${slug}/${room_number}`, {
            onError: () => toast.error('Please check again all details!')
        });

    }

    useEffect(() => {
        setData(calBooking(booking))
    }, [booking])

    return (
        <PageLayout title="Summary">
            <div className="max-w-300 2xl:max-w-340 mx-auto py-8 px-4 mb-10f space-y-6 min-h-full 2xl:min-h-[80vh]">

                {/* Step Indicator */}
                <UiProgressBar activeStep={1} />

                <div className="flex gap-6">

                    {/* LEFT SIDE: Step Content */}
                    <div className="flex-2 space-y-6">
                        <div className="flex-2 space-y-6">
                            {data.rooms.map((room) => <SummaryRoomCard key={room.room_id} search={search} room={room} updateAdults={updateAdults} updateChildren={updateChildren} showDetails={saveAndRoomDetails} />)}
                        </div>

                    </div>

                    {/* RIGHT SIDE: Booking Summary */}
                    <ReserveCard booking={data} onClick={saveAndCheckout} />

                </div>

            </div>
        </PageLayout>
    );
}