"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import {
  ArrowLeft,
  CheckCircle2,
  FileText,
  ImageIcon,
  Info,
  Save,
  Upload,
  X,
  XCircle,
} from "lucide-react";
import { useRouter } from "next/navigation";
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 { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { useToastEnhanced } from "@/hooks/use-toast-enhanced";
import { createVehicleAction } from "@/features/vehicles/actions/vehicles-actions";
import {
  vehicleCreateSchema,
  type VehicleCreateInput,
} from "@/lib/validations/vehicle-create";

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

interface VehicleCreateFormClientProps {
  categories: VehicleCategoryOption[];
}

export function VehicleCreateFormClient({
  categories,
}: VehicleCreateFormClientProps) {
  const router = useRouter();
  const toast = useToastEnhanced();
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [imagePreview, setImagePreview] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    setValue,
    watch,
    formState: { errors },
  } = useForm<VehicleCreateInput>({
    resolver: zodResolver(vehicleCreateSchema),
    defaultValues: {
      vehicle_category_id: undefined,
      name: "",
      fuel_type: "petrol",
      transmission: "manual",
      seating_capacity: 4,
      default_mileage: 0,
      mileage: 0,
      price_type: "per_km",
      description: "",
      status: "active",
      inclusion: "",
      exclusion: "",
    },
  });

  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(() => {
    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", undefined as never, { shouldValidate: true });
    if (imagePreview?.startsWith("blob:")) {
      URL.revokeObjectURL(imagePreview);
    }
    setImagePreview(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const onSubmit = async (data: VehicleCreateInput) => {
    setIsSubmitting(true);
    try {
      const result = await createVehicleAction(data);
      if (!result.success) {
        toast.error({
          title: "Failed to Create Vehicle",
          description: result.error || "Could not create vehicle.",
        });
        return;
      }

      toast.success({
        title: "Vehicle Created",
        description: result.message || `${data.name} has been created.`,
      });
      router.push("/admin/vehicle-listing");
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <section className="admin-section">
      <header className="admin-page-header mb-6">
        <div className="flex items-center gap-4">
          <Button
            variant="ghost"
            size="icon"
            onClick={() => router.back()}
            aria-label="Go back"
            type="button"
          >
            <ArrowLeft className="h-5 w-5" />
          </Button>
          <div>
            <h1 className="admin-page-title">Add New Vehicle</h1>
            <p className="admin-page-description">
              Create a vehicle with complete information and policy details.
            </p>
          </div>
        </div>
      </header>

      <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
        <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 (PNG, JPG, JPEG up to 5MB).
                </CardDescription>
              </CardHeader>
              <CardContent>
                <input
                  ref={fileInputRef}
                  type="file"
                  accept="image/*"
                  className="hidden"
                  onChange={(e) => handleImageChange(e.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">
                      Drag and drop image here
                    </span>
                    <span className="text-xs text-muted-foreground">
                      or click to browse from your device
                    </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>
                  Fill the required API fields 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 VehicleCreateInput["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 VehicleCreateInput["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 VehicleCreateInput["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 VehicleCreateInput["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 className="sticky bottom-0 z-10 flex justify-end gap-4 border-t bg-background/95 p-4 backdrop-blur">
          <Button type="button" variant="outline" onClick={() => router.back()}>
            Cancel
          </Button>
          <Button
            type="submit"
            className="frontend-btn"
            disabled={isSubmitting}
          >
            <Save className="mr-2 h-4 w-4" />
            {isSubmitting ? "Creating..." : "Create Vehicle"}
          </Button>
        </div>
      </form>
    </section>
  );
}
