
import { Calendar } from "@/components/ui/calendar"
import { PopoverTrigger, PopoverContent, Popover } from "@/components/ui/popover"
import { cn } from "@/lib/utils"
import { SearchRoom } from "@/types/home/client-side"
import { formatDate, formatReadable, getDayName } from "@/utils/dateFormatters"
import { router, usePage } from "@inertiajs/react"
import { addDays, format, setDate } from "date-fns"
import { Users, User, CalendarDays, ChevronDown } from "lucide-react"

import { useState, useEffect } from "react"

export const SideBoxFindRoom = () => {

    return <div className="absolute space-y-4 bottom-20 left-20   2xl:bottom-40 w-fit max-w-5xl mx-auto ">

        <div className="font-p hidden  md:flex flex-col gap-4 items-stretch lg:items-end  border backdrop-blur-xs border-main/50  rounded-sm bg-black/70 p-6">


            <div>
                <span className="text-sm text-gray-100">Check In</span>
                <div className="bg-black/80 border border-main/50 min-w-75 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
                    <div>
                        <h1 className="text-base font-bold text-white">08 Aug, 2026</h1>
                        <p className="text-xs text-gray-100">Thursday</p>
                    </div>
                    <ChevronDown className="w-6 h-6 text-white" />
                </div>
            </div>


            <div>
                <span className="text-sm text-gray-100">Check Out</span>
                <div className="bg-black/80 border border-main/50 min-w-75 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
                    <div>
                        <h1 className="text-base font-bold text-white">24 Aug, 2026</h1>
                        <p className="text-xs text-gray-100">Sunday</p>
                    </div>
                    <ChevronDown className="w-6 h-6 text-white" />
                </div>
            </div>


            <div>
                <span className="text-sm text-gray-100">Adults & Children</span>
                <div className="bg-black/80 border border-main/50 min-w-75 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
                    <div>
                        <h1 className="text-base font-bold text-white">2 Adults & 1 Child</h1>
                        <p className="text-xs text-gray-100">Per room</p>
                    </div>
                    <ChevronDown className="w-6 h-6 text-white" />
                </div>
            </div>


            <button className="lg:flex-1 w-full flex items-center justify-center gap-3 bg-main text-white rounded-sm px-4 min-h-14">
                <CalendarDays className="w-6 h-6" />
                <span className="font-medium uppercase">Find Your Room</span>
            </button>

        </div>
    </div>
}

export const InlineFindRoom = () => {
    const { search, maxAdults, maxChildren } = usePage().props as unknown as { search: SearchRoom, maxAdults: number, maxChildren: number }

    const [checkIn, setCheckIn] = useState<Date>(new Date(search.check_in + 'T00:00:00'))
    const [checkOut, setCheckOut] = useState<Date>(new Date(search.check_out + 'T00:00:00'))
    const [adults, setAdults] = useState(search.adults)
    const [children, setChildren] = useState(search.children)


    const searchRoom = () => {

        router.post('/search-rooms', {
            check_in: formatDate(checkIn),
            check_out: formatDate(checkOut),
            adults: adults,
            children: children
        })
    }

    // Whenever check-in changes, adjust check-out
    useEffect(() => {
        if (!checkIn) return;

        // If current checkOut is before or same as checkIn, update it
        if (!checkOut || checkOut <= checkIn) {
            setCheckOut(addDays(checkIn, 1));
        }
    }, [checkIn, checkOut]);



    // return <div className="absolute space-y-4 bottom-14 left-0 right-0  2xl:bottom-20 w-full max-w-5xl mx-auto ">
    //     {/* <span className="text-white font-p ">Check-out time: before 11:00 am  -  check-in time: after 2:00 pm</span> */}

    //     <div className="font-p hidden  md:flex flex-col lg:flex-row gap-6 items-stretch lg:items-end  border border-main/50 rounded-sm bg-black/90 p-4">


    //         <div className="flex flex-col justify-center items-start gap-0.5">
    //             <span className="text-sm text-gray-100">Check In</span>
    //             <div className="bg-black/90 text-white border border-main/50 min-w-55 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
    //                 <div>
    //                     <h1 className="text-base font-bold">08 Aug, 2026</h1>
    //                     <p className="text-xs text-gray-100">Thursday</p>
    //                 </div>
    //                 <ChevronDown className="w-6 h-6" />
    //             </div>
    //         </div>


    //         <div className="flex flex-col justify-center items-start gap-0.5">
    //             <span className="text-sm text-gray-100">Check Out</span>
    //             <div className="bg-black/90 text-white border border-main/50 min-w-55 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
    //                 <div>
    //                     <h1 className="text-base font-bold">24 Aug, 2026</h1>
    //                     <p className="text-xs text-gray-100">Sunday</p>
    //                 </div>
    //                 <ChevronDown className="w-6 h-6" />
    //             </div>
    //         </div>


    //         <div className="flex flex-col justify-center items-start gap-0.5">
    //             <span className="text-sm text-gray-100">Adults & Children</span>
    //             <div className="bg-black/90 text-white border border-main/50 min-w-65 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
    //                 <div>
    //                     <h1 className="text-base font-bold">2 Adults & 1 Child</h1>
    //                     <p className="text-xs text-gray-100">Per room</p>
    //                 </div>
    //                 <ChevronDown className="w-6 h-6" />
    //             </div>
    //         </div>


    //         <button className="lg:flex-1 w-full flex items-center justify-center gap-3 bg-main text-white rounded-sm px-4 h-14 ring-4 ring-main/30">
    //             <CalendarDays className="w-6 h-6" />
    //             <span className="font-bold uppercase ">Find Your Room</span>
    //         </button>

    //     </div>
    // </div>

    return (
        <div className="absolute space-y-4 bottom-14 left-0 right-0 2xl:bottom-20 w-full max-w-5xl mx-auto">

            <div className="font-p hidden md:flex flex-col lg:flex-row gap-6 items-stretch lg:items-end border border-main/50 rounded-sm bg-black/90 p-4">

                {/* CHECK IN */}
                <div className="flex flex-col justify-center items-start gap-0.5">
                    <span className="text-sm text-gray-100">Check In</span>

                    <Popover>
                        <PopoverTrigger asChild>
                            <div className="cursor-pointer bg-black/90 text-white border border-main/50 min-w-55 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
                                <div>
                                    <h1 className="text-base font-bold">
                                        {checkIn ? format(checkIn, "dd MMM, yyyy") : "Select date"}
                                    </h1>
                                    <p className="text-xs text-gray-100">
                                        {getDayName(checkIn)}
                                    </p>
                                </div>
                                <ChevronDown className="w-6 h-6" />
                            </div>
                        </PopoverTrigger>

                        <PopoverContent className="w-auto p-0">
                            <Calendar
                                mode="single"
                                required
                                selected={checkIn}
                                onSelect={setCheckIn}
                                autoFocus
                                disabled={(date) => {
                                    const d = new Date(date);
                                    d.setHours(0, 0, 0, 0);
                                    const t = new Date();
                                    t.setHours(0, 0, 0, 0);
                                    return d < t; // disable past dates
                                }}
                            />
                        </PopoverContent>
                    </Popover>
                </div>


                {/* CHECK OUT */}
                <div className="flex flex-col justify-center items-start gap-0.5">
                    <span className="text-sm text-gray-100">Check Out</span>

                    <Popover>
                        <PopoverTrigger asChild>
                            <div className="cursor-pointer bg-black/90 text-white border border-main/50 min-w-55 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
                                <div>
                                    <h1 className="text-base font-bold">
                                        {checkOut ? format(checkOut, "dd MMM, yyyy") : "Select date"}
                                    </h1>
                                    <p className="text-xs text-gray-100">
                                        {getDayName(checkOut)}
                                    </p>
                                </div>
                                <ChevronDown className="w-6 h-6" />
                            </div>
                        </PopoverTrigger>

                        <PopoverContent className="w-auto p-0">
                            <Calendar
                                mode="single"
                                required
                                selected={checkOut}
                                onSelect={setCheckOut}
                                disabled={(date) => {
                                    if (!checkIn) return false;

                                    const d = new Date(date);
                                    d.setHours(0, 0, 0, 0);

                                    const minCheckOut = addDays(checkIn, 1);
                                    return d < minCheckOut; // disable check-in date and previous
                                }}
                            />
                        </PopoverContent>
                    </Popover>
                </div>


                {/* ADULTS + CHILDREN */}
                <div className="flex flex-col justify-center items-start gap-0.5">
                    <span className="text-sm text-gray-100">Adults & Children</span>

                    <Popover>
                        <PopoverTrigger asChild>
                            <div className="cursor-pointer bg-black/90 text-white border border-main/50 min-w-65 rounded-sm p-1.5 px-3 flex gap-4 items-start justify-between h-14">
                                <div>
                                    <h1 className="text-base font-bold">
                                        {adults} Adults & {children} Child
                                    </h1>
                                    <p className="text-xs text-gray-100">Per room</p>
                                </div>
                                <ChevronDown className="w-6 h-6" />
                            </div>
                        </PopoverTrigger>

                        <PopoverContent className="w-60 space-y-4">

                            {/* Adults */}
                            <div className="flex justify-between items-center">
                                <span>Adults</span>
                                <div className="flex gap-3 items-center">
                                    <button
                                        onClick={() => setAdults(Math.max(1, adults - 1))}
                                        className="px-2 border"
                                    >-</button>

                                    <span>{adults}</span>

                                    <button
                                        onClick={() => setAdults(Math.min(maxAdults || 2, adults + 1))}
                                        className="px-2 border"
                                    >+</button>
                                </div>
                            </div>

                            {/* Children */}
                            <div className="flex justify-between items-center">
                                <span>Children</span>
                                <div className="flex gap-3 items-center">
                                    <button
                                        onClick={() => setChildren(Math.max(0, children - 1))}
                                        className="px-2 border rounded-full"
                                    >-</button>

                                    <span>{children}</span>

                                    <button
                                        onClick={() => setChildren(Math.min(maxChildren || 1, children + 1))}
                                        className="px-2 border  rounded-full"
                                    >+</button>
                                </div>
                            </div>

                        </PopoverContent>
                    </Popover>
                </div>


                {/* FIND BUTTON */}
                <button onClick={searchRoom} className="lg:flex-1 w-full flex items-center justify-center gap-3 bg-main text-white rounded-sm px-4 h-14 ring-4 ring-main/30 hover:scale-101 active:scale-98 transform duration-200 ease-in-out">
                    <CalendarDays className="w-6 h-6" />
                    <span className="font-bold uppercase">Find Your Room</span>
                </button>

            </div>
        </div>
    )
}



export const SearchRoomCard = () => {

    const { search, maxAdults, maxChildren } = usePage().props as unknown as { search: SearchRoom, maxAdults: number, maxChildren: number }

    const [form, setForm] = useState({
        check_in: new Date(search.check_in + 'T00:00:00'),
        check_out: new Date(search.check_out + 'T00:00:00'),
        adults: search.adults,
        children: search.children
    });


    const checkin = form.check_in;
    const checkout = form.check_out;

    const checkinDay = checkin.getDate();
    const checkoutDay = checkout.getDate();

    const checkinMonth = checkin.toLocaleString('default', { month: 'short' });
    const checkoutMonth = checkout.toLocaleString('default', { month: 'short' });

    const checkinWeek = checkin.toLocaleString('default', { weekday: 'short' });
    const checkoutWeek = checkout.toLocaleString('default', { weekday: 'short' });

    const nights = Math.ceil(
        (checkout.getTime() - checkin.getTime()) / (1000 * 60 * 60 * 24)
    );

    useEffect(() => {
        if (!form.check_in) return;

        // If current checkOut is before or same as form.check_in, update it
        if (!form.check_out || form.check_out <= form.check_in) {
            // setform.Check_out(addDays(form.check_in, 1));
            setForm({ ...form, check_out: addDays(form.check_in, 1) })
        }
    }, [form.check_in, form.check_out]);

    useEffect(() => {
        setForm({
            check_in: new Date(search.check_in + 'T00:00:00'),
            check_out: new Date(search.check_out + 'T00:00:00'),
            adults: search.adults,
            children: search.children
        })
    }, [search])

    return <div className=" border rounded-lg shadow-sm h-fit bg-white overflow-hidden hover:shadow-sm transition duration-300">

        {/* Top Row: Check-in / Nights / Check-out */}
        <div className="flex items-center justify-between p-5 bg-linear-to-r from-main/10 via-main/4 to-main/10">

            {/* Check In */}
            <Popover>
                <PopoverTrigger asChild>
                    <div className="text-start cursor-pointer transform ease-in duration-400">
                        <span className="text-sm text-neutral-500">Check In</span>
                        <div className="flex items-center gap-2 mt-1 justify-center">
                            <h1 className="text-5xl font-bold text-neutral-900">{checkinDay}</h1>
                            <div className="flex flex-col">
                                <span className="text-xs italic font-normal text-neutral-400">{checkinWeek}</span>
                                <span className="text-2xl font-semibold text-neutral-900">{checkinMonth}</span>
                            </div>
                        </div>
                    </div>
                </PopoverTrigger>
                <PopoverContent>
                    <Calendar
                        mode="single"
                        required
                        selected={form.check_in}
                        onSelect={value => setForm({ ...form, check_in: value })}
                        autoFocus
                        disabled={(date) => {
                            const d = new Date(date);
                            d.setHours(0, 0, 0, 0);
                            const t = new Date();
                            t.setHours(0, 0, 0, 0);
                            return d < t; // disable past dates
                        }}
                    />

                </PopoverContent>
            </Popover>

            {/* Nights */}
            <span className="bg-main/10 text-main font-semibold text-sm px-4 py-2 min-w-24 text-center rounded-full transform ease-in duration-400">
                {nights} Nights
            </span>

            <Popover>
                <PopoverTrigger asChild>
                    <div className="text-start cursor-pointer transform ease-in duration-400">
                        <span className="text-sm text-neutral-500">Check Out</span>
                        <div className="flex items-center gap-2 mt-1 justify-center">
                            <h1 className="text-5xl font-bold text-neutral-900">{checkoutDay}</h1>
                            <div className="flex flex-col">
                                <span className="text-xs italic font-normal text-neutral-400">{checkoutWeek}</span>
                                <span className="text-2xl font-semibold text-neutral-900">{checkoutMonth}</span>
                            </div>
                        </div>
                    </div>
                </PopoverTrigger>
                <PopoverContent>
                    <Calendar
                        mode="single"
                        required
                        selected={form.check_out}
                        onSelect={value => setForm({ ...form, check_out: value })}
                        autoFocus
                        disabled={(date) => {
                            if (!form.check_in) return false;

                            const d = new Date(date);
                            d.setHours(0, 0, 0, 0);

                            const minCheckOut = addDays(form.check_in, 1);
                            return d < minCheckOut; // disable check-in date and previous
                        }}
                    />

                </PopoverContent>
            </Popover>
        </div>

        {/* Second Row: Guests */}
        <div className="flex flex-col gap-4 px-5 py-6 ">

            {/* Adults */}
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-4 text-neutral-800">
                    <Users size={20} className="text-main" />
                    <span className="font-medium ">Adults</span>
                </div>
                <div className="flex items-center gap-2">
                    <button onClick={() => setForm({ ...form, adults: Math.max(1, form.adults - 1) })} className="w-8 h-8 cursor-pointer flex shadow-xs hover:scale-110 active:scale-95 text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition">
                        -
                    </button>
                    <span className="px-2 font-medium">{form.adults}</span>
                    <button onClick={() => setForm({ ...form, adults: Math.min(maxAdults || 2, form.adults + 1) })} className="w-8 h-8 cursor-pointer flex hover:scale-110 active:scale-95  shadow-xs text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition">
                        +
                    </button>
                </div>
            </div>

            {/* Children */}
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-4  text-neutral-800">
                    <User size={20} className="text-main" />
                    <span className="font-medium t">Children</span>
                </div>
                <div className="flex items-center gap-2">
                    <button onClick={() => setForm({ ...form, children: Math.max(0, form.children - 1) })} className="w-8 h-8 cursor-pointer flex shadow-xs hover:scale-110 active:scale-95  text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition">
                        -
                    </button>
                    <span className="px-2 t font-medium">{form.children || '-'}</span>
                    <button onClick={() => setForm({ ...form, children: Math.min(maxChildren || 1, form.children + 1) })} className="w-8 h-8 cursor-pointer hover:scale-110 active:scale-95  flex shadow-xs text-lg items-center justify-center rounded-full border text-main hover:bg-main/10 transition">
                        +
                    </button>
                </div>
            </div>

            {/* Change Date Button */}
            <div className="pt-2">
                <button onClick={() => router.post('/search-rooms', { ...form, check_in: form.check_in.toDateString(), check_out: form.check_out.toDateString() })} className=" cursor-pointer w-full py-3 rounded-sm ring-4 ring-main/20 bg-main text-white font-semibold  hover:bg-main/90 active:scale-95 transition shadow-md"> Find Room </button>
            </div>

        </div>

    </div>
}


export const SearchSideCard = ({ adults, children, searchBtn, className, onClick }: { adults?: number, children?: number, searchBtn?: boolean, className?: string, onClick?: () => void }) => {

    const { search } = usePage().props as unknown as { search: SearchRoom }

    return <div className={cn('flex items-center justify-between gap-3  border-l-4 border-l-main/40 pl-3 ', className)}>
        <div className="flex-1 flex items-center gap-3">
            <div className="flex flex-col">
                <div className="flex items-baseline gap-1 text-neutral-900 text-2xl">
                    <span className="font-semibold whitespace-nowrap">{new Date(search.check_in).getDate()} {new Date(search.check_in).toLocaleString('default', { month: 'short' })}</span>
                    <span className="font-semibold">–</span>
                    <span className="font-semibold whitespace-nowrap">{new Date(search.check_out).getDate()} {new Date(search.check_out).toLocaleString('default', { month: 'short' })}</span>
                    <span className="text-sm text-neutral-500 ml-1 whitespace-nowrap">/ {new Date(search.check_in).getFullYear()}</span>
                </div>

                <div className="flex items-center gap-2 text-sm text-neutral-600 mt-0.5">
                    <Users size={16} className="text-main" />
                    <span>{adults ?? search?.adults} Adults · {children ?? search?.children} Child</span>
                </div>
            </div>
        </div>

        {searchBtn && <button onClick={onClick} className=" cursor-pointer shrink-0 text-sm font-medium bg-main text-white ring-4 ring-main/20  px-3 py-2 rounded-full hover:bg-main/85 active:scale-95 transition duration-300"> Change Date  </button>}
    </div>

}