"use client";

import { useState, useEffect, useMemo, useRef } from "react";
import { useRouter } from "next/navigation";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Calendar } from "@/components/ui/calendar";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { toast } from "sonner";
import { format } from "date-fns";
import {
  Hotel,
  CalendarIcon,
  MapPin,
  Users,
  Star,
  CheckCircle2,
  Wifi,
  Car,
  Coffee,
  Utensils,
  Dumbbell,
  Waves,
  BedDouble,
  Bath,
  Tv,
  Wind,
  Bed,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { getClientSession, validateSessionData } from "@/features/auth";

// Mock data for locations
const locations = [
  { id: "varanasi", name: "Varanasi" },
  { id: "haridwar", name: "Haridwar" },
  { id: "rishikesh", name: "Rishikesh" },
  { id: "mathura", name: "Mathura" },
  { id: "vrindavan", name: "Vrindavan" },
  { id: "ayodhya", name: "Ayodhya" },
  { id: "tirupati", name: "Tirupati" },
  { id: "shirdi", name: "Shirdi" },
  { id: "puri", name: "Puri" },
  { id: "dwarka", name: "Dwarka" },
];

// Mock data for hotels
const allHotels = [
  {
    id: "h1",
    name: "Taj Ganges",
    location: "varanasi",
    image: "/placeholder.png?height=200&width=350",
    rating: 4.8,
    reviews: 1250,
    priceRange: "₹8,000 - ₹25,000",
    amenities: ["Free WiFi", "Pool", "Spa", "Restaurant", "Gym", "Parking"],
    rooms: [
      {
        id: "r1",
        name: "Deluxe Room",
        price: 8000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Bathroom"],
      },
      {
        id: "r2",
        name: "Premium Suite",
        price: 15000,
        maxGuests: 3,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "Living Area", "AC", "TV", "Bathtub"],
      },
      {
        id: "r3",
        name: "Royal Suite",
        price: 25000,
        maxGuests: 4,
        image: "/placeholder.png?height=120&width=200",
        amenities: [
          "2 King Beds",
          "Living Area",
          "Balcony",
          "AC",
          "TV",
          "Jacuzzi",
        ],
      },
    ],
  },
  {
    id: "h2",
    name: "BrijRama Palace",
    location: "varanasi",
    image: "/placeholder.png?height=200&width=350",
    rating: 4.9,
    reviews: 890,
    priceRange: "₹12,000 - ₹45,000",
    amenities: ["Free WiFi", "Ganga View", "Spa", "Restaurant", "Heritage"],
    rooms: [
      {
        id: "r4",
        name: "Heritage Room",
        price: 12000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "River View"],
      },
      {
        id: "r5",
        name: "Maharaja Suite",
        price: 30000,
        maxGuests: 3,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "Living Area", "AC", "TV", "Private Terrace"],
      },
      {
        id: "r6",
        name: "Royal Chamber",
        price: 45000,
        maxGuests: 4,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["2 King Beds", "Living Area", "AC", "TV", "Private Pool"],
      },
    ],
  },
  {
    id: "h3",
    name: "Haveli Hari Ganga",
    location: "haridwar",
    image: "/placeholder.png?height=200&width=350",
    rating: 4.6,
    reviews: 720,
    priceRange: "₹5,000 - ₹18,000",
    amenities: ["Free WiFi", "Ganga View", "Restaurant", "Temple Access"],
    rooms: [
      {
        id: "r7",
        name: "Standard Room",
        price: 5000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["Queen Bed", "AC", "TV"],
      },
      {
        id: "r8",
        name: "Ganga View Room",
        price: 9000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Balcony"],
      },
      {
        id: "r9",
        name: "Family Suite",
        price: 18000,
        maxGuests: 5,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["2 Queen Beds", "Living Area", "AC", "TV"],
      },
    ],
  },
  {
    id: "h4",
    name: "Divine Resort",
    location: "rishikesh",
    image: "/placeholder.png?height=200&width=350",
    rating: 4.7,
    reviews: 540,
    priceRange: "₹4,000 - ₹15,000",
    amenities: [
      "Free WiFi",
      "Yoga Center",
      "Spa",
      "Restaurant",
      "Mountain View",
    ],
    rooms: [
      {
        id: "r10",
        name: "Cottage Room",
        price: 4000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["Double Bed", "AC", "TV"],
      },
      {
        id: "r11",
        name: "Deluxe Cottage",
        price: 8000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Private Garden"],
      },
      {
        id: "r12",
        name: "Premium Villa",
        price: 15000,
        maxGuests: 4,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["2 King Beds", "Living Area", "AC", "Private Pool"],
      },
    ],
  },
  {
    id: "h5",
    name: "Krishna Palace",
    location: "mathura",
    image: "/placeholder.png?height=200&width=350",
    rating: 4.4,
    reviews: 380,
    priceRange: "₹3,000 - ₹12,000",
    amenities: ["Free WiFi", "Temple View", "Restaurant", "Parking"],
    rooms: [
      {
        id: "r13",
        name: "Standard Room",
        price: 3000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["Double Bed", "AC", "TV"],
      },
      {
        id: "r14",
        name: "Temple View Room",
        price: 6000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Balcony"],
      },
      {
        id: "r15",
        name: "Family Room",
        price: 12000,
        maxGuests: 4,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["2 Queen Beds", "AC", "TV", "Mini Kitchen"],
      },
    ],
  },
  {
    id: "h6",
    name: "Ganga Kinare",
    location: "rishikesh",
    image: "/placeholder.png?height=200&width=350",
    rating: 4.5,
    reviews: 620,
    priceRange: "₹6,000 - ₹20,000",
    amenities: ["Free WiFi", "River View", "Restaurant", "Yoga", "Spa"],
    rooms: [
      {
        id: "r16",
        name: "River View Room",
        price: 6000,
        maxGuests: 2,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Balcony"],
      },
      {
        id: "r17",
        name: "Premium Room",
        price: 12000,
        maxGuests: 3,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["King Bed", "Living Area", "AC", "TV"],
      },
      {
        id: "r18",
        name: "Luxury Suite",
        price: 20000,
        maxGuests: 4,
        image: "/placeholder.png?height=120&width=200",
        amenities: ["2 King Beds", "Living Area", "AC", "Private Balcony"],
      },
    ],
  },
];

const amenityIcons: Record<string, any> = {
  "Free WiFi": Wifi,
  Pool: Waves,
  Spa: Bath,
  Restaurant: Utensils,
  Gym: Dumbbell,
  Parking: Car,
  "Ganga View": Waves,
  Heritage: Hotel,
  "Temple Access": Hotel,
  "Yoga Center": Hotel,
  "Mountain View": Hotel,
  "Temple View": Hotel,
  "River View": Waves,
  Yoga: Hotel,
};

const roomAmenityIcons: Record<string, any> = {
  "King Bed": BedDouble,
  "Queen Bed": BedDouble,
  "Double Bed": BedDouble,
  "2 King Beds": BedDouble,
  "2 Queen Beds": BedDouble,
  AC: Wind,
  TV: Tv,
  Bathroom: Bath,
  Bathtub: Bath,
  Jacuzzi: Bath,
  "Living Area": Hotel,
  Balcony: Hotel,
  "River View": Waves,
  "Private Terrace": Hotel,
  "Private Pool": Waves,
  "Private Garden": Hotel,
  "Mini Kitchen": Coffee,
  "Private Balcony": Hotel,
};

interface Guest {
  id: string;
  name: string;
  age: string;
  gender: string;
}

export default function BookHotelPage() {
  const router = useRouter();

  // Booking form state
  const [location, setLocation] = useState<string>("");
  const [checkInDate, setCheckInDate] = useState<Date>();
  const [checkOutDate, setCheckOutDate] = useState<Date>();
  const [selectedHotel, setSelectedHotel] = useState<string | null>(null);
  const [selectedRoom, setSelectedRoom] = useState<string | null>(null);
  const [guests, setGuests] = useState<string>("2");

  const [guestDetails, setGuestDetails] = useState<Guest[]>([]);

  const [expandedHotel, setExpandedHotel] = useState<string | null>(null);
  const roomTypesRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (guests) {
      const count = Number.parseInt(guests);
      const currentCount = guestDetails.length;
      if (count > currentCount) {
        const newGuests = Array.from(
          { length: count - currentCount },
          (_, i) => ({
            id: `g-${Date.now()}-${i}`,
            name: "",
            age: "",
            gender: "",
          })
        );
        setGuestDetails([...guestDetails, ...newGuests]);
      } else if (count < currentCount) {
        setGuestDetails(guestDetails.slice(0, count));
      }
    }
  }, [guests]);

  // Filter hotels based on location
  const availableHotels = useMemo(() => {
    if (!location) return [];
    return allHotels.filter((hotel) => hotel.location === location);
  }, [location]);

  const selectedHotelData = useMemo(() => {
    return allHotels.find((h) => h.id === selectedHotel);
  }, [selectedHotel]);

  const selectedRoomData = useMemo(() => {
    if (!selectedHotelData) return null;
    return selectedHotelData.rooms.find((r) => r.id === selectedRoom);
  }, [selectedHotelData, selectedRoom]);

  // Calculate nights
  const nights = useMemo(() => {
    if (!checkInDate || !checkOutDate) return 0;
    const diff = checkOutDate.getTime() - checkInDate.getTime();
    return Math.ceil(diff / (1000 * 60 * 60 * 24));
  }, [checkInDate, checkOutDate]);

  const updateGuestDetail = (id: string, field: keyof Guest, value: string) => {
    setGuestDetails(
      guestDetails.map((g) => (g.id === id ? { ...g, [field]: value } : g))
    );
  };

  const handleHotelSelect = (hotelId: string) => {
    if (expandedHotel === hotelId) {
      setExpandedHotel(null);
    } else {
      setExpandedHotel(hotelId);
      setSelectedHotel(hotelId);
      setSelectedRoom(null);
      // Scroll to room types section
      setTimeout(() => {
        roomTypesRef.current?.scrollIntoView({
          behavior: "smooth",
          block: "nearest",
        });
      }, 100);
    }
  };

  const handleRoomSelect = (hotelId: string, roomId: string) => {
    setSelectedHotel(hotelId);
    setSelectedRoom(roomId);
  };

  const handleBookNow = () => {
    // Check if user is logged in
    const session = getClientSession("customer_session");
    if (!session || !validateSessionData(session)) {
      toast.error("Please login to book a hotel", {
        description: "You need to be logged in to complete the booking",
      });
      router.push("/login");
      return;
    }

    if (
      !location ||
      !checkInDate ||
      !checkOutDate ||
      !selectedHotel ||
      !selectedRoom
    ) {
      toast.error("Please fill all required fields");
      return;
    }

    // Validate guest details
    const incompleteGuest = guestDetails.find(
      (g) => !g.name || !g.age || !g.gender
    );
    if (incompleteGuest) {
      toast.error("Please fill all guest details");
      return;
    }

    toast.success("Hotel booked successfully!", {
      description: `${selectedHotelData?.name} - ${selectedRoomData?.name} booked for ${nights} nights`,
    });
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-background via-background to-muted/10">
      <div className="container mx-auto px-4 py-8">
        <div className="relative mb-8 p-6 rounded-2xl bg-gradient-to-r from-gray-900 via-gray-800 to-zinc-900 overflow-hidden shadow-xl">
          <div className="absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxwYXRoIGQ9Ik0zNiAxOGMzLjMxNCAwIDYgMi42ODYgNiA2cy0yLjY4NiA2LTYgNi02LTIuNjg2LTYtNiAyLjY4Ni02IDYtNiIgc3Ryb2tlPSJyZ2JhKDI1NSwyNTUsMjU1LDAuMSkiIHN0cm9rZS13aWR0aD0iMiIvPjwvZz48L3N2Zz4=')] opacity-20" />
          <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full blur-3xl -translate-y-1/2 translate-x-1/2" />
          <div className="relative z-10 flex items-center gap-4">
            <div className="p-3 rounded-xl bg-white/10 backdrop-blur-sm border border-white/10">
              <Hotel className="h-8 w-8 text-white" />
            </div>
            <div>
              <h1 className="text-2xl md:text-3xl font-bold text-white">
                Hotel Booking
              </h1>
              <p className="text-gray-300">
                Find perfect accommodations for your spiritual journey
              </p>
            </div>
          </div>
        </div>

        {/* Search Form */}
        <Card className="border-0 shadow-lg mb-6">
          <CardHeader>
            <CardTitle className="flex items-center gap-2 text-lg">
              <MapPin className="h-5 w-5 text-gray-700" />
              Search Hotels
            </CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
              {/* Location */}
              <div className="space-y-2">
                <Label>Location</Label>
                <Select
                  value={location}
                  onValueChange={(val) => {
                    setLocation(val);
                    setSelectedHotel(null);
                    setSelectedRoom(null);
                    setExpandedHotel(null);
                  }}
                >
                  <SelectTrigger>
                    <SelectValue placeholder="Select location" />
                  </SelectTrigger>
                  <SelectContent>
                    {locations.map((loc) => (
                      <SelectItem key={loc.id} value={loc.id}>
                        {loc.name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              {/* Check-in Date */}
              <div className="space-y-2">
                <Label>Check-in Date</Label>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      className={cn(
                        "w-full justify-start text-left font-normal",
                        !checkInDate && "text-muted-foreground"
                      )}
                    >
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {checkInDate ? format(checkInDate, "PPP") : "Select date"}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      mode="single"
                      selected={checkInDate}
                      onSelect={setCheckInDate}
                      disabled={(date) => date < new Date()}
                      initialFocus
                    />
                  </PopoverContent>
                </Popover>
              </div>

              {/* Check-out Date */}
              <div className="space-y-2">
                <Label>Check-out Date</Label>
                <Popover>
                  <PopoverTrigger asChild>
                    <Button
                      variant="outline"
                      className={cn(
                        "w-full justify-start text-left font-normal",
                        !checkOutDate && "text-muted-foreground"
                      )}
                    >
                      <CalendarIcon className="mr-2 h-4 w-4" />
                      {checkOutDate
                        ? format(checkOutDate, "PPP")
                        : "Select date"}
                    </Button>
                  </PopoverTrigger>
                  <PopoverContent className="w-auto p-0" align="start">
                    <Calendar
                      mode="single"
                      selected={checkOutDate}
                      onSelect={setCheckOutDate}
                      disabled={(date) =>
                        date < new Date() ||
                        (checkInDate ? date <= checkInDate : false)
                      }
                    />
                  </PopoverContent>
                </Popover>
              </div>

              {/* Guests */}
              <div className="space-y-2">
                <Label>Guests</Label>
                <Select value={guests} onValueChange={setGuests}>
                  <SelectTrigger>
                    <SelectValue placeholder="Select guests" />
                  </SelectTrigger>
                  <SelectContent>
                    {[1, 2, 3, 4, 5, 6].map((num) => (
                      <SelectItem key={num} value={num.toString()}>
                        {num} {num === 1 ? "Guest" : "Guests"}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* Available Hotels */}
        {location && (
          <div className="mb-6">
            <h2 className="text-base md:text-lg font-semibold mb-4 flex items-center gap-2">
              <Hotel className="h-5 w-5 text-gray-600" />
              Available Hotels
              {availableHotels.length > 0 && (
                <Badge variant="secondary" className="ml-2">
                  {availableHotels.length} found
                </Badge>
              )}
            </h2>

            {availableHotels.length === 0 ? (
              <Card className="border-0 shadow-lg">
                <CardContent className="py-12 text-center">
                  <Hotel className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                  <h3 className="text-base md:text-lg font-medium mb-2">
                    No hotels found
                  </h3>
                  <p className="text-sm text-muted-foreground">
                    No hotels available in this location. Try a different
                    location.
                  </p>
                </CardContent>
              </Card>
            ) : (
              <div className="space-y-6">
                {/* Hotels in 5 per row full width */}
                <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
                  {availableHotels.map((hotel) => (
                    <Card
                      key={hotel.id}
                      className={cn(
                        "border-2 cursor-pointer transition-all duration-300 hover:shadow-xl overflow-hidden",
                        selectedHotel === hotel.id
                          ? "border-gray-800 ring-2 ring-gray-800/20 shadow-lg"
                          : "border-transparent shadow-md"
                      )}
                      onClick={() => handleHotelSelect(hotel.id)}
                    >
                      <CardContent className="p-0">
                        <div className="flex flex-col">
                          <div className="relative h-40 md:h-48">
                            <img
                              src={hotel.image || "/placeholder.png"}
                              alt={hotel.name}
                              className="w-full h-full object-cover"
                            />
                            <div className="absolute top-3 right-3 bg-white/95 backdrop-blur-sm px-2 md:px-3 py-1 rounded-full shadow-md flex items-center gap-1">
                              <Star className="h-3 md:h-4 w-3 md:w-4 fill-amber-400 text-amber-400" />
                              <span className="font-semibold text-xs md:text-sm">
                                {hotel.rating}
                              </span>
                            </div>
                            {selectedHotel === hotel.id && (
                              <div className="absolute top-3 left-3 bg-gray-900 text-white px-2 md:px-3 py-1 rounded-full shadow-lg flex items-center gap-1">
                                <CheckCircle2 className="h-3 md:h-4 w-3 md:w-4" />
                                <span className="text-xs md:text-sm font-semibold">
                                  Selected
                                </span>
                              </div>
                            )}
                          </div>
                          <div className="p-3 md:p-4 space-y-2 md:space-y-3">
                            <div className="flex items-start justify-between">
                              <div className="flex-1">
                                <h3 className="font-bold text-base md:text-lg mb-1">
                                  {hotel.name}
                                </h3>
                                <p className="text-xs md:text-sm text-muted-foreground flex items-center gap-1">
                                  <MapPin className="h-3 w-3" />
                                  {
                                    locations.find(
                                      (loc) => loc.id === hotel.location
                                    )?.name
                                  }
                                </p>
                              </div>
                            </div>

                            <div className="flex items-center justify-between border-t pt-2 md:pt-3">
                              <div>
                                <p className="text-xs text-muted-foreground">
                                  Starting from
                                </p>
                                <p className="text-base md:text-lg font-bold">
                                  {hotel.priceRange.split(" - ")[0]}
                                </p>
                              </div>
                              <Badge variant="secondary" className="text-xs">
                                {hotel.reviews.toLocaleString()} reviews
                              </Badge>
                            </div>

                            <div className="flex flex-wrap gap-1 md:gap-2">
                              {hotel.amenities
                                .slice(0, 4)
                                .map((amenity, idx) => {
                                  const Icon =
                                    amenityIcons[amenity] || CheckCircle2;
                                  return (
                                    <Badge
                                      key={idx}
                                      variant="outline"
                                      className="text-xs flex items-center gap-1 px-1.5 md:px-2 py-0.5"
                                    >
                                      <Icon className="h-2.5 md:h-3 w-2.5 md:w-3" />
                                      <span className="hidden sm:inline">
                                        {amenity}
                                      </span>
                                    </Badge>
                                  );
                                })}
                              {hotel.amenities.length > 4 && (
                                <Badge
                                  variant="outline"
                                  className="text-xs px-1.5 md:px-2 py-0.5"
                                >
                                  +{hotel.amenities.length - 4}
                                </Badge>
                              )}
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>

                {/* Room types now display in full-width section below hotels */}
                {expandedHotel && selectedHotelData?.rooms && (
                  <div
                    ref={roomTypesRef}
                    className="space-y-3 md:space-y-4 animate-in slide-in-from-top-2"
                  >
                    <h4 className="text-sm md:text-base font-semibold flex items-center gap-2">
                      <Bed className="h-4 w-4 text-gray-600" />
                      Available Rooms - {selectedHotelData.name}
                    </h4>
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 md:gap-4">
                      {selectedHotelData.rooms.map((room) => (
                        <Card
                          key={room.id}
                          className={cn(
                            "cursor-pointer transition-all duration-300 border-2 overflow-hidden",
                            selectedRoom === room.id
                              ? "border-gray-900 ring-2 ring-gray-900/20 shadow-lg"
                              : "border-gray-200 hover:border-gray-400 hover:shadow-md"
                          )}
                          onClick={() =>
                            handleRoomSelect(selectedHotelData.id, room.id)
                          }
                        >
                          <CardContent className="p-0">
                            <div className="flex flex-col">
                              <div className="relative w-full h-32">
                                <img
                                  src={room.image || "/placeholder.png"}
                                  alt={room.name}
                                  className="w-full h-full object-cover"
                                />
                                {selectedRoom === room.id && (
                                  <div className="absolute top-2 right-2 bg-gray-900 text-white px-2 py-1 rounded-full shadow-lg flex items-center gap-1">
                                    <CheckCircle2 className="h-3 w-3" />
                                    <span className="text-xs font-semibold">
                                      Selected
                                    </span>
                                  </div>
                                )}
                              </div>

                              <div className="p-3 flex flex-col gap-2">
                                <div>
                                  <h5 className="font-bold text-sm mb-1">
                                    {room.name}
                                  </h5>
                                  <p className="text-xs text-muted-foreground flex items-center gap-1">
                                    <Users className="h-3 w-3" />
                                    Max {room.maxGuests} guests
                                  </p>
                                </div>

                                <div className="flex flex-wrap gap-1">
                                  {room.amenities
                                    .slice(0, 3)
                                    .map((amenity, idx) => {
                                      const Icon =
                                        roomAmenityIcons[amenity] ||
                                        CheckCircle2;
                                      return (
                                        <Badge
                                          key={idx}
                                          variant="secondary"
                                          className="text-xs flex items-center gap-1 px-1.5 py-0.5"
                                        >
                                          <Icon className="h-2.5 w-2.5" />
                                        </Badge>
                                      );
                                    })}
                                  {room.amenities.length > 3 && (
                                    <Badge
                                      variant="secondary"
                                      className="text-xs px-1.5 py-0.5"
                                    >
                                      +{room.amenities.length - 3}
                                    </Badge>
                                  )}
                                </div>

                                <div className="border-t pt-2 mt-auto">
                                  <div className="flex flex-col">
                                    <p className="text-lg font-bold text-gray-900 dark:text-gray-100">
                                      ₹{room.price.toLocaleString()}
                                    </p>
                                    <p className="text-xs text-muted-foreground">
                                      per night
                                    </p>
                                  </div>
                                </div>
                              </div>
                            </div>
                          </CardContent>
                        </Card>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </div>
        )}

        {/* Changed layout to LG grid with booking summary on RHS and guest details on LHS */}
        {selectedHotel && selectedRoom && (
          <div className="grid lg:grid-cols-3 gap-6">
            {/* Guest Details Form - Left Side (2/3 width) */}
            <div className="lg:col-span-2">
              {guestDetails.length > 0 && (
                <Card className="border-0 shadow-lg">
                  <CardHeader className="bg-gradient-to-r from-gray-50 to-white border-b">
                    <CardTitle className="text-lg flex items-center gap-2">
                      <Users className="h-5 w-5 text-gray-700" />
                      Guest Details
                    </CardTitle>
                  </CardHeader>
                  <CardContent className="p-4 md:p-6">
                    <div className="space-y-4">
                      {guestDetails.map((guest, index) => (
                        <div
                          key={guest.id}
                          className="p-4 bg-gray-50 dark:bg-gray-800/50 rounded-xl"
                        >
                          <div className="flex items-center justify-between mb-3">
                            <span className="font-medium">
                              Guest {index + 1}
                            </span>
                          </div>
                          <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div className="space-y-2">
                              <Label>Full Name</Label>
                              <Input
                                placeholder="Enter full name"
                                value={guest.name}
                                onChange={(e) =>
                                  updateGuestDetail(
                                    guest.id,
                                    "name",
                                    e.target.value
                                  )
                                }
                              />
                            </div>
                            <div className="space-y-2">
                              <Label>Age</Label>
                              <Input
                                type="number"
                                placeholder="Enter age"
                                value={guest.age}
                                onChange={(e) =>
                                  updateGuestDetail(
                                    guest.id,
                                    "age",
                                    e.target.value
                                  )
                                }
                              />
                            </div>
                            <div className="space-y-2">
                              <Label>Gender</Label>
                              <Select
                                value={guest.gender}
                                onValueChange={(val) =>
                                  updateGuestDetail(guest.id, "gender", val)
                                }
                              >
                                <SelectTrigger>
                                  <SelectValue placeholder="Select gender" />
                                </SelectTrigger>
                                <SelectContent>
                                  <SelectItem value="male">Male</SelectItem>
                                  <SelectItem value="female">Female</SelectItem>
                                  <SelectItem value="other">Other</SelectItem>
                                </SelectContent>
                              </Select>
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </CardContent>
                </Card>
              )}
            </div>

            {/* Booking Summary - Right Side (1/3 width) */}
            <div className="lg:col-span-1">
              <Card className="border-0 shadow-lg sticky top-4">
                <CardHeader className="bg-gradient-to-r from-gray-900 to-gray-700 text-white rounded-t-lg">
                  <CardTitle className="flex items-center gap-2">
                    <CheckCircle2 className="h-5 w-5" />
                    Booking Summary
                  </CardTitle>
                </CardHeader>
                <CardContent className="pt-6">
                  <div className="space-y-4 mb-6">
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-muted-foreground">Hotel</span>
                      <span className="font-semibold">
                        {selectedHotelData?.name}
                      </span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-muted-foreground">Room</span>
                      <span className="font-semibold">
                        {selectedRoomData?.name}
                      </span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-muted-foreground">Check-in</span>
                      <span className="font-medium">
                        {checkInDate ? format(checkInDate, "PP") : "-"}
                      </span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-muted-foreground">Check-out</span>
                      <span className="font-medium">
                        {checkOutDate ? format(checkOutDate, "PP") : "-"}
                      </span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-muted-foreground">Nights</span>
                      <span className="font-medium">{nights}</span>
                    </div>
                    <div className="flex justify-between py-2 border-b">
                      <span className="text-muted-foreground">Guests</span>
                      <span className="font-medium">{guests}</span>
                    </div>
                    <div className="flex justify-between py-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg px-4">
                      <span className="text-lg font-semibold">
                        Total Amount
                      </span>
                      <span className="text-xl font-bold text-gray-900 dark:text-gray-100">
                        ₹
                        {selectedRoomData
                          ? (selectedRoomData.price * nights).toLocaleString()
                          : 0}
                      </span>
                    </div>
                  </div>

                  <Button
                    className="w-full mt-6 h-12 bg-gradient-to-r from-gray-900 to-gray-700 hover:from-gray-800 hover:to-gray-600 text-white shadow-lg text-lg font-semibold"
                    onClick={handleBookNow}
                  >
                    <CheckCircle2 className="h-5 w-5 mr-2" />
                    Book Now
                  </Button>
                </CardContent>
              </Card>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}
