"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 { getStorageUrl } from "@/lib/utils";
import {
    updateVehicleAction,
    type UpdateVehicleInput,
    type VehicleListItem,
} from "@/features/vehicles/actions/vehicles-actions";
import { vehicleUpdateSchema } from "@/lib/validations/vehicle-create";

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

interface VehicleEditFormClientProps {
    vehicle: VehicleListItem;
    categories: VehicleCategoryOption[];
}

export function VehicleEditFormClient({ vehicle, categories }: VehicleEditFormClientProps) {
    const router = useRouter();
    const toast = useToastEnhanced();
    const fileInputRef = useRef<HTMLInputElement | null>(null);
    const [isSubmitting, setIsSubmitting] = useState(false);
    const [imagePreview, setImagePreview] = useState<string | null>(
        vehicle.image ? getStorageUrl(vehicle.image) : null
    );

    const {
        register,
        handleSubmit,
        setValue,
        watch,
        formState: { errors },
    } = useForm<UpdateVehicleInput>({
        resolver: zodResolver(vehicleUpdateSchema),
        defaultValues: {
            vehicle_id: vehicle.id ?? vehicle.vehicle_id ?? 0,
            vehicle_category_id: vehicle.vehicle_category_id,
            name: vehicle.name,
            fuel_type: vehicle.fuel_type as UpdateVehicleInput["fuel_type"],
            transmission: vehicle.transmission as UpdateVehicleInput["transmission"],
            seating_capacity: vehicle.seating_capacity,
            default_mileage: vehicle.default_mileage,
            mileage: vehicle.mileage,
            price_type: vehicle.price_type as UpdateVehicleInput["price_type"],
            description: vehicle.description ?? "",
            status: vehicle.status as UpdateVehicleInput["status"],
            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(() => {
        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(vehicle.image ? getStorageUrl(vehicle.image) : null);
        if (fileInputRef.current) {
            fileInputRef.current.value = "";
        }
    };

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

            toast.success({
                title: "Vehicle Updated",
                description: result.message || `${data.name} has been updated successfully.`,
            });
            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">Edit Vehicle</h1>
                        <p className="admin-page-description">
                            Update the vehicle details and submit changes when ready.
                        </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 new vehicle image only if you want to replace the existing one.
                                </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>
                                    Change any of the vehicle fields below.
                                </CardDescription>
                            </CardHeader>
                            <CardContent className="grid gap-4 md:grid-cols-2">
                                <div className="space-y-2 md:col-span-2">
                                    <input type="hidden" id="vehicle_id" {...register("vehicle_id")} />
                                    <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 UpdateVehicleInput["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 UpdateVehicleInput["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 UpdateVehicleInput["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 UpdateVehicleInput["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 ? "Updating..." : "Update Vehicle"}
                    </Button>
                </div>
            </form>
        </section>
    );
}
