"use client"

import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import Link from "next/link"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Label } from "@/components/ui/label"
import { Input } from "@/components/ui/input"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import {
  Package,
  MapPin,
  Calendar,
  IndianRupee,
  Sparkles,
  ArrowLeft,
  FileText,
  Info,
  Car,
  Users,
  Check,
  Percent,
  User,
  Phone,
  Mail,
  Plus,
  Trash2,
  Loader2,
  Hotel,
} from "lucide-react"
import { fixPackageDataStore, type FixPackage } from "@/lib/data/fix-packages"
import { getClientSession, validateSessionData } from "@/lib/auth/client-session"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"

interface Customer {
  id: string
  name: string
  age: string
  gender: string
  phone: string
  email: string
}

export default function FixedPackageDetailClient({ id }: { id: string }) {
  const router = useRouter()
  const { toast } = useToastEnhanced()

  const [pkg, setPkg] = useState<FixPackage | null>(null)
  const [customers, setCustomers] = useState<Customer[]>([
    { id: "1", name: "", age: "", gender: "", phone: "", email: "" },
  ])
  const [isSubmitting, setIsSubmitting] = useState(false)

  useEffect(() => {
    const packageData = fixPackageDataStore.getPackageById(id)
    setPkg(packageData || null)
  }, [id])

  const addCustomer = () => {
    setCustomers([
      ...customers,
      {
        id: Date.now().toString(),
        name: "",
        age: "",
        gender: "",
        phone: "",
        email: "",
      },
    ])
  }

  const removeCustomer = (customerId: string) => {
    if (customers.length > 1) {
      setCustomers(customers.filter((c) => c.id !== customerId))
    }
  }

  const updateCustomer = (customerId: string, field: keyof Customer, value: string) => {
    setCustomers(customers.map((c) => (c.id === customerId ? { ...c, [field]: value } : c)))
  }

  const calculatePricing = () => {
    if (!pkg) return { packageCost: 0, subtotal: 0, gst: 0, total: 0 }

    const packageCost = pkg.discountedPrice * customers.length
    const subtotal = packageCost
    const gst = Math.round(subtotal * 0.18)
    const total = subtotal + gst

    return { packageCost, subtotal, gst, total }
  }

  const handleBooking = async () => {
    const isValid = customers.every((c) => c.name && c.age && c.gender)
    if (!isValid) {
      toast({
        title: "Incomplete Details",
        description: "Please fill in all customer details (name, age, gender)",
        variant: "destructive",
      })
      return
    }

    const session = getClientSession("customer_session")
    if (!session || !validateSessionData(session) || session.role !== "customer") {
      toast({
        title: "Please login to continue",
        description: "You need to login to your customer account to book this package",
        variant: "destructive",
      })
      router.push("/login")
      return
    }

    setIsSubmitting(true)
    try {
      await new Promise((resolve) => setTimeout(resolve, 1500))

      toast({
        title: "Booking Confirmed!",
        description: `Your ${pkg?.name} booking has been confirmed successfully.`,
      })
      router.push("/user/fixed-bookings")
    } catch (error) {
      toast({
        title: "Booking Failed",
        description: "Something went wrong. Please try again.",
        variant: "destructive",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  if (!pkg) {
    return (
      <div className="min-h-screen bg-gradient-to-br from-purple-50 via-white to-blue-50 flex items-center justify-center">
        <div className="text-center">
          <Package className="h-16 w-16 text-gray-300 mx-auto mb-4" />
          <h2 className="text-2xl font-bold text-gray-700 mb-2">Package not found</h2>
          <p className="text-gray-500 mb-6">The package you're looking for doesn't exist</p>
          <Button asChild>
            <Link href="/fixed-packages">
              <ArrowLeft className="mr-2 h-4 w-4" />
              Back to Packages
            </Link>
          </Button>
        </div>
      </div>
    )
  }

  const discount =
    pkg.originalPrice > pkg.discountedPrice
      ? Math.round(((pkg.originalPrice - pkg.discountedPrice) / pkg.originalPrice) * 100)
      : 0
  const pricing = calculatePricing()

  const itineraryDays = pkg.itineraryDetails.split(/Day \d+:/).filter((d) => d.trim())

  return (
    <div className="min-h-screen bg-gradient-to-br from-purple-50 via-white to-blue-50">
      <main className="container mx-auto p-4 md:p-6 lg:p-8">
        {/* Back Button */}
        <div className="mb-6">
          <Button variant="outline" asChild className="gap-2 bg-transparent">
            <Link href="/fixed-packages">
              <ArrowLeft className="h-4 w-4" />
              Back to Packages
            </Link>
          </Button>
        </div>

        <div className="grid lg:grid-cols-3 gap-6">
          {/* Left Side - Images and Package Info */}
          <div className="lg:col-span-2 space-y-6">
            {/* Package Image Gallery */}
            <Card className="border-0 shadow-lg overflow-hidden">
              <div className="relative h-80 md:h-96 bg-gradient-to-br from-purple-100 to-blue-100">
                <img
                  src={`/placeholder.svg?height=400&width=800&query=${encodeURIComponent(pkg.name + " package destination")}`}
                  alt={pkg.name}
                  className="w-full h-full object-cover"
                />
                <div className="absolute top-4 left-4 flex gap-2">
                  <Badge className="bg-white/90 text-purple-900 border-white/30 backdrop-blur-sm">
                    <Sparkles className="h-3 w-3 mr-1" />
                    Fixed Package
                  </Badge>
                  {pkg.status === "inactive" && (
                    <Badge variant="destructive" className="backdrop-blur-sm">
                      Inactive
                    </Badge>
                  )}
                  {discount > 0 && (
                    <Badge className="bg-green-600 text-white backdrop-blur-sm">
                      <Percent className="h-3 w-3 mr-1" />
                      {discount}% OFF
                    </Badge>
                  )}
                </div>
              </div>
            </Card>

            {/* Package Name, Location, and Pricing */}
            <Card className="border-0 shadow-lg">
              <CardContent className="p-6">
                <h1 className="text-3xl md:text-4xl font-bold text-gray-900 mb-4">{pkg.name}</h1>

                <div className="flex flex-wrap gap-6 text-gray-700 mb-6">
                  <div className="flex items-center gap-2">
                    <MapPin className="h-5 w-5 text-purple-600" />
                    <span className="text-base">{pkg.locationDetails.split("-")[0]?.trim()}</span>
                  </div>
                  <div className="flex items-center gap-2">
                    <Calendar className="h-5 w-5 text-purple-600" />
                    <span className="text-base">
                      {pkg.totalDays} Day{pkg.totalDays > 1 ? "s" : ""}
                    </span>
                  </div>
                </div>

                <div className="flex items-center gap-4 p-6 bg-gradient-to-r from-purple-50 to-blue-50 rounded-xl border-2 border-purple-200">
                  {discount > 0 && (
                    <span className="text-gray-500 line-through text-xl">₹{pkg.originalPrice.toLocaleString()}</span>
                  )}
                  <div className="flex items-baseline gap-1">
                    <IndianRupee className="h-7 w-7 text-purple-600" />
                    <span className="text-4xl font-bold text-purple-600">{pkg.discountedPrice.toLocaleString()}</span>
                  </div>
                  <span className="text-gray-600">per person</span>
                </div>
              </CardContent>
            </Card>

            {/* Package Details Tabs */}
            <Card className="border-0 shadow-lg">
              <Tabs defaultValue="location" className="w-full">
                <CardHeader className="border-b bg-gradient-to-r from-purple-50 to-white pb-0">
                  <TabsList className="w-full justify-start bg-transparent border-b-0 h-auto p-0">
                    <TabsTrigger
                      value="location"
                      className="data-[state=active]:border-b-2 data-[state=active]:border-purple-600 data-[state=active]:bg-transparent rounded-none px-6 py-3"
                    >
                      <MapPin className="h-4 w-4 mr-2" />
                      Locations
                    </TabsTrigger>
                    <TabsTrigger
                      value="itinerary"
                      className="data-[state=active]:border-b-2 data-[state=active]:border-purple-600 data-[state=active]:bg-transparent rounded-none px-6 py-3"
                    >
                      <FileText className="h-4 w-4 mr-2" />
                      Itinerary
                    </TabsTrigger>
                    <TabsTrigger
                      value="other"
                      className="data-[state=active]:border-b-2 data-[state=active]:border-purple-600 data-[state=active]:bg-transparent rounded-none px-6 py-3"
                    >
                      <Info className="h-4 w-4 mr-2" />
                      Other Details
                    </TabsTrigger>
                  </TabsList>
                </CardHeader>

                <CardContent className="p-6">
                  <TabsContent value="location" className="mt-0">
                    <div className="space-y-4">
                      <h3 className="font-semibold text-lg flex items-center gap-2 text-gray-900">
                        <MapPin className="h-5 w-5 text-purple-600" />
                        Destination Details
                      </h3>
                      <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">{pkg.locationDetails}</p>
                    </div>
                  </TabsContent>

                  <TabsContent value="itinerary" className="mt-0">
                    <div className="space-y-4">
                      <h3 className="font-semibold text-lg flex items-center gap-2 text-gray-900">
                        <FileText className="h-5 w-5 text-purple-600" />
                        Day-by-Day Itinerary
                      </h3>
                      <div className="space-y-4">
                        {itineraryDays.map((day, index) => (
                          <div key={index} className="p-4 rounded-lg bg-purple-50 border border-purple-200">
                            <div className="flex items-start gap-3">
                              <div className="flex-shrink-0 w-10 h-10 rounded-full bg-purple-600 text-white flex items-center justify-center font-bold">
                                {index + 1}
                              </div>
                              <div className="flex-1">
                                <p className="text-gray-700 leading-relaxed">{day.trim()}</p>
                              </div>
                            </div>
                          </div>
                        ))}
                      </div>
                    </div>
                  </TabsContent>

                  <TabsContent value="other" className="mt-0">
                    <div className="space-y-4">
                      <h3 className="font-semibold text-lg flex items-center gap-2 text-gray-900">
                        <Info className="h-5 w-5 text-purple-600" />
                        Inclusions & Exclusions
                      </h3>
                      <div className="prose prose-sm max-w-none">
                        <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">{pkg.otherDetails}</p>
                      </div>
                    </div>
                  </TabsContent>
                </CardContent>
              </Tabs>
            </Card>

            {/* Vehicle Details */}
            {pkg.vehicles.length > 0 && (
              <Card className="border-0 shadow-lg">
                <CardHeader className="border-b bg-gradient-to-r from-purple-50 to-white">
                  <CardTitle className="flex items-center gap-2">
                    <Car className="h-5 w-5 text-purple-600" />
                    Available Vehicles
                  </CardTitle>
                </CardHeader>
                <CardContent className="p-6">
                  <div className="grid md:grid-cols-2 gap-4">
                    {pkg.vehicles.map((vehicle) => (
                      <div key={vehicle.id} className="p-4 rounded-xl border-2 border-purple-200 bg-purple-50">
                        <div className="flex gap-3">
                          <img
                            src={vehicle.photo || "/placeholder.svg"}
                            alt={vehicle.vehicleName}
                            className="w-20 h-16 object-cover rounded-lg bg-gray-100"
                          />
                          <div className="flex-1">
                            <h4 className="font-semibold text-gray-900 mb-1">{vehicle.vehicleName}</h4>
                            <div className="flex items-center gap-2 text-sm text-gray-600 mb-2">
                              <Users className="h-3 w-3" />
                              <span>Up to {vehicle.passengerLimit} passengers</span>
                            </div>
                            <div className="flex items-center gap-1 text-purple-600 font-bold">
                              <IndianRupee className="h-4 w-4" />
                              <span>{vehicle.perDayPrice.toLocaleString()}</span>
                              <span className="text-xs text-gray-500 font-normal">/day</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            )}

            {/* Hotel Details */}
            <Card className="border-0 shadow-lg">
              <CardHeader className="border-b bg-gradient-to-r from-purple-50 to-white">
                <CardTitle className="flex items-center gap-2">
                  <Hotel className="h-5 w-5 text-purple-600" />
                  Hotel Details
                </CardTitle>
              </CardHeader>
              <CardContent className="p-6">
                <div className="space-y-4">
                  <div className="p-4 rounded-lg border-2 border-purple-200 bg-purple-50">
                    <p className="text-gray-700 leading-relaxed">
                      Comfortable accommodation at 3-star or higher hotels throughout the journey. All hotels include
                      breakfast and dinner as mentioned in the package inclusions.
                    </p>
                  </div>
                  <div className="grid grid-cols-2 gap-3 text-sm">
                    <div className="flex items-center gap-2 text-gray-700">
                      <Check className="h-4 w-4 text-green-600" />
                      <span>Clean & Comfortable Rooms</span>
                    </div>
                    <div className="flex items-center gap-2 text-gray-700">
                      <Check className="h-4 w-4 text-green-600" />
                      <span>Daily Breakfast</span>
                    </div>
                    <div className="flex items-center gap-2 text-gray-700">
                      <Check className="h-4 w-4 text-green-600" />
                      <span>24/7 Room Service</span>
                    </div>
                    <div className="flex items-center gap-2 text-gray-700">
                      <Check className="h-4 w-4 text-green-600" />
                      <span>WiFi Available</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* Passenger Details */}
            <Card className="border-0 shadow-lg">
              <CardHeader className="border-b bg-gradient-to-r from-purple-50 to-white">
                <div className="flex items-center justify-between">
                  <CardTitle className="flex items-center gap-2">
                    <Users className="h-5 w-5 text-purple-600" />
                    Passenger Details
                  </CardTitle>
                  <Button onClick={addCustomer} size="sm" className="gap-2">
                    <Plus className="h-4 w-4" />
                    Add Passenger
                  </Button>
                </div>
              </CardHeader>
              <CardContent className="p-6 space-y-6">
                {customers.map((customer, index) => (
                  <div
                    key={customer.id}
                    className="p-4 md:p-6 rounded-xl border-2 border-purple-200 bg-gradient-to-br from-purple-50/50 to-white"
                  >
                    <div className="flex items-center justify-between mb-4">
                      <h4 className="font-semibold text-sm md:text-base flex items-center gap-2">
                        <User className="h-4 w-4 text-purple-600" />
                        {index === 0 ? "Primary Traveler" : `Traveler ${index + 1}`}
                      </h4>
                      {customers.length > 1 && index > 0 && (
                        <Button
                          variant="ghost"
                          size="sm"
                          onClick={() => removeCustomer(customer.id)}
                          className="text-red-600 hover:text-red-700 hover:bg-red-50 h-8"
                        >
                          <Trash2 className="h-4 w-4 mr-1" />
                          Remove
                        </Button>
                      )}
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                      <div>
                        <Label htmlFor={`name-${customer.id}`}>Full Name *</Label>
                        <Input
                          id={`name-${customer.id}`}
                          placeholder="Enter full name"
                          value={customer.name}
                          onChange={(e) => updateCustomer(customer.id, "name", e.target.value)}
                          className="mt-1.5"
                        />
                      </div>

                      <div>
                        <Label htmlFor={`age-${customer.id}`}>Age *</Label>
                        <Input
                          id={`age-${customer.id}`}
                          type="number"
                          placeholder="Enter age"
                          value={customer.age}
                          onChange={(e) => updateCustomer(customer.id, "age", e.target.value)}
                          className="mt-1.5"
                        />
                      </div>

                      <div>
                        <Label htmlFor={`gender-${customer.id}`}>Gender *</Label>
                        <Select value={customer.gender} onValueChange={(v) => updateCustomer(customer.id, "gender", v)}>
                          <SelectTrigger id={`gender-${customer.id}`} className="mt-1.5">
                            <SelectValue placeholder="Select gender" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="male">Male</SelectItem>
                            <SelectItem value="female">Female</SelectItem>
                            <SelectItem value="other">Other</SelectItem>
                          </SelectContent>
                        </Select>
                      </div>

                      <div>
                        <Label htmlFor={`phone-${customer.id}`}>Phone Number</Label>
                        <div className="relative mt-1.5">
                          <Phone className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                          <Input
                            id={`phone-${customer.id}`}
                            type="tel"
                            placeholder="Enter phone"
                            value={customer.phone}
                            onChange={(e) => updateCustomer(customer.id, "phone", e.target.value)}
                            className="pl-10"
                          />
                        </div>
                      </div>

                      <div className="sm:col-span-2">
                        <Label htmlFor={`email-${customer.id}`}>Email Address</Label>
                        <div className="relative mt-1.5">
                          <Mail className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
                          <Input
                            id={`email-${customer.id}`}
                            type="email"
                            placeholder="Enter email"
                            value={customer.email}
                            onChange={(e) => updateCustomer(customer.id, "email", e.target.value)}
                            className="pl-10"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                ))}
              </CardContent>
            </Card>
          </div>

          {/* Right Side - Booking Summary */}
          <div className="lg:col-span-1">
            <Card className="border-0 shadow-xl sticky top-24">
              <CardHeader className="border-b bg-gradient-to-r from-purple-50 to-white">
                <CardTitle className="flex items-center gap-2">
                  <FileText className="h-5 w-5 text-purple-600" />
                  Booking Summary
                </CardTitle>
              </CardHeader>
              <CardContent className="p-6 space-y-6">
                <div className="space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">Package Name</span>
                    <span className="font-medium text-right max-w-[200px]">{pkg.name}</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">Travelers</span>
                    <span className="font-medium">
                      {customers.length} Person{customers.length > 1 ? "s" : ""}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">Duration</span>
                    <span className="font-medium">{pkg.totalDays} Days</span>
                  </div>
                </div>

                <div className="border-t border-gray-200 pt-4 space-y-3">
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">Package Cost</span>
                    <span className="font-medium">₹{pricing.packageCost.toLocaleString()}</span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="text-gray-600">GST (18%)</span>
                    <span className="font-medium">₹{pricing.gst.toLocaleString()}</span>
                  </div>
                </div>

                <div className="border-t-2 border-purple-200 pt-4">
                  <div className="flex items-center justify-between">
                    <span className="text-lg font-bold text-gray-900">Total Amount</span>
                    <div className="text-right">
                      <div className="flex items-center gap-1 text-2xl font-bold text-purple-600">
                        <IndianRupee className="h-6 w-6" />
                        <span>{pricing.total.toLocaleString()}</span>
                      </div>
                    </div>
                  </div>
                </div>

                <Button
                  onClick={handleBooking}
                  disabled={isSubmitting}
                  className="w-full h-12 text-base bg-gradient-to-r from-purple-600 to-indigo-600 hover:from-purple-700 hover:to-indigo-700 shadow-lg hover:shadow-xl transition-all"
                >
                  {isSubmitting ? (
                    <>
                      <Loader2 className="mr-2 h-5 w-5 animate-spin" />
                      Processing...
                    </>
                  ) : (
                    <>
                      <Check className="mr-2 h-5 w-5" />
                      Confirm Booking
                    </>
                  )}
                </Button>

                <p className="text-xs text-center text-gray-500">By booking, you agree to our terms and conditions</p>
              </CardContent>
            </Card>
          </div>
        </div>
      </main>
    </div>
  )
}
