"use client";

import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import {
  Package,
  Calendar,
  MapPin,
  Users,
  Search,
  Filter,
  IndianRupee,
  Eye,
  Clock,
  Sparkles,
  FileText,
  X,
  Hotel,
  Car,
  UserCheck,
} from "lucide-react";
import { cn } from "@/lib/utils";
import Link from "next/link";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";

const statusTabs = [
  { id: "all", label: "All Bookings" },
  { id: "upcoming", label: "Upcoming" },
  { id: "completed", label: "Completed" },
  { id: "cancelled", label: "Cancelled" },
];

const mockBookings = [
  {
    id: "CP001",
    package: "Custom Maharashtra Tour",
    category: "Heritage Tour",
    destinations: "Mumbai, Pune, Nashik, Shirdi",
    date: "Sep 15, 2024",
    duration: "5 Days, 4 Nights",
    travelers: "4 People",
    status: "completed",
    amount: 35000,
    hotelDetails: {
      hotels: [
        {
          name: "Mumbai Grand",
          location: "Mumbai",
          roomType: "Deluxe",
          nights: 2,
        },
        {
          name: "Pune Residency",
          location: "Pune",
          roomType: "Suite",
          nights: 1,
        },
        {
          name: "Shirdi Palace",
          location: "Shirdi",
          roomType: "Standard",
          nights: 1,
        },
      ],
    },
    vehicleDetails: {
      type: "Toyota Innova Crysta",
      capacity: "7 Seater",
      pickupLocation: "Mumbai Airport",
      dropLocation: "Mumbai Airport",
      includedKm: "1500 km",
    },
    passengerDetails: [
      {
        name: "Rajesh Kumar",
        age: 42,
        gender: "Male",
        idType: "Passport",
        idNumber: "P1234567",
      },
      {
        name: "Anjali Kumar",
        age: 38,
        gender: "Female",
        idType: "Passport",
        idNumber: "P7654321",
      },
      {
        name: "Rohan Kumar",
        age: 15,
        gender: "Male",
        idType: "Aadhaar",
        idNumber: "XXXX-XXXX-1234",
      },
      {
        name: "Riya Kumar",
        age: 12,
        gender: "Female",
        idType: "Aadhaar",
        idNumber: "XXXX-XXXX-5678",
      },
    ],
  },
  {
    id: "CP002",
    package: "Custom Konkan Tour",
    category: "Beach Tour",
    destinations: "Alibaug, Murud, Ganpatipule",
    date: "Dec 28, 2024",
    duration: "3 Days, 2 Nights",
    travelers: "2 People",
    status: "upcoming",
    amount: 18000,
    hotelDetails: {
      hotels: [
        {
          name: "Beach Resort Alibaug",
          location: "Alibaug",
          roomType: "Sea View",
          nights: 1,
        },
        {
          name: "Murud Beach Hotel",
          location: "Murud",
          roomType: "Deluxe",
          nights: 1,
        },
      ],
    },
    vehicleDetails: {
      type: "Sedan",
      capacity: "4 Seater",
      pickupLocation: "Mumbai",
      dropLocation: "Mumbai",
      includedKm: "800 km",
    },
    passengerDetails: [
      {
        name: "Vikram Singh",
        age: 29,
        gender: "Male",
        idType: "Driving License",
        idNumber: "DL-MH-2345",
      },
      {
        name: "Priya Singh",
        age: 27,
        gender: "Female",
        idType: "Aadhaar",
        idNumber: "XXXX-XXXX-9876",
      },
    ],
  },
  {
    id: "CP003",
    package: "Custom Hill Station Tour",
    category: "Nature Tour",
    destinations: "Lonavala, Khandala, Matheran",
    date: "Oct 20, 2024",
    duration: "2 Days, 1 Night",
    travelers: "3 People",
    status: "cancelled",
    amount: 12000,
    hotelDetails: {
      hotels: [
        {
          name: "Lonavala Hills Resort",
          location: "Lonavala",
          roomType: "Family Room",
          nights: 1,
        },
      ],
    },
    vehicleDetails: {
      type: "SUV",
      capacity: "7 Seater",
      pickupLocation: "Pune",
      dropLocation: "Pune",
      includedKm: "400 km",
    },
    passengerDetails: [
      {
        name: "Suresh Patil",
        age: 50,
        gender: "Male",
        idType: "PAN Card",
        idNumber: "XXXXX1234X",
      },
      {
        name: "Sunita Patil",
        age: 47,
        gender: "Female",
        idType: "PAN Card",
        idNumber: "XXXXX5678X",
      },
      {
        name: "Sneha Patil",
        age: 20,
        gender: "Female",
        idType: "College ID",
        idNumber: "COL-2020-456",
      },
    ],
  },
];

const statusConfig = {
  all: {
    badgeClass: "bg-gray-50 text-gray-600 border-gray-200",
    label: "All",
  },
  upcoming: {
    badgeClass: "bg-blue-50 text-blue-600 border-blue-200",
    label: "Upcoming",
  },
  completed: {
    badgeClass: "bg-emerald-50 text-emerald-600 border-emerald-200",
    label: "Completed",
  },
  cancelled: {
    badgeClass: "bg-red-50 text-red-600 border-red-200",
    label: "Cancelled",
  },
};

export function CustomPackagesContent() {
  const [activeStatus, setActiveStatus] = useState("all");
  const [searchQuery, setSearchQuery] = useState("");
  const toast = useToastEnhanced();

  const filteredBookings =
    activeStatus === "all"
      ? mockBookings
      : mockBookings.filter((b) => b.status === activeStatus);

  const searchedBookings = filteredBookings.filter(
    (booking) =>
      booking.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
      booking.package.toLowerCase().includes(searchQuery.toLowerCase()) ||
      booking.destinations.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const handleCancellation = (bookingId: string) => {
    toast.success({
      title: "Cancellation Requested",
      description: `Your cancellation request for booking ${bookingId} has been submitted.`,
    });
  };

  return (
    <div className="space-y-6">
      <header>
        <h1 className="text-3xl font-bold text-balance">Custom Packages</h1>
        <p className="text-muted-foreground mt-2">
          View and manage your custom package bookings
        </p>
      </header>

      <div className="flex flex-wrap gap-2">
        {statusTabs.map((status) => {
          const isActive = activeStatus === status.id;
          const count =
            status.id === "all"
              ? mockBookings.length
              : mockBookings.filter((b) => b.status === status.id).length;
          return (
            <button
              key={status.id}
              onClick={() => setActiveStatus(status.id)}
              className={cn(
                "flex items-center gap-2 px-4 py-2 rounded-lg font-medium transition-all",
                isActive
                  ? "bg-primary text-primary-foreground shadow-md"
                  : "bg-white dark:bg-gray-800 text-muted-foreground hover:text-foreground hover:bg-muted border border-border/50"
              )}
            >
              {status.label}
              <Badge variant="outline" className="ml-1">
                {count}
              </Badge>
            </button>
          );
        })}
      </div>

      <div className="flex items-center gap-2">
        <div className="relative flex-1 max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
          <Input
            placeholder="Search bookings by ID, package, or destination..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9"
          />
        </div>
        <Button variant="outline" size="icon">
          <Filter className="h-4 w-4" />
        </Button>
      </div>

      <div className="grid gap-4">
        {searchedBookings.length === 0 ? (
          <Card className="shadow-md">
            <CardContent className="flex flex-col items-center justify-center py-16">
              <Package className="h-16 w-16 text-muted-foreground mb-4" />
              <p className="text-lg font-semibold mb-2">No bookings found</p>
              <p className="text-muted-foreground text-center">
                {searchQuery
                  ? "Try adjusting your search"
                  : "You don't have any custom package bookings yet"}
              </p>
            </CardContent>
          </Card>
        ) : (
          searchedBookings.map((booking) => {
            const config =
              statusConfig[booking.status as keyof typeof statusConfig];
            return (
              <Card
                key={booking.id}
                className="shadow-md hover:shadow-lg transition-all border-border/50"
              >
                <CardHeader>
                  <div className="flex items-start justify-between">
                    <div className="flex items-center gap-3">
                      <div className="p-3 rounded-lg bg-gradient-to-br from-rose-500 to-red-600 shadow-sm">
                        <Package
                          className="h-6 w-6 text-white"
                          aria-hidden="true"
                        />
                      </div>
                      <div>
                        <CardTitle className="text-lg">
                          Booking ID: {booking.id}
                        </CardTitle>
                        <p className="text-sm text-muted-foreground mt-1">
                          {booking.package}
                        </p>
                      </div>
                    </div>
                    <Badge
                      variant="outline"
                      className={cn("shadow-sm", config.badgeClass)}
                    >
                      {config.label}
                    </Badge>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="grid md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div className="flex items-start gap-2">
                      <MapPin
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">Destinations</p>
                        <p className="text-sm text-muted-foreground">
                          {booking.destinations}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-start gap-2">
                      <Calendar
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">Date</p>
                        <p className="text-sm text-muted-foreground">
                          {booking.date}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-start gap-2">
                      <Clock
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">Duration</p>
                        <p className="text-sm text-muted-foreground">
                          {booking.duration}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-start gap-2">
                      <Users
                        className="h-5 w-5 text-muted-foreground mt-0.5 shrink-0"
                        aria-hidden="true"
                      />
                      <div>
                        <p className="text-sm font-medium">Travelers</p>
                        <p className="text-sm text-muted-foreground">
                          {booking.travelers}
                        </p>
                      </div>
                    </div>
                  </div>
                  {booking.category && (
                    <div className="mt-3 flex items-center gap-2">
                      <Sparkles className="h-4 w-4 text-muted-foreground" />
                      <p className="text-sm text-muted-foreground">
                        {booking.category}
                      </p>
                    </div>
                  )}
                  <div className="mt-4 pt-4 border-t border-border/50 flex flex-wrap justify-between items-center gap-3">
                    <div className="flex items-center gap-2">
                      <IndianRupee className="h-5 w-5 text-amber-600" />
                      <p className="text-lg font-bold">
                        ₹{booking.amount.toLocaleString("en-IN")}
                      </p>
                    </div>
                    <div className="flex flex-wrap gap-2">
                      <Button
                        variant="outline"
                        size="sm"
                        asChild
                        className="gap-2 bg-transparent"
                      >
                        <Link href={`/user/invoices/${booking.id}`}>
                          <FileText className="h-4 w-4" />
                          Invoice
                        </Link>
                      </Button>
                      <Dialog>
                        <DialogTrigger asChild>
                          <Button
                            variant="outline"
                            size="sm"
                            className="gap-2 bg-transparent"
                          >
                            <Eye className="h-4 w-4" />
                            View Details
                          </Button>
                        </DialogTrigger>
                        <DialogContent className="max-w-3xl max-h-[85vh] overflow-y-auto">
                          <DialogHeader>
                            <DialogTitle className="text-2xl">
                              Booking Details
                            </DialogTitle>
                            <DialogDescription>
                              Complete information about your custom package
                              booking
                            </DialogDescription>
                          </DialogHeader>
                          <Tabs defaultValue="hotel" className="w-full">
                            <TabsList className="grid w-full grid-cols-3">
                              <TabsTrigger value="hotel">Hotels</TabsTrigger>
                              <TabsTrigger value="vehicle">Vehicle</TabsTrigger>
                              <TabsTrigger value="passengers">
                                Passengers
                              </TabsTrigger>
                            </TabsList>
                            <TabsContent value="hotel" className="space-y-4">
                              <div className="space-y-4">
                                <div className="flex items-center gap-2 text-lg font-semibold">
                                  <Hotel className="h-5 w-5" />
                                  Hotel Information
                                </div>
                                <div className="space-y-3">
                                  {booking.hotelDetails.hotels.map(
                                    (hotel, index) => (
                                      <div
                                        key={index}
                                        className="p-4 border rounded-lg"
                                      >
                                        <p className="font-semibold mb-3">
                                          {hotel.name}
                                        </p>
                                        <div className="grid grid-cols-2 gap-3 text-sm">
                                          <div>
                                            <p className="text-muted-foreground">
                                              Location
                                            </p>
                                            <p className="font-medium">
                                              {hotel.location}
                                            </p>
                                          </div>
                                          <div>
                                            <p className="text-muted-foreground">
                                              Room Type
                                            </p>
                                            <p className="font-medium">
                                              {hotel.roomType}
                                            </p>
                                          </div>
                                          <div>
                                            <p className="text-muted-foreground">
                                              Nights
                                            </p>
                                            <p className="font-medium">
                                              {hotel.nights}
                                            </p>
                                          </div>
                                        </div>
                                      </div>
                                    )
                                  )}
                                </div>
                              </div>
                            </TabsContent>
                            <TabsContent value="vehicle" className="space-y-4">
                              <div className="space-y-4">
                                <div className="flex items-center gap-2 text-lg font-semibold">
                                  <Car className="h-5 w-5" />
                                  Vehicle Information
                                </div>
                                <div className="grid grid-cols-2 gap-4 p-4 border rounded-lg">
                                  <div>
                                    <p className="text-sm text-muted-foreground">
                                      Vehicle Type
                                    </p>
                                    <p className="font-medium">
                                      {booking.vehicleDetails.type}
                                    </p>
                                  </div>
                                  <div>
                                    <p className="text-sm text-muted-foreground">
                                      Capacity
                                    </p>
                                    <p className="font-medium">
                                      {booking.vehicleDetails.capacity}
                                    </p>
                                  </div>
                                  <div>
                                    <p className="text-sm text-muted-foreground">
                                      Pickup Location
                                    </p>
                                    <p className="font-medium">
                                      {booking.vehicleDetails.pickupLocation}
                                    </p>
                                  </div>
                                  <div>
                                    <p className="text-sm text-muted-foreground">
                                      Drop Location
                                    </p>
                                    <p className="font-medium">
                                      {booking.vehicleDetails.dropLocation}
                                    </p>
                                  </div>
                                  <div>
                                    <p className="text-sm text-muted-foreground">
                                      Included Kilometers
                                    </p>
                                    <p className="font-medium">
                                      {booking.vehicleDetails.includedKm}
                                    </p>
                                  </div>
                                </div>
                              </div>
                            </TabsContent>
                            <TabsContent
                              value="passengers"
                              className="space-y-4"
                            >
                              <div className="space-y-4">
                                <div className="flex items-center gap-2 text-lg font-semibold">
                                  <UserCheck className="h-5 w-5" />
                                  Passenger Details
                                </div>
                                <div className="space-y-3">
                                  {booking.passengerDetails.map(
                                    (passenger, index) => (
                                      <div
                                        key={index}
                                        className="p-4 border rounded-lg"
                                      >
                                        <p className="font-semibold mb-3">
                                          Passenger {index + 1}
                                        </p>
                                        <div className="grid grid-cols-2 gap-3 text-sm">
                                          <div>
                                            <p className="text-muted-foreground">
                                              Name
                                            </p>
                                            <p className="font-medium">
                                              {passenger.name}
                                            </p>
                                          </div>
                                          <div>
                                            <p className="text-muted-foreground">
                                              Age
                                            </p>
                                            <p className="font-medium">
                                              {passenger.age}
                                            </p>
                                          </div>
                                          <div>
                                            <p className="text-muted-foreground">
                                              Gender
                                            </p>
                                            <p className="font-medium">
                                              {passenger.gender}
                                            </p>
                                          </div>
                                          <div>
                                            <p className="text-muted-foreground">
                                              ID Type
                                            </p>
                                            <p className="font-medium">
                                              {passenger.idType}
                                            </p>
                                          </div>
                                          <div className="col-span-2">
                                            <p className="text-muted-foreground">
                                              ID Number
                                            </p>
                                            <p className="font-medium">
                                              {passenger.idNumber}
                                            </p>
                                          </div>
                                        </div>
                                      </div>
                                    )
                                  )}
                                </div>
                              </div>
                            </TabsContent>
                          </Tabs>
                        </DialogContent>
                      </Dialog>
                      {booking.status === "upcoming" && (
                        <AlertDialog>
                          <AlertDialogTrigger asChild>
                            <Button
                              variant="outline"
                              size="sm"
                              className="gap-2 bg-transparent text-red-600 hover:text-red-700 hover:bg-red-50"
                            >
                              <X className="h-4 w-4" />
                              Cancel
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>
                                Cancel Booking
                              </AlertDialogTitle>
                              <AlertDialogDescription>
                                Are you sure you want to cancel booking{" "}
                                {booking.id}? This action cannot be undone.
                                Cancellation charges may apply as per the
                                package terms.
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>
                                Keep Booking
                              </AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => handleCancellation(booking.id)}
                                className="bg-red-600 hover:bg-red-700"
                              >
                                Confirm Cancellation
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            );
          })
        )}
      </div>
    </div>
  );
}
