"use client";

import * as React from "react";

import { ImagePlus, X } from "lucide-react";

import { Button } from "@/components/ui/button";
import { ImagePreview } from "@/components/ui/image-preview";
import { cn } from "@/lib/utils";

type ImageFieldProps = {
  id: string;
  label: string;
  hint?: string;
  value: File | null | undefined;
  existingUrl?: string | null;
  onChange: (file: File | null) => void;
};

export function SecurityNameImageField({
  id,
  label,
  hint,
  value,
  existingUrl,
  onChange,
}: ImageFieldProps) {
  const inputRef = React.useRef<HTMLInputElement>(null);
  const objectUrlRef = React.useRef<string | null>(null);
  const [preview, setPreview] = React.useState<string | null>(existingUrl ?? null);

  React.useEffect(() => {
    return () => {
      if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current);
    };
  }, []);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0] ?? null;
    if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current);
    objectUrlRef.current = file ? URL.createObjectURL(file) : null;
    setPreview(objectUrlRef.current ?? existingUrl ?? null);
    onChange(file);
  };

  return (
    <div className="space-y-1.5">
      <label htmlFor={id} className="block font-medium text-xs">
        {label}
      </label>
      <input
        ref={inputRef}
        id={id}
        type="file"
        accept=".png,.jpg,.jpeg,.gif,.svg"
        className="sr-only"
        onChange={handleChange}
      />
      <button
        type="button"
        onClick={() => inputRef.current?.click()}
        className={cn(
          "group relative flex aspect-[4/3] max-w-xs items-center justify-center overflow-hidden rounded-lg border-2 border-dashed bg-muted/30 transition-colors hover:border-primary/60 hover:bg-muted/50",
          preview && "border-solid bg-background",
        )}
      >
        {preview ? (
          <ImagePreview src={preview} alt={label} className="h-full w-full" />
        ) : (
          <div className="flex flex-col items-center gap-1.5 text-muted-foreground text-xs">
            <ImagePlus className="size-6" />
            <span>Click to upload</span>
            <span className="text-[10px]">PNG / JPG / GIF / SVG</span>
          </div>
        )}
      </button>
      <div className="flex items-center justify-between gap-2 max-w-xs">
        <p className="truncate text-muted-foreground text-[11px]">
          {value?.name ?? hint ?? "Optional gallery image"}
        </p>
        {value || existingUrl ? (
          <Button
            type="button"
            variant="ghost"
            size="sm"
            className="h-6 gap-1 px-1.5 text-rose-600 text-[11px] hover:bg-rose-50 hover:text-rose-700"
            onClick={(e) => {
              e.stopPropagation();
              if (objectUrlRef.current) URL.revokeObjectURL(objectUrlRef.current);
              objectUrlRef.current = null;
              onChange(null);
              if (inputRef.current) inputRef.current.value = "";
              setPreview(null);
            }}
          >
            <X className="size-3" />
            Remove
          </Button>
        ) : null}
      </div>
    </div>
  );
}
