"use client"

import { useState } from "react"
import { useRouter } from "next/navigation"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import DOMPurify from "isomorphic-dompurify"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator"
import { ArrowLeft, Save, Plus, Trash2, X, ChevronDown, ChevronUp } from "lucide-react"
import { useToastEnhanced } from "@/hooks/use-toast-enhanced"
import {
  customPackageDataStore,
  type DayPlan,
  type PackageLocation,
  type PackageVehicle,
} from "@/lib/data/custom-packages"
import { vehicleDataStore } from "@/lib/data/vehicles"
import { customPackageFormSchema, type CustomPackageFormInput } from "@/lib/validations/custom-packages"

interface PackageFormClientProps {
  mode: "add" | "edit"
  packageId?: string
}

export function PackageFormClient({ mode, packageId }: PackageFormClientProps) {
  const router = useRouter()
  const toast = useToastEnhanced()
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [expandedDays, setExpandedDays] = useState<Set<number>>(new Set([1]))

  const existingPackage = packageId ? customPackageDataStore.getPackageById(packageId) : undefined
  const availableVehicles = vehicleDataStore.getActiveVehicles()

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    formState: { errors },
  } = useForm<CustomPackageFormInput>({
    resolver: zodResolver(customPackageFormSchema),
    defaultValues: existingPackage
      ? {
          cityName: existingPackage.cityName,
          category: existingPackage.category,
          dayPlans: existingPackage.dayPlans,
        }
      : {
          cityName: "",
          category: "spiritual",
          dayPlans: [],
        },
  })

  const dayPlans = watch("dayPlans") || []
  const cityName = watch("cityName")
  const category = watch("category")

  const handleImageUpload = (dayIndex: number, locationIndex: number, file: File) => {
    if (!file.type.startsWith("image/")) {
      toast.error({
        title: "Invalid File",
        description: "Please upload an image file (JPG, PNG, GIF, etc.)",
      })
      return
    }

    const reader = new FileReader()
    reader.onloadend = () => {
      const updatedDayPlans = [...dayPlans]
      updatedDayPlans[dayIndex].locations[locationIndex].image = reader.result as string
      setValue("dayPlans", updatedDayPlans)
    }
    reader.readAsDataURL(file)
  }

  const toggleDayExpansion = (dayNumber: number) => {
    setExpandedDays((prev) => {
      const newSet = new Set(prev)
      if (newSet.has(dayNumber)) {
        newSet.delete(dayNumber)
      } else {
        newSet.add(dayNumber)
      }
      return newSet
    })
  }

  const addDayPlan = (dayNumber: number) => {
    const newDayPlan: DayPlan = {
      dayNumber,
      locations: [],
      vehicles: [],
      pricing: {
        b2cWeekdayPerHead: 0,
        b2cWeekendPerHead: 0,
        b2bAgentPricing: 0,
      },
    }
    setValue("dayPlans", [...dayPlans, newDayPlan])
    setExpandedDays((prev) => new Set([...prev, dayNumber]))
  }

  const removeDayPlan = (dayNumber: number) => {
    setValue(
      "dayPlans",
      dayPlans.filter((d) => d.dayNumber !== dayNumber),
    )
    setExpandedDays((prev) => {
      const newSet = new Set(prev)
      newSet.delete(dayNumber)
      return newSet
    })
  }

  const addLocation = (dayIndex: number) => {
    const newLocation: PackageLocation = {
      id: `loc_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      name: "",
      image: "",
      itineraryDescription: "",
      otherDetails: "",
    }
    const updatedDayPlans = [...dayPlans]
    updatedDayPlans[dayIndex].locations.push(newLocation)
    setValue("dayPlans", updatedDayPlans)
  }

  const removeLocation = (dayIndex: number, locationIndex: number) => {
    const updatedDayPlans = [...dayPlans]
    updatedDayPlans[dayIndex].locations.splice(locationIndex, 1)
    setValue("dayPlans", updatedDayPlans)
  }

  const addVehicle = (dayIndex: number) => {
    const newVehicle: PackageVehicle = {
      id: `veh_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
      vehicleId: "",
      vehicleName: "",
      vehiclePhoto: "",
      perDayPrice: 0,
    }
    const updatedDayPlans = [...dayPlans]
    updatedDayPlans[dayIndex].vehicles.push(newVehicle)
    setValue("dayPlans", updatedDayPlans)
  }

  const removeVehicle = (dayIndex: number, vehicleIndex: number) => {
    const updatedDayPlans = [...dayPlans]
    updatedDayPlans[dayIndex].vehicles.splice(vehicleIndex, 1)
    setValue("dayPlans", updatedDayPlans)
  }

  const handleVehicleSelect = (dayIndex: number, vehicleIndex: number, vehicleId: string) => {
    const vehicle = availableVehicles.find((v) => v.id === vehicleId)
    if (vehicle) {
      const updatedDayPlans = [...dayPlans]
      updatedDayPlans[dayIndex].vehicles[vehicleIndex] = {
        ...updatedDayPlans[dayIndex].vehicles[vehicleIndex],
        vehicleId: vehicle.id,
        vehicleName: vehicle.name,
        vehiclePhoto: vehicle.photo,
        perDayPrice: vehicle.perDayPrice,
      }
      setValue("dayPlans", updatedDayPlans)
    }
  }

  const onSubmit = async (data: CustomPackageFormInput) => {
    setIsSubmitting(true)

    // Sanitize all text inputs
    const sanitizedData = {
      cityName: DOMPurify.sanitize(data.cityName.trim()),
      category: data.category,
      dayPlans: data.dayPlans.map((day) => ({
        ...day,
        locations: day.locations.map((loc) => ({
          ...loc,
          name: DOMPurify.sanitize(loc.name.trim()),
          itineraryDescription: DOMPurify.sanitize(loc.itineraryDescription.trim()),
          otherDetails: DOMPurify.sanitize(loc.otherDetails.trim()),
        })),
      })),
    }

    try {
      if (mode === "add") {
        customPackageDataStore.addPackage(sanitizedData.cityName, sanitizedData.category, sanitizedData.dayPlans)
        toast.success({
          title: "Package Added",
          description: `Custom package for ${sanitizedData.cityName} has been created successfully.`,
        })
      } else if (packageId) {
        customPackageDataStore.updatePackage(
          packageId,
          sanitizedData.cityName,
          sanitizedData.category,
          sanitizedData.dayPlans,
        )
        toast.success({
          title: "Package Updated",
          description: `Custom package for ${sanitizedData.cityName} has been updated successfully.`,
        })
      }
      router.push("/admin/custom-packages")
    } catch (error) {
      toast.error({
        title: "Error",
        description: "Failed to save the package. Please try again.",
      })
    } finally {
      setIsSubmitting(false)
    }
  }

  const availableDays = Array.from({ length: 15 }, (_, i) => i + 1).filter(
    (day) => !dayPlans.some((d) => d.dayNumber === day),
  )

  return (
    <section aria-labelledby="package-form-heading" className="admin-section max-w-5xl">
      <header className="admin-page-header">
        <div className="flex items-center gap-4">
          <Button variant="ghost" size="icon" onClick={() => router.back()} aria-label="Go back">
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 id="package-form-heading" className="admin-page-title">
              {mode === "add" ? "Add New Custom Package" : "Edit Custom Package"}
            </h1>
            <p className="admin-page-description">
              {mode === "add" ? "Create a new multi-day tour package" : "Update package details and itinerary"}
            </p>
          </div>
        </div>
      </header>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        {/* Step 1: City Setup */}
        <Card>
          <CardHeader>
            <CardTitle>Step 1: City Setup</CardTitle>
            <CardDescription>Enter the city name and category for this custom package</CardDescription>
          </CardHeader>
          <CardContent className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="cityName">
                City Name <span className="text-destructive">*</span>
              </Label>
              <Input
                id="cityName"
                {...register("cityName")}
                placeholder="e.g., Varanasi, Ayodhya, Haridwar"
                aria-invalid={!!errors.cityName}
                aria-describedby={errors.cityName ? "cityName-error" : undefined}
              />
              {errors.cityName && (
                <p id="cityName-error" className="text-sm text-destructive">
                  {errors.cityName.message}
                </p>
              )}
            </div>

            <div className="space-y-2">
              <Label htmlFor="category">
                Category <span className="text-destructive">*</span>
              </Label>
              <Select value={category} onValueChange={(value: any) => setValue("category", value)}>
                <SelectTrigger id="category" aria-invalid={!!errors.category}>
                  <SelectValue placeholder="Select a category" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="adventure">Adventure</SelectItem>
                  <SelectItem value="thrill">Thrill</SelectItem>
                  <SelectItem value="suspense">Suspense</SelectItem>
                  <SelectItem value="spiritual">Spiritual</SelectItem>
                  <SelectItem value="others">Others</SelectItem>
                </SelectContent>
              </Select>
              {errors.category && <p className="text-sm text-destructive">{errors.category.message}</p>}
            </div>
          </CardContent>
        </Card>

        {/* Step 2: Day Plans */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle>Step 2: Day Plans</CardTitle>
                <CardDescription>Select days and add locations, vehicles, and pricing for each day</CardDescription>
              </div>
              {availableDays.length > 0 && (
                <Select onValueChange={(value) => addDayPlan(Number(value))}>
                  <SelectTrigger className="w-48" aria-label="Add new day plan">
                    <SelectValue placeholder="Add New Day Plan" />
                  </SelectTrigger>
                  <SelectContent>
                    {availableDays.map((day) => (
                      <SelectItem key={day} value={String(day)}>
                        Day {day}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              )}
            </div>
          </CardHeader>
          <CardContent className="space-y-4">
            {dayPlans.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <p>No day plans added yet. Select a day from the dropdown to get started.</p>
              </div>
            ) : (
              dayPlans.map((dayPlan, dayIndex) => {
                const isExpanded = expandedDays.has(dayPlan.dayNumber)
                return (
                  <Card key={dayPlan.dayNumber} className="border-2">
                    <CardHeader>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center gap-3">
                          <Badge variant="default" className="text-base px-3 py-1">
                            Day {dayPlan.dayNumber}
                          </Badge>
                          <span className="text-sm text-muted-foreground">
                            {dayPlan.locations.length} location(s), {dayPlan.vehicles.length} vehicle(s)
                          </span>
                        </div>
                        <div className="flex gap-2">
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => toggleDayExpansion(dayPlan.dayNumber)}
                            aria-label={isExpanded ? "Collapse day plan" : "Expand day plan"}
                          >
                            {isExpanded ? <ChevronUp className="h-5 w-5" /> : <ChevronDown className="h-5 w-5" />}
                          </Button>
                          <Button
                            type="button"
                            variant="ghost"
                            size="icon"
                            onClick={() => removeDayPlan(dayPlan.dayNumber)}
                            aria-label="Remove day plan"
                          >
                            <X className="h-5 w-5 text-destructive" />
                          </Button>
                        </div>
                      </div>
                    </CardHeader>

                    {isExpanded && (
                      <CardContent className="space-y-6">
                        {/* Locations */}
                        <div className="space-y-4">
                          <div className="flex items-center justify-between">
                            <h4 className="font-semibold">Locations</h4>
                            <Button type="button" variant="outline" size="sm" onClick={() => addLocation(dayIndex)}>
                              <Plus className="mr-2 h-4 w-4" />
                              Add Location
                            </Button>
                          </div>

                          {dayPlan.locations.length === 0 ? (
                            <p className="text-sm text-muted-foreground text-center py-4">No locations added yet</p>
                          ) : (
                            dayPlan.locations.map((location, locationIndex) => (
                              <Card key={location.id} className="p-4">
                                <div className="flex items-start justify-between mb-4">
                                  <h5 className="font-medium">Location {locationIndex + 1}</h5>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => removeLocation(dayIndex, locationIndex)}
                                    aria-label="Remove location"
                                  >
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </div>
                                <div className="grid gap-4 sm:grid-cols-2">
                                  <div className="space-y-2">
                                    <Label htmlFor={`dayPlans.${dayIndex}.locations.${locationIndex}.name`}>
                                      Location Name <span className="text-destructive">*</span>
                                    </Label>
                                    <Input
                                      id={`dayPlans.${dayIndex}.locations.${locationIndex}.name`}
                                      {...register(`dayPlans.${dayIndex}.locations.${locationIndex}.name`)}
                                      placeholder="e.g., Kashi Vishwanath Temple"
                                    />
                                    {errors.dayPlans?.[dayIndex]?.locations?.[locationIndex]?.name && (
                                      <p className="text-sm text-destructive">
                                        {errors.dayPlans[dayIndex]?.locations?.[locationIndex]?.name?.message}
                                      </p>
                                    )}
                                  </div>

                                  <div className="space-y-2">
                                    <Label htmlFor={`dayPlans.${dayIndex}.locations.${locationIndex}.image`}>
                                      Image <span className="text-destructive">*</span>
                                    </Label>
                                    <div className="flex items-center gap-2">
                                      <Input
                                        id={`dayPlans.${dayIndex}.locations.${locationIndex}.image`}
                                        type="file"
                                        accept="image/*"
                                        onChange={(e) => {
                                          const file = e.target.files?.[0]
                                          if (file) {
                                            handleImageUpload(dayIndex, locationIndex, file)
                                          }
                                        }}
                                        className="cursor-pointer"
                                      />
                                      {location.image && (
                                        <div className="relative h-10 w-10 rounded border overflow-hidden flex-shrink-0">
                                          <img
                                            src={location.image || "/placeholder.svg"}
                                            alt="Preview"
                                            className="h-full w-full object-cover"
                                          />
                                        </div>
                                      )}
                                    </div>
                                    {errors.dayPlans?.[dayIndex]?.locations?.[locationIndex]?.image && (
                                      <p className="text-sm text-destructive">
                                        {errors.dayPlans[dayIndex]?.locations?.[locationIndex]?.image?.message}
                                      </p>
                                    )}
                                  </div>

                                  <div className="space-y-2 sm:col-span-2">
                                    <Label
                                      htmlFor={`dayPlans.${dayIndex}.locations.${locationIndex}.itineraryDescription`}
                                    >
                                      Itinerary Description <span className="text-destructive">*</span>
                                    </Label>
                                    <Textarea
                                      id={`dayPlans.${dayIndex}.locations.${locationIndex}.itineraryDescription`}
                                      {...register(
                                        `dayPlans.${dayIndex}.locations.${locationIndex}.itineraryDescription`,
                                      )}
                                      placeholder="Describe the visit plan and highlights..."
                                      rows={3}
                                    />
                                    {errors.dayPlans?.[dayIndex]?.locations?.[locationIndex]?.itineraryDescription && (
                                      <p className="text-sm text-destructive">
                                        {
                                          errors.dayPlans[dayIndex]?.locations?.[locationIndex]?.itineraryDescription
                                            ?.message
                                        }
                                      </p>
                                    )}
                                  </div>
                                  <div className="space-y-2 sm:col-span-2">
                                    <Label htmlFor={`dayPlans.${dayIndex}.locations.${locationIndex}.otherDetails`}>
                                      Other Details
                                    </Label>
                                    <Textarea
                                      id={`dayPlans.${dayIndex}.locations.${locationIndex}.otherDetails`}
                                      {...register(`dayPlans.${dayIndex}.locations.${locationIndex}.otherDetails`)}
                                      placeholder="Additional information, timings, tips, etc."
                                      rows={2}
                                    />
                                  </div>
                                </div>
                              </Card>
                            ))
                          )}
                        </div>

                        <Separator />

                        {/* Vehicles */}
                        <div className="space-y-4">
                          <div className="flex items-center justify-between">
                            <h4 className="font-semibold">Vehicles</h4>
                            <Button type="button" variant="outline" size="sm" onClick={() => addVehicle(dayIndex)}>
                              <Plus className="mr-2 h-4 w-4" />
                              Add Vehicle
                            </Button>
                          </div>

                          {dayPlan.vehicles.length === 0 ? (
                            <p className="text-sm text-muted-foreground text-center py-4">No vehicles added yet</p>
                          ) : (
                            dayPlan.vehicles.map((vehicle, vehicleIndex) => (
                              <Card key={vehicle.id} className="p-4">
                                <div className="flex items-start justify-between mb-4">
                                  <h5 className="font-medium">Vehicle {vehicleIndex + 1}</h5>
                                  <Button
                                    type="button"
                                    variant="ghost"
                                    size="icon"
                                    onClick={() => removeVehicle(dayIndex, vehicleIndex)}
                                    aria-label="Remove vehicle"
                                  >
                                    <Trash2 className="h-4 w-4 text-destructive" />
                                  </Button>
                                </div>
                                <div className="space-y-4">
                                  <div className="space-y-2">
                                    <Label htmlFor={`dayPlans.${dayIndex}.vehicles.${vehicleIndex}.vehicleId`}>
                                      Select Vehicle <span className="text-destructive">*</span>
                                    </Label>
                                    <Select
                                      value={vehicle.vehicleId}
                                      onValueChange={(value) => handleVehicleSelect(dayIndex, vehicleIndex, value)}
                                    >
                                      <SelectTrigger id={`dayPlans.${dayIndex}.vehicles.${vehicleIndex}.vehicleId`}>
                                        <SelectValue placeholder="Choose a vehicle" />
                                      </SelectTrigger>
                                      <SelectContent>
                                        {availableVehicles.map((v) => (
                                          <SelectItem key={v.id} value={v.id}>
                                            {v.name} - ₹{v.perDayPrice}/day ({v.passengerLimit} seats)
                                          </SelectItem>
                                        ))}
                                      </SelectContent>
                                    </Select>
                                    {errors.dayPlans?.[dayIndex]?.vehicles?.[vehicleIndex]?.vehicleId && (
                                      <p className="text-sm text-destructive">
                                        {errors.dayPlans[dayIndex]?.vehicles?.[vehicleIndex]?.vehicleId?.message}
                                      </p>
                                    )}
                                  </div>

                                  {vehicle.vehicleId && (
                                    <Card className="p-3 bg-muted/50">
                                      <div className="flex items-center gap-3">
                                        {vehicle.vehiclePhoto && (
                                          <img
                                            src={vehicle.vehiclePhoto || "/placeholder.svg"}
                                            alt={vehicle.vehicleName}
                                            className="h-16 w-24 rounded object-cover"
                                          />
                                        )}
                                        <div className="flex-1">
                                          <p className="font-medium">{vehicle.vehicleName}</p>
                                          <p className="text-sm text-muted-foreground">
                                            ₹{vehicle.perDayPrice} per day
                                          </p>
                                        </div>
                                      </div>
                                    </Card>
                                  )}
                                </div>
                              </Card>
                            ))
                          )}
                        </div>

                        <Separator />

                        {/* Pricing */}
                        <div className="space-y-4">
                          <h4 className="font-semibold">Pricing (Per Person)</h4>
                          <div className="grid gap-4 sm:grid-cols-3">
                            <div className="space-y-2">
                              <Label htmlFor={`dayPlans.${dayIndex}.pricing.b2cWeekdayPerHead`}>
                                B2C Weekday <span className="text-destructive">*</span>
                              </Label>
                              <Input
                                id={`dayPlans.${dayIndex}.pricing.b2cWeekdayPerHead`}
                                type="number"
                                {...register(`dayPlans.${dayIndex}.pricing.b2cWeekdayPerHead`, {
                                  valueAsNumber: true,
                                })}
                                placeholder="1500"
                              />
                              {errors.dayPlans?.[dayIndex]?.pricing?.b2cWeekdayPerHead && (
                                <p className="text-sm text-destructive">
                                  {errors.dayPlans[dayIndex]?.pricing?.b2cWeekdayPerHead?.message}
                                </p>
                              )}
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor={`dayPlans.${dayIndex}.pricing.b2cWeekendPerHead`}>
                                B2C Weekend <span className="text-destructive">*</span>
                              </Label>
                              <Input
                                id={`dayPlans.${dayIndex}.pricing.b2cWeekendPerHead`}
                                type="number"
                                {...register(`dayPlans.${dayIndex}.pricing.b2cWeekendPerHead`, {
                                  valueAsNumber: true,
                                })}
                                placeholder="1800"
                              />
                              {errors.dayPlans?.[dayIndex]?.pricing?.b2cWeekendPerHead && (
                                <p className="text-sm text-destructive">
                                  {errors.dayPlans[dayIndex]?.pricing?.b2cWeekendPerHead?.message}
                                </p>
                              )}
                            </div>
                            <div className="space-y-2">
                              <Label htmlFor={`dayPlans.${dayIndex}.pricing.b2bAgentPricing`}>
                                B2B Agent <span className="text-destructive">*</span>
                              </Label>
                              <Input
                                id={`dayPlans.${dayIndex}.pricing.b2bAgentPricing`}
                                type="number"
                                {...register(`dayPlans.${dayIndex}.pricing.b2bAgentPricing`, {
                                  valueAsNumber: true,
                                })}
                                placeholder="1200"
                              />
                              {errors.dayPlans?.[dayIndex]?.pricing?.b2bAgentPricing && (
                                <p className="text-sm text-destructive">
                                  {errors.dayPlans[dayIndex]?.pricing?.b2bAgentPricing?.message}
                                </p>
                              )}
                            </div>
                          </div>
                        </div>
                      </CardContent>
                    )}
                  </Card>
                )
              })
            )}
          </CardContent>
        </Card>

        {/* Submit Button */}
        <div className="flex justify-end gap-3">
          <Button type="button" variant="outline" onClick={() => router.back()} disabled={isSubmitting}>
            Cancel
          </Button>
          <Button type="submit" disabled={isSubmitting}>
            <Save className="mr-2 h-4 w-4" />
            {isSubmitting ? "Saving..." : mode === "add" ? "Create Package" : "Update Package"}
          </Button>
        </div>
      </form>
    </section>
  )
}
