
import ConfirmBooking from "@/components/(public)/ConfirmBooking";
import Price from "@/components/(public)/Price";
import UiProgressBar from "@/components/(public)/UiProgressBar";
import InputField, { CountrySelector, TextAreaField } from "@/components/core/InputField";
import { Label } from "@/components/ui/label";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Separator } from "@/components/ui/separator";
import PageLayout from "@/layouts/home/page-layout";
import { CheckoutBookingInput } from "@/types/home/bookings";
import { calAdultTotal, calBookingSubTotal, calBookingTotal, calChildrenTotal, calPriceAdjustment, calRoomTotal } from "@/utils/client/calBooking";
import { useForm } from "@inertiajs/react";
import { CreditCard, DollarSign, Users } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";

type GuestInfo = {
    title?: 'Mr' | 'Mrs' | 'Ms' | 'Miss' | 'Dr' | 'Mx' | string,
    first_name: string,
    last_name: string,
    email: string,
    phone: string,
    passport: string,
    country: string,
    special_requests: string,
}

export type GuestInfoFormProp = {
    guest: GuestInfo,
    updateGuest: (field: keyof GuestInfo, value: string) => void,
    errors?: any;
}


function CheckInOutDetails({ checkIn, checkOut, adults, children }: { checkIn: string, checkOut: string, adults: number, children: number }) {

    const check_in_date = new Date(checkIn).getDate()
    const check_in_day = new Date(checkIn).toLocaleString('default', { month: 'short' })

    const check_out_date = new Date(checkOut).getDate()
    const check_out_day = new Date(checkOut).toLocaleString('default', { month: 'short' })

    const year = new Date(checkIn).getFullYear()

    return <div className="flex items-center justify-between gap-3  border-l-4 border-l-main/40 pl-3">
        {/* Date + Guests */}
        <div className="flex-1 flex items-center gap-3">
            {/* Info */}
            <div className="flex flex-col">
                {/* Dates */}
                <div className="flex items-baseline gap-1 text-neutral-900 text-2xl">
                    <span className="font-semibold">{check_in_date} {check_in_day}</span>
                    <span className="font-semibold">–</span>
                    <span className="font-semibold">{check_out_date} {check_out_day}</span>
                    <span className="text-sm text-neutral-500 ml-1">/ {year}</span>
                </div>

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

}

function PaymentOption({ value, onChange }: { value: string, onChange: (val: string) => void }) {

    return (
        <div className="space-y-3">
            <h3 className="text-base font-semibold text-neutral-500 flex items-center gap-2">
                <CreditCard className="w-4 h-4" /> Payment Option
            </h3>

            <RadioGroup value={value} onValueChange={onChange} className="space-y-2">
                <Label className="flex items-start gap-3 p-3 border rounded-lg cursor-pointer hover:border-main transition">
                    <RadioGroupItem value="pay_now" className="mt-1" />
                    <div className="flex flex-col text-sm">
                        <span className="font-medium">Pay Now</span>
                        <span className="text-neutral-500">
                            Secure your booking instantly with online payment.
                        </span>
                    </div>
                </Label>

                <Label className="flex items-start gap-3 p-3 border rounded-lg cursor-pointer hover:border-main transition">
                    <RadioGroupItem value="pay_at_hotel" className="mt-1" />
                    <div className="flex flex-col text-sm">
                        <span className="font-medium">Pay at Hotel</span>
                        <span className="text-neutral-500">
                            Reserve now and settle the payment upon arrival.
                        </span>
                    </div>
                </Label>
            </RadioGroup>
        </div>
    )
}

function BookingCard({ booking, onClick, updatePaymentMethod }: { booking: CheckoutBookingInput, onClick: () => void, updatePaymentMethod: (value: string) => void }) {


    return <div className="flex-1  bg-white p-6 rounded-lg border border-main/40 space-y-4 shadow-lg  h-fit">

        <CheckInOutDetails checkIn={booking.check_in} checkOut={booking.check_out} adults={calAdultTotal(booking.rooms)} children={calChildrenTotal(booking.rooms)} />
        <Separator />

        <div className="space-y-4 transform duration-500 ease-in">
            <h2 className="text-base text-neutral-500 font-semibold flex items-center gap-2"><DollarSign className="w-4 h-4" /> Booking Summary  </h2>

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

                {
                    booking.rooms.map((room, index) => <div key={index} className="flex justify-between border-b-2 border-dashed pb-2">
                        <span>Room 0{index + 1}</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-b-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-b-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 className="pt-4 flex justify-between font-semibold text-lg">
                    <span>Total</span>
                    <span><Price value={calBookingTotal(booking)} /></span>
                </div>

            </div>
        </div>

        <Separator />

        <PaymentOption value={booking.payment_option} onChange={updatePaymentMethod} />

        <button onClick={onClick} className="w-full bg-black text-white py-3 rounded-lg font-semibold hover:opacity-90 transition">
            (<Price value={calBookingTotal(booking)} />)  Proceed to Payment
        </button>

    </div >

}

function GuestInfoForm({ guest, updateGuest, errors }: GuestInfoFormProp) {


    return <div className="flex-2 h-fit p-6 border rounded-none bg-white">
        <h2 className="text-xl font-semibold text-gray-800 mb-6 flex items-center gap-2">
            <Users size={20} /> Guest Details
        </h2>

        <div className="flex flex-col gap-5">
            <div className="space-y-4">
                <div className="grid grid-cols-2 gap-8">
                    <InputField label="First Name" value={guest.first_name} onChange={value => updateGuest('first_name', value)} error={errors['guest.first_name']} />
                    <InputField label="Last Name" value={guest.last_name} onChange={value => updateGuest('last_name', value)} error={errors['guest.last_name']} />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-8 mt-4">
                    <InputField label="Email Address" type='email' value={guest.email} onChange={value => updateGuest('email', value)} error={errors['guest.email']} />
                    <InputField label="Phone Number" value={guest.phone} onChange={value => updateGuest('phone', value)} error={errors['guest.phone']} />
                </div>
                <div className="grid grid-cols-1 sm:grid-cols-2 gap-8 mt-4">
                    <InputField label="Passport Number (Optional)" value={guest.passport} onChange={value => updateGuest('passport', value)} error={errors['guest.passport']} />
                    <CountrySelector label="Country" value={guest.country} onChange={value => updateGuest('country', value)} classNameField='rounded-sm shadow-none' error={errors['guest.country']} />
                </div>

                <TextAreaField label="Special Requests" value={guest.special_requests} onChange={value => updateGuest('special_requests', value)} error={errors['guest.special_requests']} classNameTextArea="min-h-32" />
            </div>
        </div>
    </div>
}

export default function CheckoutPage({ booking }: { booking: CheckoutBookingInput }) {


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



    const [confirmOpen, setConfirmOpen] = useState(false)

    // Inside your CheckoutPage component
    function updateGuest(field: keyof typeof data.guest, value: string) {
        setData(`guest.${field}`, value);
    }

    function updatePaymentMethod(value: string) {
        setData('payment_option', value)
    }

    console.log(data);
    function proceedBooking() {

        post('/booking/update-checkout', {
            preserveState: true,
            preserveScroll: true,
            onSuccess: () => {

                if (data.payment_option === "pay_now") {
                    // router.visit('/payment');
                } else {
                    // router.visit('/booking/confirm');
                }

                setConfirmOpen(true)
                toast.success('Successfuly Updated Booking Data')

            },
            onError: () => toast.error('Please check again guest details!')

        })
    }

    return (
        <PageLayout title="Checkout">
            <div className="max-w-300 2xl:max-w-340 mx-auto py-10 mb-14 px-4 space-y-6 min-h-screen">

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

                <div className="flex gap-6">

                    {/* LEFT SIDE: Step Content */}
                    <GuestInfoForm guest={data.guest} updateGuest={updateGuest} errors={errors} />

                    {/* RIGHT SIDE: Booking Summary */}
                    <BookingCard booking={data} onClick={proceedBooking} updatePaymentMethod={updatePaymentMethod} />

                </div>

            </div>

            <ConfirmBooking
                open={confirmOpen}
                setOpen={setConfirmOpen}
                booking={booking}
            />
        </PageLayout>
    );
}