﻿"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import {
  ArrowLeft,
  CheckCircle2,
  FileText,
  ImageIcon,
  Info,
  Save,
  Upload,
  X,
  XCircle,
} from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { RichTextEditor } from "@/components/shared/rich-text-editor";
import { Button } from "@/components/ui/button";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { getStorageUrl } from "@/lib/utils";
import {
  type VehicleUpdateInput,
  vehicleUpdateSchema,
} from "@/lib/validations/vehicle-create";
import type { VehicleListItem } from "@/features/vehicles/actions/vehicles-actions";

interface VehicleCategoryOption {
  id: number;
  name: string;
}

interface EditVehicleDialogProps {
  vehicle: VehicleListItem | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  categories: VehicleCategoryOption[];
  onSave: (input: VehicleUpdateInput) => Promise<boolean>;
}

export function EditVehicleDialog({
  vehicle,
  open,
  onOpenChange,
  categories,
  onSave,
}: EditVehicleDialogProps) {
  const [isSubmitting, setIsSubmitting] = useState(false);
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const existingImageUrl = vehicle?.image ? getStorageUrl(vehicle.image) : null;
  const [imagePreview, setImagePreview] = useState<string | null>(
    existingImageUrl
  );

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<VehicleUpdateInput>({
    resolver: zodResolver(vehicleUpdateSchema),
    defaultValues: {
      vehicle_id: vehicle?.id ?? vehicle?.vehicle_id ?? 0,
      vehicle_category_id: vehicle?.vehicle_category_id ?? undefined,
      name: vehicle?.name ?? "",
      fuel_type:
        (vehicle?.fuel_type as VehicleUpdateInput["fuel_type"]) ?? "petrol",
      transmission:
        (vehicle?.transmission as VehicleUpdateInput["transmission"]) ??
        "manual",
      seating_capacity: vehicle?.seating_capacity ?? 4,
      default_mileage: vehicle?.default_mileage ?? 0,
      mileage: vehicle?.mileage ?? 0,
      price_type:
        (vehicle?.price_type as VehicleUpdateInput["price_type"]) ?? "per_km",
      description: vehicle?.description ?? "",
      status: (vehicle?.status as VehicleUpdateInput["status"]) ?? "active",
      inclusion: vehicle?.inclusion ?? "",
      exclusion: vehicle?.exclusion ?? "",
      image: vehicle?.image ?? undefined,
    },
  });

  const selectedCategory = watch("vehicle_category_id");
  const selectedFuelType = watch("fuel_type");
  const selectedTransmission = watch("transmission");
  const selectedPriceType = watch("price_type");
  const selectedStatus = watch("status");

  useEffect(() => {
    if (vehicle) {
      reset({
        vehicle_id: vehicle.id ?? vehicle.vehicle_id ?? 0,
        vehicle_category_id: vehicle.vehicle_category_id,
        name: vehicle.name,
        fuel_type: vehicle.fuel_type as VehicleUpdateInput["fuel_type"],
        transmission:
          vehicle.transmission as VehicleUpdateInput["transmission"],
        seating_capacity: vehicle.seating_capacity,
        default_mileage: vehicle.default_mileage,
        mileage: vehicle.mileage,
        price_type: vehicle.price_type as VehicleUpdateInput["price_type"],
        description: vehicle.description || "",
        status: vehicle.status as VehicleUpdateInput["status"],
        inclusion: vehicle.inclusion || "",
        exclusion: vehicle.exclusion || "",
        image: vehicle.image ?? undefined,
      });
      setImagePreview(existingImageUrl);
      if (fileInputRef.current) {
        fileInputRef.current.value = "";
      }
    }
  }, [vehicle, existingImageUrl, reset]);

  useEffect(() => {
    return () => {
      if (imagePreview?.startsWith("blob:")) {
        URL.revokeObjectURL(imagePreview);
      }
    };
  }, [imagePreview]);

  const handleImageChange = (file?: File) => {
    if (!file) return;
    setValue("image", file, { shouldValidate: true });
    if (imagePreview?.startsWith("blob:")) {
      URL.revokeObjectURL(imagePreview);
    }
    setImagePreview(URL.createObjectURL(file));
  };

  const clearImage = () => {
    setValue("image", vehicle?.image ?? undefined, { shouldValidate: true });
    if (imagePreview?.startsWith("blob:")) {
      URL.revokeObjectURL(imagePreview);
    }
    setImagePreview(existingImageUrl);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

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

    try {
      const success = await onSave(data);
      if (!success) return;
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-[90vw] max-h-[90vh] flex flex-col">
        <DialogHeader className="flex-shrink-0">
          <DialogTitle>Edit Vehicle</DialogTitle>
          <DialogDescription>
            Make changes to the vehicle details and submit when ready.
          </DialogDescription>
        </DialogHeader>

        <form
          onSubmit={handleSubmit(onSubmit)}
          className="flex flex-col flex-1 overflow-hidden"
        >
          <div className="flex-1 overflow-y-auto space-y-6 px-4 pb-4">
            <input type="hidden" {...register("vehicle_id")} />

            <div className="rounded-2xl bg-gradient-to-r from-primary/5 via-secondary/10 to-primary/5 p-1">
              <div className="grid gap-6 rounded-[calc(1rem-2px)] bg-background p-4 md:grid-cols-2 md:p-6">
                <Card className="border-border/60 shadow-sm">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <ImageIcon className="h-5 w-5 text-primary" />
                      Vehicle Image
                    </CardTitle>
                    <CardDescription>
                      Upload a clear vehicle image. Only include a new image
                      when changing it.
                    </CardDescription>
                  </CardHeader>
                  <CardContent>
                    <input
                      ref={fileInputRef}
                      type="file"
                      accept="image/*"
                      className="hidden"
                      onChange={(event) =>
                        handleImageChange(event.target.files?.[0])
                      }
                    />

                    {imagePreview ? (
                      <div className="relative overflow-hidden rounded-xl border border-border">
                        <img
                          src={imagePreview}
                          alt="Vehicle preview"
                          className="h-64 w-full object-cover"
                        />
                        <div className="absolute right-2 top-2 flex gap-2">
                          <Button
                            type="button"
                            size="sm"
                            variant="secondary"
                            onClick={() => fileInputRef.current?.click()}
                          >
                            Update
                          </Button>
                          <Button
                            type="button"
                            size="icon"
                            variant="destructive"
                            onClick={clearImage}
                          >
                            <X className="h-4 w-4" />
                          </Button>
                        </div>
                      </div>
                    ) : (
                      <button
                        type="button"
                        onClick={() => fileInputRef.current?.click()}
                        className="flex h-64 w-full flex-col items-center justify-center rounded-xl border-2 border-dashed border-primary/30 bg-primary/5 text-sm text-muted-foreground transition hover:border-primary/50 hover:bg-primary/10"
                      >
                        <span className="mb-2 rounded-full bg-primary/15 p-3 text-primary">
                          <Upload className="h-6 w-6" />
                        </span>
                        <span className="font-medium text-foreground">
                          Click to upload vehicle image
                        </span>
                        <span className="text-xs text-muted-foreground">
                          Only include a new image if you want to overwrite the
                          existing one.
                        </span>
                      </button>
                    )}
                    {errors.image && (
                      <p className="mt-2 text-sm text-destructive">
                        {errors.image.message}
                      </p>
                    )}
                  </CardContent>
                </Card>

                <Card className="border-border/60 shadow-sm">
                  <CardHeader>
                    <CardTitle className="flex items-center gap-2">
                      <Info className="h-5 w-5 text-primary" />
                      Basic Information
                    </CardTitle>
                    <CardDescription>
                      Update the API fields needed for this vehicle.
                    </CardDescription>
                  </CardHeader>
                  <CardContent className="grid gap-4 md:grid-cols-2">
                    <div className="space-y-2 md:col-span-2">
                      <Label>Vehicle Category</Label>
                      <Select
                        value={selectedCategory ? String(selectedCategory) : ""}
                        onValueChange={(value) =>
                          setValue("vehicle_category_id", Number(value), {
                            shouldValidate: true,
                          })
                        }
                      >
                        <SelectTrigger
                          aria-invalid={!!errors.vehicle_category_id}
                        >
                          <SelectValue placeholder="Select category" />
                        </SelectTrigger>
                        <SelectContent>
                          {categories.map((category) => (
                            <SelectItem
                              key={category.id}
                              value={String(category.id)}
                            >
                              {category.name}
                            </SelectItem>
                          ))}
                        </SelectContent>
                      </Select>
                      {errors.vehicle_category_id && (
                        <p className="text-sm text-destructive">
                          {errors.vehicle_category_id.message}
                        </p>
                      )}
                    </div>

                    <div className="space-y-2 md:col-span-2">
                      <Label htmlFor="vehicle-name">Vehicle Name</Label>
                      <Input
                        id="vehicle-name"
                        placeholder="e.g., Toyota Camry 2024"
                        {...register("name")}
                        aria-invalid={!!errors.name}
                      />
                      {errors.name && (
                        <p className="text-sm text-destructive">
                          {errors.name.message}
                        </p>
                      )}
                    </div>

                    <div className="space-y-2">
                      <Label>Fuel Type</Label>
                      <Select
                        value={selectedFuelType}
                        onValueChange={(value) =>
                          setValue(
                            "fuel_type",
                            value as VehicleUpdateInput["fuel_type"],
                            {
                              shouldValidate: true,
                            }
                          )
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="petrol">Petrol</SelectItem>
                          <SelectItem value="diesel">Diesel</SelectItem>
                          <SelectItem value="electric">Electric</SelectItem>
                          <SelectItem value="hybrid">Hybrid</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label>Transmission</Label>
                      <Select
                        value={selectedTransmission}
                        onValueChange={(value) =>
                          setValue(
                            "transmission",
                            value as VehicleUpdateInput["transmission"],
                            {
                              shouldValidate: true,
                            }
                          )
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="manual">Manual</SelectItem>
                          <SelectItem value="automatic">Automatic</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="seating-capacity">Seating Capacity</Label>
                      <Input
                        id="seating-capacity"
                        type="number"
                        min={1}
                        placeholder="e.g., 5"
                        {...register("seating_capacity")}
                        aria-invalid={!!errors.seating_capacity}
                      />
                      {errors.seating_capacity && (
                        <p className="text-sm text-destructive">
                          {errors.seating_capacity.message}
                        </p>
                      )}
                    </div>

                    <div className="space-y-2">
                      <Label htmlFor="default-mileage">Default Mileage</Label>
                      <Input
                        id="default-mileage"
                        type="number"
                        min={0}
                        step="0.01"
                        placeholder="e.g., 15"
                        {...register("default_mileage")}
                        aria-invalid={!!errors.default_mileage}
                      />
                      {errors.default_mileage && (
                        <p className="text-sm text-destructive">
                          {errors.default_mileage.message}
                        </p>
                      )}
                    </div>

                    <div className="space-y-2 md:col-span-2">
                      <Label htmlFor="mileage">Current Mileage</Label>
                      <Input
                        id="mileage"
                        type="number"
                        min={0}
                        step="0.01"
                        placeholder="e.g., 25000"
                        {...register("mileage")}
                        aria-invalid={!!errors.mileage}
                      />
                      {errors.mileage && (
                        <p className="text-sm text-destructive">
                          {errors.mileage.message}
                        </p>
                      )}
                    </div>

                    <div className="space-y-2">
                      <Label>Price Type</Label>
                      <Select
                        value={selectedPriceType}
                        onValueChange={(value) =>
                          setValue(
                            "price_type",
                            value as VehicleUpdateInput["price_type"],
                            {
                              shouldValidate: true,
                            }
                          )
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="per_km">Per KM</SelectItem>
                          <SelectItem value="per_day">Per Day</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>

                    <div className="space-y-2">
                      <Label>Status</Label>
                      <Select
                        value={selectedStatus}
                        onValueChange={(value) =>
                          setValue(
                            "status",
                            value as VehicleUpdateInput["status"],
                            {
                              shouldValidate: true,
                            }
                          )
                        }
                      >
                        <SelectTrigger>
                          <SelectValue placeholder="Select" />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="active">Active</SelectItem>
                          <SelectItem value="inactive">Inactive</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                  </CardContent>
                </Card>
              </div>
            </div>

            <div className="grid gap-6 md:grid-cols-2">
              <Card className="border-border/60 shadow-sm">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <CheckCircle2 className="h-5 w-5 text-green-600" />
                    Inclusions
                  </CardTitle>
                  <CardDescription>
                    What is included in this vehicle service.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-2">
                  <RichTextEditor
                    value={watch("inclusion") || ""}
                    onChange={(value) =>
                      setValue("inclusion", value, { shouldValidate: true })
                    }
                    placeholder="Add inclusions..."
                  />
                  {errors.inclusion && (
                    <p className="text-sm text-destructive">
                      {errors.inclusion.message}
                    </p>
                  )}
                </CardContent>
              </Card>

              <Card className="border-border/60 shadow-sm">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <XCircle className="h-5 w-5 text-rose-600" />
                    Exclusions
                  </CardTitle>
                  <CardDescription>
                    What is not included in this vehicle service.
                  </CardDescription>
                </CardHeader>
                <CardContent className="space-y-2">
                  <RichTextEditor
                    value={watch("exclusion") || ""}
                    onChange={(value) =>
                      setValue("exclusion", value, { shouldValidate: true })
                    }
                    placeholder="Add exclusions..."
                  />
                  {errors.exclusion && (
                    <p className="text-sm text-destructive">
                      {errors.exclusion.message}
                    </p>
                  )}
                </CardContent>
              </Card>
            </div>

            <Card className="border-border/60 shadow-sm">
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="h-5 w-5 text-primary" />
                  Vehicle Description
                </CardTitle>
                <CardDescription>
                  Provide a detailed description highlighting features and
                  comfort.
                </CardDescription>
              </CardHeader>
              <CardContent className="space-y-2">
                <RichTextEditor
                  value={watch("description") || ""}
                  onChange={(value) =>
                    setValue("description", value, { shouldValidate: true })
                  }
                  placeholder="Provide a comprehensive description of the vehicle..."
                />
                {errors.description && (
                  <p className="text-sm text-destructive">
                    {errors.description.message}
                  </p>
                )}
              </CardContent>
            </Card>
          </div>

          <DialogFooter className="flex-shrink-0 border-t pt-4">
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              <Save className="mr-2 h-4 w-4" />
              {isSubmitting ? "Saving..." : "Save Changes"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
