"use client"

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

type BookingStatus = "upcoming" | "completed" | "cancelled"

interface HotelDetails {
  name: string
  roomType: string
  roomCount: number
  checkIn: string
  checkOut: string
}

interface VehicleDetails {
  type: string
  capacity: string
  pickupLocation: string
  dropLocation: string
}

interface PassengerDetail {
  name: string
  age: number
  gender: string
  idType: string
  idNumber: string
}

interface Booking {
  id: string
  package: string
  destination: string
  date: string
  duration: string
  travelers: string
  amount: number
  status: BookingStatus
  hotelDetails?: HotelDetails
  vehicleDetails: VehicleDetails
  passengerDetails: PassengerDetail[]
}

const sampleBookings: Booking[] = [
  {
    id: "FXB001",
    package: "Char Dham Yatra",
    destination: "Uttarakhand",
    date: "Dec 28, 2024",
    duration: "8 Days, 7 Nights",
    travelers: "4 People",
    amount: 152000,
    status: "upcoming",
    hotelDetails: {
      name: "Divine Hotels - Char Dham Circuit",
      roomType: "Deluxe Double",
      roomCount: 2,
      checkIn: "Dec 28, 2024",
      checkOut: "Jan 04, 2025",
    },
    vehicleDetails: {
      type: "Luxury SUV",
      capacity: "7 Passengers",
      pickupLocation: "Haridwar Railway Station",
      dropLocation: "Haridwar Railway Station",
    },
    passengerDetails: [
      { name: "Rajesh Kumar", age: 45, gender: "Male", idType: "Aadhar", idNumber: "XXXX-XXXX-1234" },
      { name: "Sunita Kumar", age: 42, gender: "Female", idType: "Aadhar", idNumber: "XXXX-XXXX-5678" },
      { name: "Amit Kumar", age: 20, gender: "Male", idType: "Aadhar", idNumber: "XXXX-XXXX-9012" },
      { name: "Priya Kumar", age: 18, gender: "Female", idType: "Aadhar", idNumber: "XXXX-XXXX-3456" },
    ],
  },
  {
    id: "FXB002",
    package: "Golden Triangle Spiritual Tour",
    destination: "Delhi, Agra, Mathura, Vrindavan, Jaipur",
    date: "Nov 15, 2024",
    duration: "5 Days, 4 Nights",
    travelers: "2 People",
    amount: 56000,
    status: "completed",
    hotelDetails: {
      name: "Heritage Hotels - Golden Triangle",
      roomType: "Executive Suite",
      roomCount: 1,
      checkIn: "Nov 15, 2024",
      checkOut: "Nov 19, 2024",
    },
    vehicleDetails: {
      type: "Sedan",
      capacity: "4 Passengers",
      pickupLocation: "Delhi International Airport",
      dropLocation: "Delhi International Airport",
    },
    passengerDetails: [
      { name: "Test Customer", age: 35, gender: "Male", idType: "Passport", idNumber: "XXXX1234" },
      { name: "Anita Sharma", age: 32, gender: "Female", idType: "Passport", idNumber: "XXXX5678" },
    ],
  },
  {
    id: "FXB003",
    package: "Varanasi - Prayagraj Spiritual Journey",
    destination: "Varanasi, Sarnath, Prayagraj",
    date: "Oct 05, 2024",
    duration: "4 Days, 3 Nights",
    travelers: "3 People",
    amount: 63000,
    status: "cancelled",
    vehicleDetails: {
      type: "SUV",
      capacity: "7 Passengers",
      pickupLocation: "Varanasi Junction",
      dropLocation: "Varanasi Junction",
    },
    passengerDetails: [
      { name: "Vikram Singh", age: 50, gender: "Male", idType: "Aadhar", idNumber: "XXXX-XXXX-7890" },
      { name: "Meera Singh", age: 48, gender: "Female", idType: "Aadhar", idNumber: "XXXX-XXXX-2345" },
      { name: "Arjun Singh", age: 22, gender: "Male", idType: "Driving License", idNumber: "XXXX-XXXX-6789" },
    ],
  },
]

export default function FixedBookingsContent() {
  const [activeTab, setActiveTab] = useState<"all" | BookingStatus>("all")
  const [searchQuery, setSearchQuery] = useState("")
  const { toast } = useToastEnhanced()

  const getFilteredBookings = () => {
    let filtered = sampleBookings

    if (activeTab !== "all") {
      filtered = filtered.filter((booking) => booking.status === activeTab)
    }

    if (searchQuery) {
      filtered = filtered.filter(
        (booking) =>
          booking.id.toLowerCase().includes(searchQuery.toLowerCase()) ||
          booking.package.toLowerCase().includes(searchQuery.toLowerCase()) ||
          booking.destination.toLowerCase().includes(searchQuery.toLowerCase()),
      )
    }

    return filtered
  }

  const handleCancelBooking = (bookingId: string) => {
    toast({
      title: "Booking Cancelled",
      description: `Booking ${bookingId} has been cancelled successfully.`,
    })
  }

  const filteredBookings = getFilteredBookings()

  const getStatusConfig = (status: BookingStatus) => {
    const configs = {
      upcoming: {
        label: "Upcoming",
        badgeClass: "bg-blue-100 text-blue-700 border-blue-300",
      },
      completed: {
        label: "Completed",
        badgeClass: "bg-green-100 text-green-700 border-green-300",
      },
      cancelled: {
        label: "Cancelled",
        badgeClass: "bg-red-100 text-red-700 border-red-300",
      },
    }
    return configs[status]
  }

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="space-y-2">
        <h1 className="text-2xl md:text-3xl font-bold text-gray-900 flex items-center gap-3">
          <Box className="h-8 w-8 text-purple-600" />
          Fixed Bookings
        </h1>
        <p className="text-gray-600">View and manage your fixed package bookings</p>
      </div>

      {/* Tabs and Search */}
      <div className="flex flex-col md:flex-row gap-4 justify-between">
        <Tabs value={activeTab} onValueChange={(v) => setActiveTab(v as typeof activeTab)} className="w-full md:w-auto">
          <TabsList className="grid grid-cols-4 w-full md:w-auto">
            <TabsTrigger value="all">All Bookings</TabsTrigger>
            <TabsTrigger value="upcoming">Upcoming</TabsTrigger>
            <TabsTrigger value="completed">Completed</TabsTrigger>
            <TabsTrigger value="cancelled">Cancelled</TabsTrigger>
          </TabsList>
        </Tabs>

        <div className="relative flex-1 md:max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
          <Input
            placeholder="Search bookings by ID, package, or destination..."
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            className="pl-9"
          />
        </div>
      </div>

      {/* Bookings List */}
      <div className="space-y-4">
        {filteredBookings.length === 0 ? (
          <Card className="p-12 text-center">
            <Box className="h-16 w-16 text-gray-300 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-700 mb-2">No bookings found</h3>
            <p className="text-gray-500 mb-6">Try adjusting your search or filter criteria</p>
            <Button asChild>
              <Link href="/fixed-packages">Browse Fixed Packages</Link>
            </Button>
          </Card>
        ) : (
          filteredBookings.map((booking) => {
            const config = getStatusConfig(booking.status)

            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-purple-500 to-indigo-600 shadow-sm">
                        <Box 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">Destination</p>
                        <p className="text-sm text-muted-foreground">{booking.destination}</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>
                  <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-purple-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 fixed package booking</DialogDescription>
                          </DialogHeader>
                          <Tabs defaultValue="hotel" className="w-full">
                            <TabsList className="grid w-full grid-cols-3">
                              <TabsTrigger value="hotel">Hotel</TabsTrigger>
                              <TabsTrigger value="vehicle">Vehicle</TabsTrigger>
                              <TabsTrigger value="passengers">Passengers</TabsTrigger>
                            </TabsList>
                            <TabsContent value="hotel" className="space-y-4">
                              {booking.hotelDetails ? (
                                <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="grid grid-cols-2 gap-4 p-4 border rounded-lg">
                                    <div>
                                      <p className="text-sm text-muted-foreground">Hotel Name</p>
                                      <p className="font-medium">{booking.hotelDetails.name}</p>
                                    </div>
                                    <div>
                                      <p className="text-sm text-muted-foreground">Room Type</p>
                                      <p className="font-medium">{booking.hotelDetails.roomType}</p>
                                    </div>
                                    <div>
                                      <p className="text-sm text-muted-foreground">Number of Rooms</p>
                                      <p className="font-medium">{booking.hotelDetails.roomCount}</p>
                                    </div>
                                    <div>
                                      <p className="text-sm text-muted-foreground">Check-In</p>
                                      <p className="font-medium">{booking.hotelDetails.checkIn}</p>
                                    </div>
                                    <div>
                                      <p className="text-sm text-muted-foreground">Check-Out</p>
                                      <p className="font-medium">{booking.hotelDetails.checkOut}</p>
                                    </div>
                                  </div>
                                </div>
                              ) : (
                                <div className="text-center py-8 text-muted-foreground">
                                  <Hotel className="h-12 w-12 mx-auto mb-2 opacity-50" />
                                  <p>No hotel accommodation included in this package</p>
                                </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>
                              </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 text-red-600 hover:text-red-700 hover:bg-red-50 bg-transparent"
                            >
                              <XCircle className="h-4 w-4" />
                              Cancel
                            </Button>
                          </AlertDialogTrigger>
                          <AlertDialogContent>
                            <AlertDialogHeader>
                              <AlertDialogTitle>Are you sure you want to cancel this booking?</AlertDialogTitle>
                              <AlertDialogDescription>
                                This action cannot be undone. Your booking for {booking.package} will be cancelled and a
                                refund will be processed according to our cancellation policy.
                              </AlertDialogDescription>
                            </AlertDialogHeader>
                            <AlertDialogFooter>
                              <AlertDialogCancel>No, Keep Booking</AlertDialogCancel>
                              <AlertDialogAction
                                onClick={() => handleCancelBooking(booking.id)}
                                className="bg-red-600 hover:bg-red-700"
                              >
                                Yes, Cancel Booking
                              </AlertDialogAction>
                            </AlertDialogFooter>
                          </AlertDialogContent>
                        </AlertDialog>
                      )}
                    </div>
                  </div>
                </CardContent>
              </Card>
            )
          })
        )}
      </div>
    </div>
  )
}
