"use client"

import { useEffect, useState, useMemo } from "react"
import { useRouter } from "next/navigation"
import { AgentHeader } from "@/components/agent/agent-header"
import { getClientSession, validateSessionData } from "@/lib/auth/client-session"
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,
  Sparkles,
  BedDouble,
  Bath,
  Tv,
  Wind,
  UserPlus,
  ChevronDown,
  ChevronUp,
} from "lucide-react"
import { cn } from "@/lib/utils"

// 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.svg?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.svg?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Bathroom"],
      },
      {
        id: "r2",
        name: "Premium Suite",
        price: 15000,
        maxGuests: 3,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["King Bed", "Living Area", "AC", "TV", "Bathtub"],
      },
      {
        id: "r3",
        name: "Royal Suite",
        price: 25000,
        maxGuests: 4,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["2 King Beds", "Living Area", "Balcony", "AC", "TV", "Jacuzzi"],
      },
    ],
  },
  {
    id: "h2",
    name: "BrijRama Palace",
    location: "varanasi",
    image: "/placeholder.svg?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.svg?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "River View"],
      },
      {
        id: "r5",
        name: "Maharaja Suite",
        price: 30000,
        maxGuests: 3,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["King Bed", "Living Area", "AC", "TV", "Private Terrace"],
      },
      {
        id: "r6",
        name: "Royal Chamber",
        price: 45000,
        maxGuests: 4,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["2 King Beds", "Living Area", "AC", "TV", "Private Pool"],
      },
    ],
  },
  {
    id: "h3",
    name: "Haveli Hari Ganga",
    location: "haridwar",
    image: "/placeholder.svg?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.svg?height=120&width=200",
        amenities: ["Queen Bed", "AC", "TV"],
      },
      {
        id: "r8",
        name: "Ganga View Room",
        price: 9000,
        maxGuests: 2,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Balcony"],
      },
      {
        id: "r9",
        name: "Family Suite",
        price: 18000,
        maxGuests: 5,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["2 Queen Beds", "Living Area", "AC", "TV"],
      },
    ],
  },
  {
    id: "h4",
    name: "Divine Resort",
    location: "rishikesh",
    image: "/placeholder.svg?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.svg?height=120&width=200",
        amenities: ["Double Bed", "AC", "TV"],
      },
      {
        id: "r11",
        name: "Deluxe Cottage",
        price: 8000,
        maxGuests: 2,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Private Garden"],
      },
      {
        id: "r12",
        name: "Premium Villa",
        price: 15000,
        maxGuests: 4,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["2 King Beds", "Living Area", "AC", "Private Pool"],
      },
    ],
  },
  {
    id: "h5",
    name: "Krishna Palace",
    location: "mathura",
    image: "/placeholder.svg?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.svg?height=120&width=200",
        amenities: ["Double Bed", "AC", "TV"],
      },
      {
        id: "r14",
        name: "Temple View Room",
        price: 6000,
        maxGuests: 2,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Balcony"],
      },
      {
        id: "r15",
        name: "Family Room",
        price: 12000,
        maxGuests: 4,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["2 Queen Beds", "AC", "TV", "Mini Kitchen"],
      },
    ],
  },
  {
    id: "h6",
    name: "Ganga Kinare",
    location: "rishikesh",
    image: "/placeholder.svg?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.svg?height=120&width=200",
        amenities: ["King Bed", "AC", "TV", "Balcony"],
      },
      {
        id: "r17",
        name: "Premium Room",
        price: 12000,
        maxGuests: 3,
        image: "/placeholder.svg?height=120&width=200",
        amenities: ["King Bed", "Living Area", "AC", "TV"],
      },
      {
        id: "r18",
        name: "Luxury Suite",
        price: 20000,
        maxGuests: 4,
        image: "/placeholder.svg?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 HotelBookingPage() {
  const router = useRouter()
  const [agentEmail, setAgentEmail] = useState<string>("agent@teertham.com")
  const [agentName, setAgentName] = useState<string>("Agent")
  const [isLoading, setIsLoading] = useState(true)

  // 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)

  useEffect(() => {
    const session = getClientSession("agent_session")
    if (!session || !validateSessionData(session) || session.role !== "agent") {
      router.push("/login")
      return
    }
    setAgentEmail(session.email || "agent@teertham.com")
    setAgentName(session.name || "Agent")
    setIsLoading(false)
  }, [router])

  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)
    }
  }

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

  const handleBookNow = () => {
    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`,
    })
  }

  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-gray-800" />
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-slate-50 via-gray-50 to-zinc-100 dark:from-slate-950 dark:via-gray-950 dark:to-zinc-950">
      <AgentHeader agentEmail={agentEmail} agentName={agentName} />
      <main className="container mx-auto p-4 md:p-6 lg:p-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 clients</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)}
                      initialFocus
                    />
                  </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-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-lg font-medium mb-2">No hotels found</h3>
                  <p className="text-muted-foreground">
                    No hotels available in this location. Try a different location.
                  </p>
                </CardContent>
              </Card>
            ) : (
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {availableHotels.map((hotel) => (
                  <div key={hotel.id} className="space-y-4">
                    <Card
                      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-48">
                            <img
                              src={hotel.image || "/placeholder.svg"}
                              alt={hotel.name}
                              className="w-full h-full object-cover"
                            />
                            {selectedHotel === hotel.id && (
                              <div className="absolute top-3 right-3 p-1.5 bg-gray-900 rounded-full">
                                <CheckCircle2 className="h-4 w-4 text-white" />
                              </div>
                            )}
                          </div>

                          <div className="p-5">
                            <div className="flex items-start justify-between mb-3">
                              <div>
                                <h3 className="font-bold text-xl mb-1">{hotel.name}</h3>
                                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                                  <MapPin className="h-4 w-4" />
                                  <span className="capitalize">{hotel.location}</span>
                                </div>
                              </div>
                              <div className="text-right">
                                <div className="flex items-center gap-1 mb-1">
                                  <Star className="h-4 w-4 text-yellow-500 fill-yellow-500" />
                                  <span className="font-bold">{hotel.rating}</span>
                                  <span className="text-sm text-muted-foreground">({hotel.reviews})</span>
                                </div>
                                <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                                  {hotel.priceRange}
                                </p>
                              </div>
                            </div>

                            <div className="flex flex-wrap gap-2 mb-4">
                              {hotel.amenities.slice(0, 4).map((amenity) => {
                                const Icon = amenityIcons[amenity] || Hotel
                                return (
                                  <Badge key={amenity} variant="secondary" className="flex items-center gap-1 text-xs">
                                    <Icon className="h-3 w-3" />
                                    {amenity}
                                  </Badge>
                                )
                              })}
                              {hotel.amenities.length > 4 && (
                                <Badge variant="secondary" className="text-xs">
                                  +{hotel.amenities.length - 4}
                                </Badge>
                              )}
                            </div>

                            <Button className="w-full bg-gradient-to-r from-gray-900 to-gray-700 hover:from-gray-800 hover:to-gray-600 text-white shadow-md">
                              {expandedHotel === hotel.id ? (
                                <>
                                  <ChevronUp className="h-4 w-4 mr-2" />
                                  Hide Rooms
                                </>
                              ) : (
                                <>
                                  <ChevronDown className="h-4 w-4 mr-2" />
                                  View Rooms
                                </>
                              )}
                            </Button>
                          </div>
                        </div>
                      </CardContent>
                    </Card>

                    {expandedHotel === hotel.id && (
                      <div className="pl-4 border-l-4 border-gray-300 dark:border-gray-700 space-y-3 animate-in slide-in-from-top-2 duration-300">
                        <h4 className="font-semibold text-sm text-muted-foreground uppercase tracking-wide">
                          Available Rooms
                        </h4>
                        {hotel.rooms.map((room) => (
                          <Card
                            key={room.id}
                            className={cn(
                              "border-2 cursor-pointer transition-all duration-200 hover:shadow-lg",
                              selectedRoom === room.id && selectedHotel === hotel.id
                                ? "border-gray-800 ring-2 ring-gray-800/20"
                                : "border-transparent",
                            )}
                            onClick={(e) => {
                              e.stopPropagation()
                              handleRoomSelect(hotel.id, room.id)
                            }}
                          >
                            <CardContent className="p-4">
                              <div className="flex gap-4">
                                <img
                                  src={room.image || "/placeholder.svg"}
                                  alt={room.name}
                                  className="w-28 h-20 object-cover rounded-lg"
                                />
                                <div className="flex-1">
                                  <div className="flex items-start justify-between mb-2">
                                    <div>
                                      <h5 className="font-bold">{room.name}</h5>
                                      <div className="flex items-center gap-1 text-sm text-muted-foreground">
                                        <Users className="h-3 w-3" />
                                        <span>Max {room.maxGuests} guests</span>
                                      </div>
                                    </div>
                                    <div className="text-right">
                                      <p className="font-bold text-lg text-gray-800 dark:text-gray-200">
                                        ₹{room.price.toLocaleString("en-IN")}
                                      </p>
                                      <p className="text-xs text-muted-foreground">/night</p>
                                    </div>
                                  </div>
                                  <div className="flex flex-wrap gap-1.5">
                                    {room.amenities.slice(0, 4).map((amenity) => {
                                      const Icon = roomAmenityIcons[amenity] || Hotel
                                      return (
                                        <Badge
                                          key={amenity}
                                          variant="outline"
                                          className="text-xs flex items-center gap-1"
                                        >
                                          <Icon className="h-3 w-3" />
                                          {amenity}
                                        </Badge>
                                      )
                                    })}
                                  </div>
                                </div>
                                {selectedRoom === room.id && selectedHotel === hotel.id && (
                                  <div className="flex items-center">
                                    <CheckCircle2 className="h-6 w-6 text-gray-800" />
                                  </div>
                                )}
                              </div>
                            </CardContent>
                          </Card>
                        ))}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* Booking Summary */}
        {selectedHotel && selectedRoom && selectedHotelData && selectedRoomData && (
          <Card className="border-0 shadow-lg overflow-hidden">
            <div className="h-1 bg-gradient-to-r from-gray-900 via-gray-700 to-gray-900" />
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-lg">
                <Sparkles className="h-5 w-5 text-gray-700" />
                Booking Summary
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div className="space-y-4">
                  <div className="p-4 bg-gray-50 dark:bg-gray-800/50 rounded-xl">
                    <div className="flex gap-4 mb-3">
                      <img
                        src={selectedHotelData.image || "/placeholder.svg"}
                        alt={selectedHotelData.name}
                        className="w-24 h-16 object-cover rounded-lg"
                      />
                      <div>
                        <h4 className="font-bold">{selectedHotelData.name}</h4>
                        <p className="text-sm text-muted-foreground capitalize">{selectedHotelData.location}</p>
                      </div>
                    </div>
                    <div className="flex gap-4 pt-3 border-t border-gray-200 dark:border-gray-700">
                      <img
                        src={selectedRoomData.image || "/placeholder.svg"}
                        alt={selectedRoomData.name}
                        className="w-20 h-14 object-cover rounded-lg"
                      />
                      <div>
                        <h5 className="font-medium">{selectedRoomData.name}</h5>
                        <p className="text-sm text-muted-foreground">Max {selectedRoomData.maxGuests} guests</p>
                      </div>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-3">
                    <div className="p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">Check-in</p>
                      <p className="font-medium">{checkInDate ? format(checkInDate, "PP") : "Not selected"}</p>
                    </div>
                    <div className="p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">Check-out</p>
                      <p className="font-medium">{checkOutDate ? format(checkOutDate, "PP") : "Not selected"}</p>
                    </div>
                    <div className="p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">Nights</p>
                      <p className="font-medium">
                        {nights} {nights === 1 ? "Night" : "Nights"}
                      </p>
                    </div>
                    <div className="p-3 bg-gray-50 dark:bg-gray-800/50 rounded-lg">
                      <p className="text-xs text-muted-foreground mb-1">Guests</p>
                      <p className="font-medium">{guests}</p>
                    </div>
                  </div>
                </div>

                <div className="space-y-4">
                  <div className="p-4 bg-gradient-to-br from-gray-50 to-zinc-100 dark:from-gray-800/50 dark:to-zinc-800/50 rounded-xl border border-gray-200 dark:border-gray-700">
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-muted-foreground">Room Rate ({nights} nights)</span>
                      <span>₹{(selectedRoomData.price * nights).toLocaleString("en-IN")}</span>
                    </div>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-muted-foreground">GST (12%)</span>
                      <span>₹{Math.round(selectedRoomData.price * nights * 0.12).toLocaleString("en-IN")}</span>
                    </div>
                    <div className="flex items-center justify-between mb-2">
                      <span className="text-muted-foreground">Service Fee</span>
                      <span>₹500</span>
                    </div>
                    <div className="h-px bg-gray-200 dark:bg-gray-700 my-3" />
                    <div className="flex items-center justify-between">
                      <span className="font-bold">Total Amount</span>
                      <span className="text-xl font-bold text-gray-800 dark:text-gray-200">
                        ₹
                        {(
                          selectedRoomData.price * nights +
                          Math.round(selectedRoomData.price * nights * 0.12) +
                          500
                        ).toLocaleString("en-IN")}
                      </span>
                    </div>
                  </div>
                </div>
              </div>

              {guests && Number.parseInt(guests) > 0 && (
                <div className="mt-6 pt-6 border-t">
                  <h3 className="text-lg font-semibold mb-4 flex items-center gap-2">
                    <UserPlus className="h-5 w-5 text-gray-700" />
                    Guest Details
                  </h3>
                  <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>
                </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}
              >
                Book Now
              </Button>
            </CardContent>
          </Card>
        )}
      </main>
    </div>
  )
}
