"use client";

import { ImageUpIcon } from "lucide-react";
import { useId, useRef, useState, type ReactNode } from "react";

import { imageFilesFrom } from "@/features/media/upload-client";
import { IMAGE_ACCEPT } from "@/lib/media/constants";
import { cn } from "@/lib/utils";

/**
 * Click, drag-and-drop or keyboard target for image files. Renders a native
 * file input, so it works with screen readers and without a mouse.
 */
export function Dropzone({
  onFiles,
  multiple = false,
  disabled = false,
  className,
  children,
  hint,
}: {
  onFiles: (files: File[]) => void;
  multiple?: boolean;
  disabled?: boolean;
  className?: string;
  /** Replaces the default prompt. */
  children?: ReactNode;
  hint?: ReactNode;
}) {
  const inputId = useId();
  const inputRef = useRef<HTMLInputElement>(null);
  const [dragging, setDragging] = useState(false);
  const depth = useRef(0);

  const accept = (files: File[]) => {
    if (disabled || files.length === 0) return;
    onFiles(multiple ? files : files.slice(0, 1));
  };

  return (
    <div
      onDragEnter={(event) => {
        event.preventDefault();
        depth.current += 1;
        setDragging(true);
      }}
      onDragOver={(event) => event.preventDefault()}
      onDragLeave={() => {
        depth.current -= 1;
        if (depth.current <= 0) setDragging(false);
      }}
      onDrop={(event) => {
        event.preventDefault();
        depth.current = 0;
        setDragging(false);
        accept(imageFilesFrom(event.dataTransfer.files));
      }}
      className={cn(
        "relative flex flex-col items-center justify-center gap-2 rounded-xl border border-dashed border-input bg-muted/40 px-4 py-8 text-center transition-colors",
        "focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/30",
        dragging && "border-primary bg-accent",
        disabled
          ? "opacity-60"
          : "cursor-pointer hover:border-primary/50 hover:bg-accent/50",
        className,
      )}
      onClick={() => !disabled && inputRef.current?.click()}
    >
      <input
        ref={inputRef}
        id={inputId}
        type="file"
        accept={IMAGE_ACCEPT}
        multiple={multiple}
        disabled={disabled}
        className="sr-only"
        onClick={(event) => event.stopPropagation()}
        onChange={(event) => {
          accept(Array.from(event.target.files ?? []));
          event.target.value = "";
        }}
      />
      {children ?? (
        <>
          <span className="grid size-10 place-items-center rounded-full bg-background text-primary shadow-soft">
            <ImageUpIcon className="size-5" />
          </span>
          <label htmlFor={inputId} className="cursor-pointer text-sm">
            <span className="font-medium text-primary">Click to upload</span>{" "}
            <span className="text-muted-foreground">or drag and drop</span>
          </label>
          {hint && <p className="text-xs text-muted-foreground">{hint}</p>}
        </>
      )}
    </div>
  );
}
