'use client';

import DashboardLayout from '@/app/dashboard/layout';
import { useEffect, useState, useRef, useCallback, useMemo } 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';
import {
  Calendar,
  Clock,
  Users,
  DollarSign,
  UtensilsCrossed,
  CheckCircle2,
  XCircle,
  Search,
  Sparkles,
  MessageSquare,
  Copy,
  Check,
  RefreshCw,
  Filter,
  User,
  X,
  SlidersHorizontal,
  ChevronRight,
  AlertCircle,
  CalendarX,
  PartyPopper,
  TrendingUp,
  Eye,
  CheckCircle
} from 'lucide-react';

const getStatusBadge = (status?: string) => {
  if (!status) return null;
  const lowerStatus = status.toLowerCase();

  if (lowerStatus === 'arrived') {
    return (
      <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-emerald-50 text-emerald-700 border border-emerald-200/80 shadow-xs">
        <span className="relative flex h-2 w-2">
          <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
          <span className="relative inline-flex rounded-full h-2 w-2 bg-emerald-500"></span>
        </span>
        Arrived
      </span>
    );
  }
  if (lowerStatus === 'refunded' || lowerStatus === 'paid') {
    return (
      <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-blue-50 text-blue-700 border border-blue-200/80 shadow-xs">
        <span className="h-2 w-2 rounded-full bg-blue-500"></span>
        {status.charAt(0).toUpperCase() + status.slice(1)}
      </span>
    );
  }
  if (lowerStatus === 'cancelled' || lowerStatus === 'cancel') {
    return (
      <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-rose-50 text-rose-700 border border-rose-200/80 shadow-xs">
        <span className="h-2 w-2 rounded-full bg-rose-500"></span>
        Cancelled
      </span>
    );
  }

  return (
    <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-xs font-semibold bg-amber-50 text-amber-700 border border-amber-200/80 shadow-xs">
      <span className="relative flex h-2 w-2">
        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-amber-400 opacity-75"></span>
        <span className="relative inline-flex rounded-full h-2 w-2 bg-amber-500"></span>
      </span>
      Pending
    </span>
  );
};

const getInitials = (name?: string) => {
  if (!name) return 'G';
  const parts = name.trim().split(' ');
  if (parts.length >= 2) {
    return (parts[0][0] + parts[1][0]).toUpperCase();
  }
  return name.slice(0, 2).toUpperCase();
};

const BookingList = () => {
  const { userInfo, setOrderInfo, Toast } = useGlobalContext();
  const searchParams = useSearchParams();
  const [bookings, setBookings] = useState<any[]>([]);
  const [page, setPage] = useState(Number(searchParams.get('page')) || 1);
  const [loading, setLoading] = useState(true);
  const [hasMore, setHasMore] = useState(true);
  const [updatingId, setUpdatingId] = useState<string | null>(null);
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const [selectedBooking, setSelectedBooking] = useState<any | null>(null);

  const limit = 40;

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

    try {
      if (!append) setLoading(true);
      const params = new URLSearchParams({
        page: currentPage.toString(),
        limit: limit.toString(),
        restaurant_id: 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, e?: React.MouseEvent) => {
    if (e) e.stopPropagation();
    try {
      setUpdatingId(id);
      await apis.Booking.updateBooking({ id, status });
      if (Toast?.success) {
        Toast.success(`Booking updated to ${status}`);
      }
      if (selectedBooking && selectedBooking._id === id) {
        setSelectedBooking((prev: any) => prev ? { ...prev, status } : null);
      }
      setBookings((prev) =>
        prev.map((b) => (b._id === id ? { ...b, status } : b))
      );
    } catch (error) {
      console.error('Error updating booking status:', error);
      if (Toast?.error) {
        Toast.error('Failed to update booking status');
      }
    } finally {
      setUpdatingId(null);
    }
  };

  const handleCopyId = (e: React.MouseEvent, idStr: string) => {
    e.stopPropagation();
    navigator.clipboard.writeText(idStr);
    setCopiedId(idStr);
    if (Toast?.success) {
      Toast.success(`Copied Booking ID #${idStr}`);
    }
    setTimeout(() => setCopiedId(null), 2000);
  };

  return (
    <div className="min-h-screen bg-slate-50/70 p-4 sm:p-6 lg:p-8">
      {/* Bookings Card Grid */}
      {loading ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <div
              key={i}
              className="h-64 rounded-2xl bg-white border border-slate-200/80 p-5 animate-pulse space-y-4 shadow-xs"
            >
              <div className="flex items-center justify-between">
                <div className="flex items-center gap-3">
                  <div className="h-10 w-10 rounded-full bg-slate-200"></div>
                  <div className="space-y-2">
                    <div className="h-4 w-28 bg-slate-200 rounded-sm"></div>
                    <div className="h-3 w-20 bg-slate-100 rounded-sm"></div>
                  </div>
                </div>
                <div className="h-6 w-16 bg-slate-200 rounded-full"></div>
              </div>
              <div className="h-24 bg-slate-100 rounded-xl"></div>
              <div className="h-9 bg-slate-200 rounded-xl"></div>
            </div>
          ))}
        </div>
      ) : bookings.length > 0 ? (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {bookings.map((booking, index) => {
            const isLast = bookings.length === index + 1;
            const customerName = booking?.customer_id?.name || 'Guest Customer';
            const bookingIdStr = booking?.booking_id
              ? booking.booking_id.toString().replace(/^#/, '')
              : booking._id.slice(-8).toUpperCase();
            const statusLower = booking?.status?.toLowerCase() || 'pending';

            let cardAccentClass = 'border-t-4 border-amber-500';
            if (statusLower === 'arrived') cardAccentClass = 'border-t-4 border-emerald-500';
            if (statusLower === 'paid' || statusLower === 'refunded') cardAccentClass = 'border-t-4 border-blue-500';
            if (statusLower === 'cancelled' || statusLower === 'cancel') cardAccentClass = 'border-t-4 border-rose-500';

            return (
              <div
                key={booking._id}
                ref={isLast ? lastBookingRef : null}
                className={`group relative bg-white rounded-2xl border border-slate-200/80 shadow-xs hover:shadow-md hover:-translate-y-0.5 transition-all duration-200 flex flex-col justify-between overflow-hidden ${cardAccentClass}`}
              >
                <div className="p-5 space-y-4">
                  {/* Card Header: Customer info & Status */}
                  <div className="flex items-start justify-between gap-3">
                    <div className="flex items-center gap-3 min-w-0">
                      <div className="h-11 w-11 rounded-full bg-gradient-to-br from-amber-500 to-orange-600 text-white font-bold text-sm flex items-center justify-center shrink-0 shadow-xs">
                        {getInitials(customerName)}
                      </div>
                      <div className="min-w-0">
                        <h3
                          onClick={() => setSelectedBooking(booking)}
                          className="font-bold text-slate-900 text-base leading-snug truncate hover:text-orange-600 transition-colors cursor-pointer"
                        >
                          {customerName}
                        </h3>
                        <div className="flex items-center gap-1.5 mt-0.5">
                          <span className="text-xs font-mono font-medium text-slate-500">
                            #{bookingIdStr}
                          </span>
                          <button
                            onClick={(e) => handleCopyId(e, bookingIdStr)}
                            title="Copy ID"
                            className="text-slate-400 hover:text-slate-600 p-0.5 rounded-sm hover:bg-slate-100 transition-colors cursor-pointer"
                          >
                            {copiedId === bookingIdStr ? (
                              <Check className="h-3 w-3 text-emerald-600" />
                            ) : (
                              <Copy className="h-3 w-3" />
                            )}
                          </button>
                        </div>
                      </div>
                    </div>

                    <div className="shrink-0">{getStatusBadge(booking?.status)}</div>
                  </div>

                  {/* Created timestamp */}
                  <div className="flex items-center gap-1.5 text-[11px] text-slate-400">
                    <Clock className="h-3 w-3 text-slate-400" />
                    <span>
                      Booked at {dayjs(booking.createdAt).format('DD MMM YYYY, hh:mm A')}
                    </span>
                  </div>

                  {/* Booking Details Box */}
                  <div className="rounded-xl bg-slate-50/80 border border-slate-100 p-3.5 space-y-2.5">
                    {/* Time Slot Highlight */}
                    <div className="flex items-center justify-between bg-white px-3 py-2 rounded-lg border border-slate-200/60 shadow-2xs">
                      <span className="text-xs font-medium text-slate-500 flex items-center gap-1.5">
                        <Calendar className="h-3.5 w-3.5 text-orange-500" />
                        Reserved Slot
                      </span>
                      <span className="text-xs font-bold text-slate-900">
                        {booking?.slot_id?.start
                          ? dayjs(booking.slot_id.start).format('DD MMM YYYY, hh:mm A')
                          : 'N/A'}
                      </span>
                    </div>

                    {/* Guests & Amount Grid */}
                    <div className="grid grid-cols-2 gap-2 pt-1">
                      <div className="flex items-center gap-2 bg-white px-3 py-2 rounded-lg border border-slate-200/60">
                        <Users className="h-3.5 w-3.5 text-indigo-500 shrink-0" />
                        <div>
                          <p className="text-[10px] uppercase font-semibold text-slate-400">
                            Guests
                          </p>
                          <p className="text-xs font-bold text-slate-800">
                            {booking?.no_of_guest || 1} {booking?.no_of_guest === 1 ? 'Guest' : 'Guests'}
                          </p>
                        </div>
                      </div>

                      <div className="flex items-center gap-2 bg-white px-3 py-2 rounded-lg border border-slate-200/60">
                        <DollarSign className="h-3.5 w-3.5 text-emerald-500 shrink-0" />
                        <div>
                          <p className="text-[10px] uppercase font-semibold text-slate-400">
                            Amount
                          </p>
                          <p className="text-xs font-bold text-slate-900">
                            {currency}{booking?.total_booking_amount ?? 0}
                          </p>
                        </div>
                      </div>
                    </div>

                    {/* Occasion Badge if available */}
                    {booking?.occasion_type && (
                      <div className="pt-2 border-t border-slate-200/60 flex items-start gap-1.5">
                        <Sparkles className="h-3.5 w-3.5 text-amber-500 shrink-0 mt-0.5" />
                        <div className="min-w-0">
                          <p className="text-[10px] uppercase font-semibold text-slate-400">
                            Occasion
                          </p>
                          <p className="text-xs font-semibold text-slate-800 truncate">
                            {booking.occasion_type}
                          </p>
                        </div>
                      </div>
                    )}

                    {/* Special Request */}
                    {booking?.special_request && (
                      <div className="pt-2 border-t border-slate-200/60">
                        <div className="flex items-center gap-1.5 text-slate-500 text-[11px] font-medium mb-1">
                          <MessageSquare className="h-3 w-3 text-orange-500" />
                          <span>Special Request</span>
                        </div>
                        <p className="text-xs text-slate-700 bg-white p-2 rounded-lg border border-slate-200/80 italic leading-relaxed">
                          "{booking.special_request}"
                        </p>
                      </div>
                    )}
                  </div>
                </div>

                {/* Card Footer Actions */}
                <div className="p-3.5 bg-slate-50/50 border-t border-slate-100 flex items-center gap-1.5 sm:gap-2">
                  <button
                    onClick={() => setSelectedBooking(booking)}
                    className="flex-1 py-2 px-2.5 sm:px-3 rounded-xl border border-slate-200 hover:bg-slate-100 text-xs font-semibold text-slate-700 transition-colors flex items-center justify-center gap-1 sm:gap-1.5 cursor-pointer whitespace-nowrap shrink-0"
                  >
                    <Eye className="h-3.5 w-3.5 text-slate-500 shrink-0" />
                    <span>Details</span>
                  </button>

                  {!['arrived', 'refunded', 'cancelled', 'cancel'].includes(statusLower) && (
                    <>
                      <button
                        disabled={updatingId === booking._id}
                        onClick={(e) => updateBookingStatus(booking._id, 'cancel', e)}
                        className="py-2 px-2.5 sm:px-3 rounded-xl bg-rose-50 hover:bg-rose-100 text-rose-700 text-xs font-semibold transition-colors flex items-center justify-center gap-1 border border-rose-200/60 disabled:opacity-50 cursor-pointer whitespace-nowrap shrink-0"
                      >
                        <XCircle className="h-3.5 w-3.5 shrink-0" />
                        <span>Cancel</span>
                      </button>

                      <button
                        disabled={updatingId === booking._id}
                        onClick={(e) => updateBookingStatus(booking._id, 'arrived', e)}
                        className="flex-1 py-2 px-2.5 sm:px-3 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white text-xs font-semibold shadow-xs transition-all flex items-center justify-center gap-1.5 disabled:opacity-50 cursor-pointer whitespace-nowrap shrink-0"
                      >
                        <CheckCircle2 className="h-3.5 w-3.5 shrink-0" />
                        <span>{updatingId === booking._id ? 'Updating...' : 'Arrived'}</span>
                      </button>
                    </>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      ) : (
        /* Empty State */
        <div className="bg-white rounded-2xl border border-slate-200/80 p-12 text-center space-y-4 max-w-md mx-auto my-8 shadow-xs">
          <div className="h-16 w-16 bg-amber-50 text-amber-500 rounded-2xl flex items-center justify-center mx-auto">
            <CalendarX className="h-8 w-8" />
          </div>
          <div>
            <h3 className="text-lg font-bold text-slate-900">No Bookings Found</h3>
            <p className="text-xs text-slate-500 mt-1">
              No table bookings have been placed yet.
            </p>
          </div>
        </div>
      )}

      {/* Booking Details Modal */}
      {selectedBooking && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-slate-900/60 backdrop-blur-xs p-4 animate-in fade-in duration-200">
          <div className="relative w-full max-w-lg rounded-2xl bg-white p-6 shadow-2xl border border-slate-100 max-h-[90vh] overflow-y-auto space-y-6">
            {/* Modal Header */}
            <div className="flex items-start justify-between border-b border-slate-100 pb-4">
              <div className="flex items-center gap-3">
                <div className="h-12 w-12 rounded-full bg-gradient-to-br from-amber-500 to-orange-600 text-white font-bold text-base flex items-center justify-center shadow-xs">
                  {getInitials(selectedBooking?.customer_id?.name)}
                </div>
                <div>
                  <h3 className="text-lg font-bold text-slate-900">
                    {selectedBooking?.customer_id?.name || 'Guest Customer'}
                  </h3>
                  <p className="text-xs text-slate-500 font-mono">
                    Booking ID: #{selectedBooking?.booking_id ? selectedBooking.booking_id.toString().replace(/^#/, '') : selectedBooking._id}
                  </p>
                </div>
              </div>
              <button
                onClick={() => setSelectedBooking(null)}
                className="text-slate-400 hover:text-slate-600 p-1 rounded-lg hover:bg-slate-100 transition-colors cursor-pointer"
              >
                <X className="h-5 w-5" />
              </button>
            </div>

            {/* Modal Body */}
            <div className="space-y-4 text-xs text-slate-700">
              <div className="flex items-center justify-between bg-slate-50 p-3 rounded-xl border border-slate-100">
                <span className="font-semibold text-slate-500">Current Status</span>
                {getStatusBadge(selectedBooking?.status)}
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 space-y-1">
                  <span className="text-[10px] font-semibold text-slate-400 uppercase">Guests</span>
                  <p className="text-sm font-bold text-slate-900 flex items-center gap-1.5">
                    <Users className="h-4 w-4 text-indigo-500" />
                    {selectedBooking?.no_of_guest || 1} Person(s)
                  </p>
                </div>

                <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 space-y-1">
                  <span className="text-[10px] font-semibold text-slate-400 uppercase">Total Amount</span>
                  <p className="text-sm font-bold text-slate-900 flex items-center gap-1.5">
                    <DollarSign className="h-4 w-4 text-emerald-500" />
                    {currency}{selectedBooking?.total_booking_amount ?? 0}
                  </p>
                </div>
              </div>

              <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-100 space-y-2">
                <span className="text-[10px] font-semibold text-slate-400 uppercase block">Reserved Time Slot</span>
                <div className="flex items-center gap-2 text-sm font-bold text-slate-800">
                  <Calendar className="h-4 w-4 text-orange-500" />
                  {selectedBooking?.slot_id?.start
                    ? dayjs(selectedBooking.slot_id.start).format('dddd, DD MMMM YYYY, hh:mm A')
                    : 'N/A'}
                </div>
              </div>

              {selectedBooking?.occasion_type && (
                <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-100 space-y-1">
                  <span className="text-[10px] font-semibold text-slate-400 uppercase block">Occasion</span>
                  <p className="text-xs font-semibold text-slate-800 flex items-center gap-1.5">
                    <Sparkles className="h-4 w-4 text-amber-500" />
                    {selectedBooking.occasion_type}
                  </p>
                </div>
              )}

              {selectedBooking?.special_request && (
                <div className="bg-slate-50 p-3.5 rounded-xl border border-slate-100 space-y-1">
                  <span className="text-[10px] font-semibold text-slate-400 uppercase block">Special Request</span>
                  <p className="text-xs text-slate-700 italic bg-white p-2.5 rounded-lg border border-slate-200/80">
                    "{selectedBooking.special_request}"
                  </p>
                </div>
              )}

              <div className="pt-2 text-[11px] text-slate-400 border-t border-slate-100 flex items-center justify-between">
                <span>Booking Date</span>
                <span className="font-semibold text-slate-600">
                  {dayjs(selectedBooking.createdAt).format('DD MMM YYYY, hh:mm A')}
                </span>
              </div>
            </div>

            {/* Modal Actions */}
            <div className="border-t border-slate-100 pt-4 flex items-center gap-3">
              <button
                onClick={() => setSelectedBooking(null)}
                className="flex-1 py-2.5 px-4 rounded-xl border border-slate-200 text-xs font-semibold text-slate-700 hover:bg-slate-100 transition-colors cursor-pointer"
              >
                Close
              </button>

              {!['arrived', 'refunded', 'cancelled', 'cancel'].includes(
                selectedBooking?.status?.toLowerCase() || ''
              ) && (
                  <>
                    <button
                      disabled={updatingId === selectedBooking._id}
                      onClick={() => updateBookingStatus(selectedBooking._id, 'cancel')}
                      className="py-2.5 px-4 rounded-xl bg-rose-50 text-rose-700 text-xs font-semibold hover:bg-rose-100 border border-rose-200/60 transition-colors cursor-pointer"
                    >
                      Cancel Booking
                    </button>
                    <button
                      disabled={updatingId === selectedBooking._id}
                      onClick={() => updateBookingStatus(selectedBooking._id, 'arrived')}
                      className="flex-1 py-2.5 px-4 rounded-xl bg-gradient-to-r from-emerald-600 to-teal-600 hover:from-emerald-700 hover:to-teal-700 text-white text-xs font-semibold shadow-xs transition-all cursor-pointer"
                    >
                      Mark as Arrived
                    </button>
                  </>
                )}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

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

