"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { Upload, X } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";

import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { getStorageUrl } from "@/lib/utils";
import {
  sightseeingSchema,
  type SightseeingInput,
} from "@/lib/validations/location";
import DOMPurify from "dompurify";

import type { AdminSightseeing } from "./types";

interface EditSightseeingDialogProps {
  sightseeing: AdminSightseeing | null;
  open: boolean;
  onOpenChange: (open: boolean) => void;
  onSave: (id: string, name: string, image?: File) => Promise<boolean>;
}

function getImageUrl(path: string | null): string | null {
  if (!path) return null;
  return path.startsWith("http") ? path : getStorageUrl(path);
}

export function EditSightseeingDialog({
  sightseeing,
  open,
  onOpenChange,
  onSave,
}: EditSightseeingDialogProps) {
  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [imagePreview, setImagePreview] = useState<string | null>(null);
  const [imageError, setImageError] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<SightseeingInput>({
    resolver: zodResolver(sightseeingSchema),
    defaultValues: { name: "" },
  });

  useEffect(() => {
    if (!sightseeing) return;
    reset({ name: sightseeing.name });
    setImageFile(null);
    setImagePreview(getImageUrl(sightseeing.image));
    setImageError(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  }, [sightseeing, reset]);

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

  const handleImageChange = (file?: File) => {
    if (!file) return;

    if (!file.type.startsWith("image/")) {
      setImageError("Please upload a valid image file.");
      return;
    }

    if (imagePreview?.startsWith("blob:")) {
      URL.revokeObjectURL(imagePreview);
    }

    setImageFile(file);
    setImagePreview(URL.createObjectURL(file));
    setImageError(null);
  };

  const handleRemoveImage = () => {
    if (imagePreview?.startsWith("blob:")) {
      URL.revokeObjectURL(imagePreview);
    }
    setImageFile(null);
    setImagePreview(null);
    setImageError(null);
    if (fileInputRef.current) {
      fileInputRef.current.value = "";
    }
  };

  const onSubmit = async (data: SightseeingInput) => {
    if (!sightseeing) return;

    setIsSubmitting(true);
    try {
      await onSave(
        sightseeing.id,
        DOMPurify.sanitize(data.name.trim()),
        imageFile ?? undefined
      );
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Edit Sightseeing</DialogTitle>
          <DialogDescription>
            Update the sightseeing location name or replace its image.
          </DialogDescription>
        </DialogHeader>
        <form onSubmit={handleSubmit(onSubmit)}>
          <div className="grid gap-4 py-4">
            <div className="grid gap-2">
              <Label htmlFor="edit-sightseeing-name">Location Name</Label>
              <Input
                id="edit-sightseeing-name"
                placeholder="Enter location name"
                {...register("name")}
                aria-invalid={!!errors.name}
                aria-describedby={
                  errors.name ? "edit-sightseeing-name-error" : undefined
                }
              />
              {errors.name && (
                <p
                  id="edit-sightseeing-name-error"
                  className="text-sm text-destructive"
                >
                  {errors.name.message}
                </p>
              )}
            </div>

            <div className="grid gap-2">
              <Label>Image</Label>
              <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={`${sightseeing?.name ?? "Sightseeing"} preview`}
                    className="h-44 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={handleRemoveImage}
                    >
                      <X className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              ) : (
                <button
                  type="button"
                  onClick={() => fileInputRef.current?.click()}
                  className="flex h-40 w-full flex-col items-center justify-center rounded-xl border-2 border-dashed border-border bg-muted/20 text-sm text-muted-foreground transition hover:border-primary/50 hover:bg-muted/40"
                >
                  <span className="mb-2 rounded-xl bg-primary/10 p-3 text-primary">
                    <Upload className="h-5 w-5" />
                  </span>
                  Upload sight seeing image
                </button>
              )}
              {imageError && (
                <p className="text-sm text-destructive">{imageError}</p>
              )}
            </div>
          </div>
          <DialogFooter>
            <Button
              type="button"
              variant="outline"
              onClick={() => onOpenChange(false)}
            >
              Cancel
            </Button>
            <Button type="submit" disabled={isSubmitting}>
              {isSubmitting ? "Saving..." : "Save Changes"}
            </Button>
          </DialogFooter>
        </form>
      </DialogContent>
    </Dialog>
  );
}
