'use client';
import DashboardLayout from '@/app/dashboard/layout';
import { useEffect, useState, useRef, useCallback } from 'react';
import { useGlobalContext } from '@/context/Provider';
import { useSearchParams } from 'next/navigation';
import dayjs from 'dayjs';
import apis from '@/utils/apis';
import { currency } from '@/lib/utils';

const BookingList = () => {
    const { userInfo, setOrderInfo, orderInfo } = useGlobalContext();
    const searchParams = useSearchParams();
    const [activeModal, setActiveModal] = useState<string | null>(null);
    const [bookings, setBookings] = useState<any[]>([]);
    const [page, setPage] = useState(Number(searchParams.get('page')) || 1);
    const [loading, setLoading] = useState(false);
    const [hasMore, setHasMore] = useState(true);
    const limit = 40;

    const fetchBookings = async (currentPage: number, append = false) => {
        const restaurant_id = userInfo?.restaurant_id?._id;

        try {
            setLoading(true);
            const params = new URLSearchParams({
                page: currentPage.toString(),
                limit: limit.toString(),
                restaurant_id
            });
            const apiRes = await apis.Booking.getBooking(params.toString());
            const data = apiRes?.data || [];

            if (append) {
                setBookings((prev) => [...prev, ...data]);
            } else {
                setBookings(data);
            }

            setHasMore(data.length === limit);
        } catch (error) {
            console.error('Error fetching bookings:', error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        if (userInfo?._id) {
            fetchBookings(page, false);
        }
    }, [userInfo]);

    const observer = useRef<IntersectionObserver | null>(null);
    const lastBookingRef = useCallback(
        (node: any) => {
            if (loading) return;
            if (observer.current) observer.current.disconnect();

            observer.current = new IntersectionObserver((entries) => {
                if (entries[0].isIntersecting && hasMore) {
                    const nextPage = page + 1;
                    setPage(nextPage);
                    fetchBookings(nextPage, true);
                }
            });

            if (node) observer.current.observe(node);
        },
        [loading, hasMore, page]
    );

    const updateBookingStatus = async (id: string, status: string) => {
        try {
            await apis.Booking.updateBooking({ id, status });
            setBookings([]);
            setPage(1);
            fetchBookings(1, false);
        } catch (error) {
            console.error('Error updating booking status:', error);
        }
    };

    return (
        <div className="grid h-[92vh] grid-cols-1 gap-6 overflow-y-auto bg-gray-50 p-4 md:grid-cols-2 lg:grid-cols-3">
            {bookings.length > 0 ? (
                bookings.map((booking, index) => {
                    const isLast = bookings.length === index + 1;
                    return (
                        <div
                            key={booking._id}
                            ref={isLast ? lastBookingRef : null}
                            className="min-h-[280px] h-fit rounded-lg bg-white shadow-lg shadow-gray-500/50 flex flex-col justify-between"                        >
                            {/* Header */}
                            <div
                                className="p-6 cursor-pointer"
                                onClick={() => {
                                    setActiveModal('bookingDetail');
                                    setOrderInfo(booking);
                                }}
                            >
                                <div className="mb-4 flex items-start justify-between">
                                    <div>
                                        <h3 className="text-[10px] font-[500] text-[#333]">
                                            Booking Id: {booking.booking_id}
                                        </h3>
                                        <p className="text-[14px] font-[500] text-[var(--orange-400)]">
                                            {booking?.customer_id?.name}
                                        </p>
                                    </div>
                                    <span className="text-[10px] font-[500] text-[#808080]">
                                        {dayjs(booking.createdAt).format('DD MMM YYYY hh:mm a')}
                                    </span>
                                </div>
                                <div className="mb-0 p-2 rounded-lg border border-gray-200 shadow-sm bg-white w-full max-w-sm">
                                    <h3 className="text-[11px] font-semibold text-gray-500 mb-1">
                                        Booking ID: <span className="text-gray-800">{booking.booking_id}</span>
                                    </h3>

                                    <div className="mt-2 space-y-1">
                                        <p className="text-sm text-gray-700">
                                            👥 <span className="font-medium">Guests:</span> {booking?.no_of_guest}
                                        </p>

                                        <p className="text-sm text-gray-700">
                                            💰 <span className="font-medium">Amount:</span> {currency}{booking?.total_booking_amount}
                                        </p>

                                        <p className="text-sm text-gray-700">
                                            🕒 <span className="font-medium">Slot:</span> {dayjs(booking?.slot_id?.start).format('DD/MM/YYYY, HH:mm')}
                                        </p>

                                        {booking?.occasion_type && (
                                            <p className="text-sm text-gray-700">
                                                🎉 <span className="font-medium">Occasion:</span> {booking.occasion_type}
                                            </p>
                                        )}

                                        {booking?.special_request && (
                                            <p className="text-sm text-gray-700">
                                                📝 <span className="font-medium">Special Request:</span> {booking.special_request}
                                            </p>
                                        )}
                                    </div>
                                </div>
                            </div>

                            {/* Action Buttons */}
                            {!["arrived", "Refunded"]?.includes(booking.status) && (
                                <div className="flex gap-3 px-6 pb-6 mb-0">
                                    <button
                                        className="flex-1 rounded-lg bg-[#FC2424] px-4 py-2 text-[14px] font-[600] text-white hover:bg-red-600"
                                        onClick={() => updateBookingStatus(booking._id, 'cancel')}
                                    >
                                        Cancel
                                    </button>
                                    <button
                                        className="flex-1 rounded-lg bg-[var(--primary-brand)] px-4 py-2 text-[14px] font-[600] text-[#ffffff] hover:bg-[var(--primary-brand)]"
                                        onClick={() => updateBookingStatus(booking._id, 'arrived')}
                                    >
                                        Arrived
                                    </button>
                                </div>
                            )}

                        </div>
                    );
                })
            ) : (
                <p className="col-span-full text-center">
                    {loading ? 'Loading bookings...' : 'No bookings to show.'}
                </p>
            )}
        </div>
    );
};

export default function BookingPage() {
    return (
        <DashboardLayout>
            <BookingList />
        </DashboardLayout>
    );
}
