﻿"use client";

import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { AgentHeader } from "@/roles/agent/components/agent-header";
import { getClientSession, validateSessionData } from "@/features/auth";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import {
  Car,
  Building2,
  Sparkles,
  Package,
  Clock,
  PlayCircle,
  CheckCircle2,
  XCircle,
  User,
  Mail,
  Phone,
  MapPin,
  IndianRupee,
  Calendar,
  Search,
  Filter,
  CalendarClock,
  X,
  Eye,
  Users,
  Hotel,
  Star,
  Settings,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

const bookingCategories = [
  { id: "vehicle", label: "Vehicle Bookings", icon: Car },
  { id: "hotel", label: "Hotel Bookings", icon: Building2 },
  { id: "spiritual", label: "Spiritual Bookings", icon: Sparkles },
  { id: "custom", label: "Custom Bookings", icon: Package },
];

const statusTabs = [
  { id: "upcoming", label: "Upcoming", icon: Clock },
  { id: "ongoing", label: "Ongoing", icon: PlayCircle },
  { id: "completed", label: "Completed", icon: CheckCircle2 },
  { id: "cancelled", label: "Cancelled", icon: XCircle },
];

// Mock data for vehicle bookings
const vehicleBookings = {
  upcoming: [
    {
      id: "VB001",
      customerName: "Rahul Sharma",
      customerEmail: "rahul.sharma@email.com",
      customerPhone: "+91 98765 43210",
      pickupCity: "Delhi",
      dropCity: "Jaipur",
      bookingDate: "Dec 15, 2025",
      bookingAmount: 4500,
      passengers: [
        { name: "Rahul Sharma", age: "35", gender: "Male" },
        { name: "Priya Sharma", age: "32", gender: "Female" },
      ],
      vehicle: { name: "Innova Crysta", seats: 7, type: "SUV" },
    },
    {
      id: "VB002",
      customerName: "Priya Patel",
      customerEmail: "priya.patel@email.com",
      customerPhone: "+91 87654 32109",
      pickupCity: "Mumbai",
      dropCity: "Pune",
      bookingDate: "Dec 18, 2025",
      bookingAmount: 3200,
      passengers: [{ name: "Priya Patel", age: "28", gender: "Female" }],
      vehicle: { name: "Sedan", seats: 4, type: "Sedan" },
    },
  ],
  ongoing: [
    {
      id: "VB003",
      customerName: "Amit Kumar",
      customerEmail: "amit.kumar@email.com",
      customerPhone: "+91 76543 21098",
      pickupCity: "Bangalore",
      dropCity: "Mysore",
      bookingDate: "Dec 09, 2025",
      bookingAmount: 2800,
      passengers: [
        { name: "Amit Kumar", age: "40", gender: "Male" },
        { name: "Sunita Kumar", age: "38", gender: "Female" },
        { name: "Rahul Kumar", age: "12", gender: "Male" },
      ],
      vehicle: { name: "SUV", seats: 6, type: "SUV" },
    },
  ],
  completed: [
    {
      id: "VB004",
      customerName: "Neha Singh",
      customerEmail: "neha.singh@email.com",
      customerPhone: "+91 65432 10987",
      pickupCity: "Chennai",
      dropCity: "Pondicherry",
      bookingDate: "Dec 01, 2025",
      bookingAmount: 3500,
      passengers: [
        { name: "Neha Singh", age: "30", gender: "Female" },
        { name: "Vikram Singh", age: "34", gender: "Male" },
      ],
      vehicle: { name: "Innova Crysta", seats: 7, type: "SUV" },
    },
  ],
  cancelled: [
    {
      id: "VB005",
      customerName: "Vikram Reddy",
      customerEmail: "vikram.r@email.com",
      customerPhone: "+91 54321 09876",
      pickupCity: "Hyderabad",
      dropCity: "Warangal",
      bookingDate: "Nov 28, 2025",
      bookingAmount: 2200,
      cancelReason: "Customer request",
      passengers: [{ name: "Vikram Reddy", age: "45", gender: "Male" }],
      vehicle: { name: "Sedan", seats: 4, type: "Sedan" },
    },
  ],
};

// Mock data for hotel bookings
const hotelBookings = {
  upcoming: [
    {
      id: "HB001",
      customerName: "Ananya Gupta",
      customerEmail: "ananya.g@email.com",
      customerPhone: "+91 98712 34567",
      hotelName: "Taj Palace Hotel",
      hotelLocation: "New Delhi",
      bookingDate: "Dec 20, 2025",
      checkOut: "Dec 23, 2025",
      bookingAmount: 12500,
      guests: [
        { name: "Ananya Gupta", age: "29", gender: "Female" },
        { name: "Rohan Gupta", age: "32", gender: "Male" },
      ],
      room: { type: "Deluxe Room", count: 1, pricePerNight: 4000 },
    },
    {
      id: "HB002",
      customerName: "Rajesh Menon",
      customerEmail: "rajesh.m@email.com",
      customerPhone: "+91 87612 34567",
      hotelName: "Oberoi Grand",
      hotelLocation: "Kolkata",
      bookingDate: "Dec 22, 2025",
      checkOut: "Dec 25, 2025",
      bookingAmount: 9800,
      guests: [{ name: "Rajesh Menon", age: "45", gender: "Male" }],
      room: { type: "Standard Room", count: 1, pricePerNight: 3200 },
    },
  ],
  ongoing: [
    {
      id: "HB003",
      customerName: "Sneha Nair",
      customerEmail: "sneha.n@email.com",
      customerPhone: "+91 76512 34567",
      hotelName: "Leela Beach Resort",
      hotelLocation: "Goa",
      bookingDate: "Dec 08, 2025",
      checkOut: "Dec 12, 2025",
      bookingAmount: 15000,
      guests: [
        { name: "Sneha Nair", age: "33", gender: "Female" },
        { name: "Arun Nair", age: "36", gender: "Male" },
        { name: "Arya Nair", age: "8", gender: "Female" },
      ],
      room: { type: "Beach Villa", count: 1, pricePerNight: 3500 },
    },
  ],
  completed: [
    {
      id: "HB004",
      customerName: "Arjun Iyer",
      customerEmail: "arjun.i@email.com",
      customerPhone: "+91 65412 34567",
      hotelName: "ITC Maurya",
      hotelLocation: "New Delhi",
      bookingDate: "Nov 25, 2025",
      checkOut: "Nov 28, 2025",
      bookingAmount: 18500,
      guests: [
        { name: "Arjun Iyer", age: "50", gender: "Male" },
        { name: "Lakshmi Iyer", age: "48", gender: "Female" },
      ],
      room: { type: "Executive Suite", count: 1, pricePerNight: 6000 },
    },
  ],
  cancelled: [
    {
      id: "HB005",
      customerName: "Meera Joshi",
      customerEmail: "meera.j@email.com",
      customerPhone: "+91 54312 34567",
      hotelName: "Marriott Resort",
      hotelLocation: "Udaipur",
      bookingDate: "Nov 20, 2025",
      checkOut: "Nov 23, 2025",
      bookingAmount: 11000,
      cancelReason: "Plans changed",
      guests: [{ name: "Meera Joshi", age: "27", gender: "Female" }],
      room: { type: "Lake View Room", count: 1, pricePerNight: 3500 },
    },
  ],
};

const spiritualBookings = {
  upcoming: [
    {
      id: "SB001",
      customerName: "Suresh Pandey",
      customerEmail: "suresh.p@email.com",
      customerPhone: "+91 99887 76655",
      destination: "Varanasi",
      tripDuration: "3 Days",
      bookingDate: "Dec 25, 2025",
      bookingAmount: 28500,
      passengers: [
        { name: "Suresh Pandey", age: "55", gender: "Male" },
        { name: "Kamla Pandey", age: "52", gender: "Female" },
        { name: "Aditya Pandey", age: "25", gender: "Male" },
      ],
      vehicle: { name: "Innova Crysta", seats: 7, pricePerDay: 4500 },
      hotel: { name: "Taj Ganges", rating: 5, pricePerRoom: 8500, rooms: 2 },
    },
    {
      id: "SB002",
      customerName: "Lakshmi Devi",
      customerEmail: "lakshmi.d@email.com",
      customerPhone: "+91 88776 65544",
      destination: "Ayodhya",
      tripDuration: "2 Days",
      bookingDate: "Dec 28, 2025",
      bookingAmount: 18200,
      passengers: [
        { name: "Lakshmi Devi", age: "60", gender: "Female" },
        { name: "Ram Kumar", age: "65", gender: "Male" },
      ],
      vehicle: { name: "Sedan", seats: 4, pricePerDay: 2500 },
      hotel: { name: "Hotel Saket", rating: 3, pricePerRoom: 3200, rooms: 1 },
    },
  ],
  ongoing: [
    {
      id: "SB003",
      customerName: "Mohan Tiwari",
      customerEmail: "mohan.t@email.com",
      customerPhone: "+91 77665 54433",
      destination: "Haridwar",
      tripDuration: "4 Days",
      bookingDate: "Dec 07, 2025",
      bookingAmount: 45000,
      passengers: [
        { name: "Mohan Tiwari", age: "48", gender: "Male" },
        { name: "Geeta Tiwari", age: "45", gender: "Female" },
        { name: "Ankit Tiwari", age: "22", gender: "Male" },
        { name: "Prachi Tiwari", age: "18", gender: "Female" },
      ],
      vehicle: { name: "Tempo Traveller", seats: 12, pricePerDay: 6000 },
      hotel: {
        name: "Radisson Haridwar",
        rating: 4,
        pricePerRoom: 5500,
        rooms: 2,
      },
    },
  ],
  completed: [
    {
      id: "SB004",
      customerName: "Vijay Sharma",
      customerEmail: "vijay.s@email.com",
      customerPhone: "+91 66554 43322",
      destination: "Rishikesh",
      tripDuration: "3 Days",
      bookingDate: "Nov 20, 2025",
      bookingAmount: 32000,
      passengers: [
        { name: "Vijay Sharma", age: "42", gender: "Male" },
        { name: "Sunita Sharma", age: "40", gender: "Female" },
      ],
      vehicle: { name: "SUV", seats: 6, pricePerDay: 3500 },
      hotel: { name: "Divine Resort", rating: 4, pricePerRoom: 4500, rooms: 1 },
    },
  ],
  cancelled: [
    {
      id: "SB005",
      customerName: "Deepak Verma",
      customerEmail: "deepak.v@email.com",
      customerPhone: "+91 55443 32211",
      destination: "Mathura",
      tripDuration: "2 Days",
      bookingDate: "Nov 15, 2025",
      bookingAmount: 15000,
      cancelReason: "Health issues",
      passengers: [{ name: "Deepak Verma", age: "38", gender: "Male" }],
      vehicle: { name: "Sedan", seats: 4, pricePerDay: 2500 },
      hotel: { name: "Krishna Inn", rating: 3, pricePerRoom: 2800, rooms: 1 },
    },
  ],
};

const customBookings = {
  upcoming: [
    {
      id: "CB001",
      customerName: "Ashok Mehta",
      customerEmail: "ashok.m@email.com",
      customerPhone: "+91 98123 45678",
      destination: "Varanasi",
      category: "Heritage Tour",
      tripDuration: "4 Days",
      bookingDate: "Dec 30, 2025",
      bookingAmount: 52000,
      passengers: [
        { name: "Ashok Mehta", age: "50", gender: "Male" },
        { name: "Nirmala Mehta", age: "48", gender: "Female" },
        { name: "Rohit Mehta", age: "24", gender: "Male" },
        { name: "Sneha Mehta", age: "20", gender: "Female" },
      ],
      vehicle: { name: "Innova Crysta", seats: 7, pricePerDay: 4500 },
      hotel: { stars: 4, category: "Premium", pricePerRoom: 3500, rooms: 2 },
    },
    {
      id: "CB002",
      customerName: "Kavita Singh",
      customerEmail: "kavita.s@email.com",
      customerPhone: "+91 87654 32198",
      destination: "Rishikesh",
      category: "Adventure Sports",
      tripDuration: "3 Days",
      bookingDate: "Jan 05, 2026",
      bookingAmount: 38500,
      passengers: [
        { name: "Kavita Singh", age: "28", gender: "Female" },
        { name: "Raj Singh", age: "30", gender: "Male" },
        { name: "Pooja Singh", age: "26", gender: "Female" },
      ],
      vehicle: { name: "SUV", seats: 6, pricePerDay: 3500 },
      hotel: { stars: 3, category: "Standard", pricePerRoom: 2000, rooms: 2 },
    },
  ],
  ongoing: [
    {
      id: "CB003",
      customerName: "Ramesh Gupta",
      customerEmail: "ramesh.g@email.com",
      customerPhone: "+91 76543 21987",
      destination: "Prayagraj",
      category: "Spiritual Tour",
      tripDuration: "2 Days",
      bookingDate: "Dec 08, 2025",
      bookingAmount: 22000,
      passengers: [
        { name: "Ramesh Gupta", age: "58", gender: "Male" },
        { name: "Sarla Gupta", age: "55", gender: "Female" },
      ],
      vehicle: { name: "Sedan", seats: 4, pricePerDay: 2500 },
      hotel: { stars: 3, category: "Standard", pricePerRoom: 2000, rooms: 1 },
    },
  ],
  completed: [
    {
      id: "CB004",
      customerName: "Preeti Agarwal",
      customerEmail: "preeti.a@email.com",
      customerPhone: "+91 65432 19876",
      destination: "Haridwar",
      category: "Cultural Experience",
      tripDuration: "3 Days",
      bookingDate: "Nov 18, 2025",
      bookingAmount: 35000,
      passengers: [
        { name: "Preeti Agarwal", age: "35", gender: "Female" },
        { name: "Amit Agarwal", age: "38", gender: "Male" },
        { name: "Aryan Agarwal", age: "10", gender: "Male" },
      ],
      vehicle: { name: "Innova Crysta", seats: 7, pricePerDay: 4500 },
      hotel: { stars: 4, category: "Premium", pricePerRoom: 3500, rooms: 1 },
    },
  ],
  cancelled: [
    {
      id: "CB005",
      customerName: "Sanjay Jain",
      customerEmail: "sanjay.j@email.com",
      customerPhone: "+91 54321 98765",
      destination: "Mathura",
      category: "Temple Tour",
      tripDuration: "2 Days",
      bookingDate: "Nov 10, 2025",
      bookingAmount: 18000,
      cancelReason: "Schedule conflict",
      passengers: [
        { name: "Sanjay Jain", age: "45", gender: "Male" },
        { name: "Rekha Jain", age: "42", gender: "Female" },
      ],
      vehicle: { name: "Sedan", seats: 4, pricePerDay: 2500 },
      hotel: { stars: 2, category: "Economy", pricePerRoom: 1200, rooms: 1 },
    },
  ],
};

const statusConfig = {
  upcoming: {
    badgeClass:
      "bg-blue-50 text-blue-600 border-blue-200 dark:bg-blue-950 dark:text-blue-400 dark:border-blue-800",
    label: "Upcoming",
  },
  ongoing: {
    badgeClass:
      "bg-amber-50 text-amber-600 border-amber-200 dark:bg-amber-950 dark:text-amber-400 dark:border-amber-800",
    label: "Ongoing",
  },
  completed: {
    badgeClass:
      "bg-emerald-50 text-emerald-600 border-emerald-200 dark:bg-emerald-950 dark:text-emerald-400 dark:border-emerald-800",
    label: "Completed",
  },
  cancelled: {
    badgeClass:
      "bg-red-50 text-red-600 border-red-200 dark:bg-red-950 dark:text-red-400 dark:border-red-800",
    label: "Cancelled",
  },
};

export default function AllBookingsPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [agentEmail, setAgentEmail] = useState<string>(
    "info@ameeraholidays.com"
  );
  const [agentName, setAgentName] = useState<string>("Agent");
  const [isLoading, setIsLoading] = useState(true);
  const [activeCategory, setActiveCategory] = useState("vehicle");
  const [activeStatus, setActiveStatus] = useState("upcoming");
  const [searchQuery, setSearchQuery] = useState("");

  // Reschedule dialog state
  const [isRescheduleOpen, setIsRescheduleOpen] = useState(false);
  const [rescheduleBookingId, setRescheduleBookingId] = useState<string | null>(
    null
  );
  const [newDate, setNewDate] = useState("");

  // Cancel dialog state
  const [isCancelOpen, setIsCancelOpen] = useState(false);
  const [cancelBookingId, setCancelBookingId] = useState<string | null>(null);

  const [isViewDetailsOpen, setIsViewDetailsOpen] = useState(false);
  const [selectedBooking, setSelectedBooking] = useState<any>(null);
  const [detailsTab, setDetailsTab] = useState<
    "passengers" | "hotel" | "vehicle"
  >("passengers");

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

    const tab = searchParams.get("tab");
    if (tab && ["vehicle", "hotel", "spiritual", "custom"].includes(tab)) {
      setActiveCategory(tab);
    }
  }, [router, searchParams]);

  const handleReschedule = (bookingId: string) => {
    setRescheduleBookingId(bookingId);
    setIsRescheduleOpen(true);
  };

  const handleConfirmReschedule = () => {
    if (!newDate) {
      toast.error("Please select a new date");
      return;
    }
    toast.success(`Booking ${rescheduleBookingId} rescheduled to ${newDate}`);
    setIsRescheduleOpen(false);
    setRescheduleBookingId(null);
    setNewDate("");
  };

  const handleCancelBooking = (bookingId: string) => {
    setCancelBookingId(bookingId);
    setIsCancelOpen(true);
  };

  const handleConfirmCancel = () => {
    toast.success(`Booking ${cancelBookingId} cancelled successfully`);
    setIsCancelOpen(false);
    setCancelBookingId(null);
  };

  const handleViewDetails = (booking: any) => {
    setSelectedBooking(booking);
    setDetailsTab("passengers");
    setIsViewDetailsOpen(true);
  };

  const getBookings = () => {
    if (activeCategory === "vehicle") {
      return (
        vehicleBookings[activeStatus as keyof typeof vehicleBookings] || []
      );
    } else if (activeCategory === "hotel") {
      return hotelBookings[activeStatus as keyof typeof hotelBookings] || [];
    } else if (activeCategory === "spiritual") {
      return (
        spiritualBookings[activeStatus as keyof typeof spiritualBookings] || []
      );
    } else if (activeCategory === "custom") {
      return customBookings[activeStatus as keyof typeof customBookings] || [];
    }
    return [];
  };

  const bookings = getBookings();
  const filteredBookings = bookings.filter(
    (booking: any) =>
      booking.customerName.toLowerCase().includes(searchQuery.toLowerCase()) ||
      booking.id.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const currentCategory = bookingCategories.find(
    (c) => c.id === activeCategory
  );
  const currentStatus = statusTabs.find((s) => s.id === activeStatus);
  const config = statusConfig[activeStatus as keyof typeof statusConfig];

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

  const renderBookingCard = (booking: any) => {
    return (
      <div
        key={booking.id}
        className="p-4 rounded-xl bg-gradient-to-br from-white to-gray-50 dark:from-gray-800 dark:to-gray-850 border border-border/50 hover:shadow-md transition-all duration-200"
      >
        <div className="flex flex-col gap-4">
          {/* Top row: Customer info and booking details */}
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {/* Customer Details */}
            <div className="space-y-1">
              <div className="flex items-center gap-2">
                <User className="h-4 w-4 text-gray-600" />
                <span className="font-semibold">{booking.customerName}</span>
              </div>
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Mail className="h-3 w-3" />
                <span className="truncate">{booking.customerEmail}</span>
              </div>
              <div className="flex items-center gap-2 text-sm text-muted-foreground">
                <Phone className="h-3 w-3" />
                <span>{booking.customerPhone}</span>
              </div>
            </div>

            {/* Location/Destination Info */}
            <div className="space-y-1">
              {activeCategory === "vehicle" ? (
                <>
                  <div className="flex items-center gap-2">
                    <MapPin className="h-4 w-4 text-emerald-600" />
                    <span className="text-sm font-medium">
                      {booking.pickupCity} â†’ {booking.dropCity}
                    </span>
                  </div>
                  <p className="text-xs text-muted-foreground pl-6">
                    Pickup to Drop
                  </p>
                </>
              ) : activeCategory === "hotel" ? (
                <>
                  <div className="flex items-center gap-2">
                    <Building2 className="h-4 w-4 text-emerald-600" />
                    <span className="text-sm font-medium">
                      {booking.hotelName}
                    </span>
                  </div>
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <MapPin className="h-3 w-3" />
                    <span>{booking.hotelLocation}</span>
                  </div>
                </>
              ) : (
                <>
                  <div className="flex items-center gap-2">
                    <MapPin className="h-4 w-4 text-emerald-600" />
                    <span className="text-sm font-medium">
                      {booking.destination}
                    </span>
                  </div>
                  {activeCategory === "custom" && booking.category && (
                    <div className="flex items-center gap-2 text-sm text-muted-foreground">
                      <Sparkles className="h-3 w-3" />
                      <span>{booking.category}</span>
                    </div>
                  )}
                  <div className="flex items-center gap-2 text-sm text-muted-foreground">
                    <Clock className="h-3 w-3" />
                    <span>{booking.tripDuration}</span>
                  </div>
                </>
              )}
            </div>

            {/* Booking Date & Duration */}
            <div className="space-y-1">
              <div className="flex items-center gap-2">
                <Calendar className="h-4 w-4 text-blue-600" />
                <span className="text-sm">{booking.bookingDate}</span>
              </div>
              {activeCategory === "hotel" && booking.checkOut && (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <span className="pl-6">to {booking.checkOut}</span>
                </div>
              )}
              {(activeCategory === "spiritual" ||
                activeCategory === "custom") && (
                <div className="flex items-center gap-2 text-sm text-muted-foreground">
                  <Users className="h-3 w-3" />
                  <span>{booking.passengers?.length || 0} Traveler(s)</span>
                </div>
              )}
            </div>

            {/* Amount */}
            <div className="space-y-1">
              <div className="flex items-center gap-2">
                <IndianRupee className="h-4 w-4 text-amber-600" />
                <span className="text-lg font-bold">
                  ₹{booking.bookingAmount.toLocaleString("en-IN")}
                </span>
              </div>
              <Badge variant="outline" className={config?.badgeClass}>
                {config?.label}
              </Badge>
            </div>
          </div>

          {/* Bottom row: ID and Actions */}
          <div className="flex flex-wrap items-center justify-between gap-3 pt-3 border-t border-border/50">
            <span className="text-xs text-muted-foreground font-mono">
              #{booking.id}
            </span>

            {/* Action Buttons */}
            <div className="flex flex-wrap gap-2">
              {/* View Details button for all categories */}
              <Button
                size="sm"
                variant="outline"
                className="text-xs bg-transparent"
                onClick={() => handleViewDetails(booking)}
              >
                <Eye className="h-3 w-3 mr-1" />
                View Details
              </Button>

              {activeStatus === "upcoming" && (
                <>
                  <Button
                    size="sm"
                    className="agent-btn text-xs"
                    onClick={() => handleReschedule(booking.id)}
                  >
                    <CalendarClock className="h-3 w-3 mr-1" />
                    Reschedule
                  </Button>
                  <Button
                    size="sm"
                    variant="outline"
                    className="text-red-600 border-red-200 hover:bg-red-50 dark:hover:bg-red-950 text-xs bg-transparent"
                    onClick={() => handleCancelBooking(booking.id)}
                  >
                    <X className="h-3 w-3 mr-1" />
                    Cancel
                  </Button>
                </>
              )}
              {activeStatus === "ongoing" && (
                <Button size="sm" className="agent-btn text-xs">
                  <PlayCircle className="h-3 w-3 mr-1" />
                  Track
                </Button>
              )}
              {activeStatus === "completed" && (
                <Button
                  size="sm"
                  variant="outline"
                  className="text-xs bg-transparent"
                >
                  <CheckCircle2 className="h-3 w-3 mr-1" />
                  Download Invoice
                </Button>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  const renderDetailsContent = () => {
    if (!selectedBooking) return null;

    const hasVehicle = selectedBooking.vehicle;
    const hasHotel = selectedBooking.hotel || selectedBooking.room;
    const hasPassengers = selectedBooking.passengers || selectedBooking.guests;

    return (
      <div className="space-y-4">
        {/* Tabs */}
        <div className="flex gap-2 border-b border-border pb-2">
          {hasPassengers && (
            <button
              onClick={() => setDetailsTab("passengers")}
              className={cn(
                "px-4 py-2 rounded-lg text-sm font-medium transition-all",
                detailsTab === "passengers"
                  ? "agent-btn text-white"
                  : "text-muted-foreground hover:text-foreground hover:bg-muted"
              )}
            >
              <Users className="h-4 w-4 inline mr-2" />
              {activeCategory === "hotel" ? "Guests" : "Passengers"}
            </button>
          )}
          {hasHotel && (
            <button
              onClick={() => setDetailsTab("hotel")}
              className={cn(
                "px-4 py-2 rounded-lg text-sm font-medium transition-all",
                detailsTab === "hotel"
                  ? "agent-btn text-white"
                  : "text-muted-foreground hover:text-foreground hover:bg-muted"
              )}
            >
              <Hotel className="h-4 w-4 inline mr-2" />
              Hotel
            </button>
          )}
          {hasVehicle && (
            <button
              onClick={() => setDetailsTab("vehicle")}
              className={cn(
                "px-4 py-2 rounded-lg text-sm font-medium transition-all",
                detailsTab === "vehicle"
                  ? "agent-btn text-white"
                  : "text-muted-foreground hover:text-foreground hover:bg-muted"
              )}
            >
              <Car className="h-4 w-4 inline mr-2" />
              Vehicle
            </button>
          )}
        </div>

        {/* Tab Content */}
        <div className="min-h-[200px]">
          {/* Passengers/Guests Tab */}
          {detailsTab === "passengers" && hasPassengers && (
            <div className="space-y-3">
              <h4 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">
                {activeCategory === "hotel"
                  ? "Guest Details"
                  : "Passenger Details"}
              </h4>
              <div className="grid gap-3">
                {(selectedBooking.passengers || selectedBooking.guests)?.map(
                  (person: any, index: number) => (
                    <div
                      key={index}
                      className="flex items-center justify-between p-3 rounded-lg bg-muted/50 border border-border/50"
                    >
                      <div className="flex items-center gap-3">
                        <div className="h-10 w-10 rounded-full bg-gradient-to-br from-gray-700 to-gray-900 flex items-center justify-center text-white font-semibold">
                          {person.name?.charAt(0) || "?"}
                        </div>
                        <div>
                          <p className="font-medium">{person.name}</p>
                          <p className="text-sm text-muted-foreground">
                            {person.age} years â€¢ {person.gender}
                          </p>
                        </div>
                      </div>
                      {index === 0 && (
                        <Badge
                          variant="outline"
                          className="bg-emerald-50 text-emerald-600 border-emerald-200"
                        >
                          Primary
                        </Badge>
                      )}
                    </div>
                  )
                )}
              </div>
            </div>
          )}

          {/* Hotel Tab */}
          {detailsTab === "hotel" && hasHotel && (
            <div className="space-y-3">
              <h4 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">
                Hotel Details
              </h4>
              <div className="p-4 rounded-lg bg-muted/50 border border-border/50">
                {activeCategory === "hotel" && selectedBooking.room ? (
                  <div className="space-y-3">
                    <div className="flex items-center gap-3">
                      <Hotel className="h-5 w-5 text-gray-600" />
                      <div>
                        <p className="font-semibold">
                          {selectedBooking.hotelName}
                        </p>
                        <p className="text-sm text-muted-foreground">
                          {selectedBooking.hotelLocation}
                        </p>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4 pt-3 border-t border-border/50">
                      <div>
                        <p className="text-xs text-muted-foreground">
                          Room Type
                        </p>
                        <p className="font-medium">
                          {selectedBooking.room.type}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">Rooms</p>
                        <p className="font-medium">
                          {selectedBooking.room.count}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">
                          Price/Night
                        </p>
                        <p className="font-medium">
                          ₹
                          {selectedBooking.room.pricePerNight?.toLocaleString(
                            "en-IN"
                          )}
                        </p>
                      </div>
                    </div>
                  </div>
                ) : activeCategory === "spiritual" && selectedBooking.hotel ? (
                  <div className="space-y-3">
                    <div className="flex items-center gap-3">
                      <Hotel className="h-5 w-5 text-gray-600" />
                      <div>
                        <p className="font-semibold">
                          {selectedBooking.hotel.name}
                        </p>
                        <div className="flex items-center gap-1">
                          {Array.from({
                            length: selectedBooking.hotel.rating,
                          }).map((_, i) => (
                            <Star
                              key={i}
                              className="h-3 w-3 fill-yellow-400 text-yellow-400"
                            />
                          ))}
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4 pt-3 border-t border-border/50">
                      <div>
                        <p className="text-xs text-muted-foreground">Rooms</p>
                        <p className="font-medium">
                          {selectedBooking.hotel.rooms}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">
                          Price/Room/Night
                        </p>
                        <p className="font-medium">
                          ₹
                          {selectedBooking.hotel.pricePerRoom?.toLocaleString(
                            "en-IN"
                          )}
                        </p>
                      </div>
                    </div>
                  </div>
                ) : activeCategory === "custom" && selectedBooking.hotel ? (
                  <div className="space-y-3">
                    <div className="flex items-center gap-3">
                      <Hotel className="h-5 w-5 text-gray-600" />
                      <div>
                        <p className="font-semibold">
                          {selectedBooking.hotel.stars} Star{" "}
                          {selectedBooking.hotel.category}
                        </p>
                        <div className="flex items-center gap-1">
                          {Array.from({
                            length: selectedBooking.hotel.stars,
                          }).map((_, i) => (
                            <Star
                              key={i}
                              className="h-3 w-3 fill-yellow-400 text-yellow-400"
                            />
                          ))}
                        </div>
                      </div>
                    </div>
                    <div className="grid grid-cols-2 gap-4 pt-3 border-t border-border/50">
                      <div>
                        <p className="text-xs text-muted-foreground">
                          Category
                        </p>
                        <p className="font-medium">
                          {selectedBooking.hotel.category}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">Rooms</p>
                        <p className="font-medium">
                          {selectedBooking.hotel.rooms}
                        </p>
                      </div>
                      <div>
                        <p className="text-xs text-muted-foreground">
                          Price/Room/Night
                        </p>
                        <p className="font-medium">
                          ₹
                          {selectedBooking.hotel.pricePerRoom?.toLocaleString(
                            "en-IN"
                          )}
                        </p>
                      </div>
                    </div>
                  </div>
                ) : null}
              </div>
            </div>
          )}

          {/* Vehicle Tab */}
          {detailsTab === "vehicle" && hasVehicle && (
            <div className="space-y-3">
              <h4 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">
                Vehicle Details
              </h4>
              <div className="p-4 rounded-lg bg-muted/50 border border-border/50">
                <div className="flex items-center gap-4">
                  <div className="h-16 w-24 rounded-lg bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-600 flex items-center justify-center">
                    <Car className="h-8 w-8 text-gray-500" />
                  </div>
                  <div className="flex-1">
                    <p className="font-semibold text-lg">
                      {selectedBooking.vehicle.name}
                    </p>
                    <div className="flex items-center gap-4 text-sm text-muted-foreground mt-1">
                      <span className="flex items-center gap-1">
                        <Users className="h-3 w-3" />
                        {selectedBooking.vehicle.seats} Seats
                      </span>
                      {selectedBooking.vehicle.type && (
                        <span className="flex items-center gap-1">
                          <Settings className="h-3 w-3" />
                          {selectedBooking.vehicle.type}
                        </span>
                      )}
                    </div>
                    {selectedBooking.vehicle.pricePerDay && (
                      <p className="text-sm font-medium text-emerald-600 mt-2">
                        ₹
                        {selectedBooking.vehicle.pricePerDay.toLocaleString(
                          "en-IN"
                        )}
                        /day
                      </p>
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  };

  return (
    <div className="min-h-screen bg-gradient-to-br from-gray-50 via-white to-gray-100 dark:from-gray-950 dark:via-gray-900 dark:to-gray-950">
      <AgentHeader agentEmail={agentEmail} agentName={agentName} />

      <main className="container mx-auto p-4 md:p-6 lg:p-8">
        {/* Page Title */}
        <div className="mb-6">
          <h1 className="text-2xl font-bold">All Bookings</h1>
          <p className="text-muted-foreground">
            Manage all your customer bookings in one place
          </p>
        </div>

        {/* Category Tabs */}
        <div className="flex flex-wrap gap-2 mb-6">
          {bookingCategories.map((category) => {
            const Icon = category.icon;
            const isActive = activeCategory === category.id;
            return (
              <button
                key={category.id}
                onClick={() => setActiveCategory(category.id)}
                className={cn(
                  "flex items-center gap-2 px-4 py-2.5 rounded-lg font-medium transition-all whitespace-nowrap",
                  isActive
                    ? "agent-btn text-white shadow-md"
                    : "bg-white dark:bg-gray-800 text-muted-foreground hover:text-foreground hover:bg-gray-100 dark:hover:bg-gray-700 border border-border/50"
                )}
              >
                <Icon className="h-4 w-4" />
                {category.label}
              </button>
            );
          })}
        </div>

        <div className="flex flex-col md:flex-row gap-6">
          {/* Sidebar with status tabs */}
          <div className="w-full md:w-64 shrink-0">
            <Card className="border-border/50 overflow-hidden shadow-sm">
              <div className="h-1 bg-gradient-to-r from-gray-700 to-gray-900" />
              <div className="p-3 border-b border-border/50 bg-muted/30">
                <h3 className="font-semibold text-sm text-muted-foreground uppercase tracking-wider">
                  Booking Status
                </h3>
              </div>
              <div className="p-2">
                {statusTabs.map((status) => {
                  const Icon = status.icon;
                  const isActive = activeStatus === status.id;
                  return (
                    <button
                      key={status.id}
                      onClick={() => setActiveStatus(status.id)}
                      className={cn(
                        "w-full flex items-center gap-3 px-4 py-3 rounded-lg font-medium transition-all text-left mb-1 last:mb-0",
                        isActive
                          ? "agent-btn text-white shadow-md"
                          : "text-muted-foreground hover:text-foreground hover:bg-muted"
                      )}
                    >
                      <Icon
                        className={cn("h-5 w-5", isActive ? "text-white" : "")}
                      />
                      {status.label}
                    </button>
                  );
                })}
              </div>
            </Card>
          </div>

          {/* Content area */}
          <div className="flex-1 min-w-0">
            <Card className="border-border/50 shadow-sm overflow-hidden">
              <div className="h-1 bg-gradient-to-r from-gray-700 to-gray-900" />
              <CardHeader>
                <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
                  <CardTitle className="text-xl font-semibold flex items-center gap-3">
                    {currentStatus?.label} {currentCategory?.label}
                    <Badge variant="outline" className={config?.badgeClass}>
                      {filteredBookings.length}
                    </Badge>
                  </CardTitle>

                  <div className="flex items-center gap-2">
                    <div className="relative">
                      <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                      <Input
                        placeholder="Search bookings..."
                        value={searchQuery}
                        onChange={(e) => setSearchQuery(e.target.value)}
                        className="pl-9 w-[200px]"
                      />
                    </div>
                    <Button variant="outline" size="icon">
                      <Filter className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </CardHeader>

              <CardContent>
                {filteredBookings.length === 0 ? (
                  <div className="flex flex-col items-center justify-center py-16 text-center">
                    {currentCategory && currentStatus && (
                      <>
                        <div className="p-4 rounded-full bg-gradient-to-br from-gray-200 to-gray-300 dark:from-gray-700 dark:to-gray-600 mb-4">
                          <currentCategory.icon className="h-10 w-10 text-gray-600 dark:text-gray-300" />
                        </div>
                        <h3 className="text-xl font-semibold mb-2">
                          No {currentStatus.label} {currentCategory.label}
                        </h3>
                        <p className="text-muted-foreground max-w-md">
                          Your {currentStatus.label.toLowerCase()}{" "}
                          {currentCategory.label.toLowerCase()} will appear
                          here.
                        </p>
                      </>
                    )}
                  </div>
                ) : (
                  <div className="space-y-4">
                    {filteredBookings.map((booking: any) =>
                      renderBookingCard(booking)
                    )}
                  </div>
                )}
              </CardContent>
            </Card>
          </div>
        </div>
      </main>

      {/* Reschedule Dialog */}
      <Dialog open={isRescheduleOpen} onOpenChange={setIsRescheduleOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Reschedule Booking</DialogTitle>
            <DialogDescription>
              Select a new date for booking #{rescheduleBookingId}
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <Label htmlFor="newDate">New Date</Label>
            <Input
              id="newDate"
              type="date"
              value={newDate}
              onChange={(e) => setNewDate(e.target.value)}
              className="mt-2"
            />
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsRescheduleOpen(false)}
            >
              Cancel
            </Button>
            <Button className="agent-btn" onClick={handleConfirmReschedule}>
              Confirm Reschedule
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* Cancel Dialog */}
      <Dialog open={isCancelOpen} onOpenChange={setIsCancelOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Cancel Booking</DialogTitle>
            <DialogDescription>
              Are you sure you want to cancel booking #{cancelBookingId}? This
              action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <DialogFooter>
            <Button variant="outline" onClick={() => setIsCancelOpen(false)}>
              Keep Booking
            </Button>
            <Button variant="destructive" onClick={handleConfirmCancel}>
              Yes, Cancel Booking
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      <Dialog open={isViewDetailsOpen} onOpenChange={setIsViewDetailsOpen}>
        <DialogContent className="max-w-2xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <Eye className="h-5 w-5" />
              Booking Details
              {selectedBooking && (
                <Badge variant="outline" className="ml-2 font-mono">
                  #{selectedBooking.id}
                </Badge>
              )}
            </DialogTitle>
            <DialogDescription>
              View complete details of this booking including passengers, hotel,
              and vehicle information.
            </DialogDescription>
          </DialogHeader>
          {renderDetailsContent()}
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setIsViewDetailsOpen(false)}
            >
              Close
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
