"use client";

import { useRef, useState, useEffect } from "react";
import { ImagePlus, Loader, FileText, X } from "lucide-react";
import { urlAsset } from "@/lib/utils/assets";
import styles from "./FileInput.module.css";

interface FileInputProps {
  label?: string;
  /** Chemin relatif renvoyé par le backend (ex: "/uploads/produits/xxx.jpg") ou null. */
  value?: string | null;
  accept?: string;
  hint?: string;
  loading?: boolean;
  onChange?: (file: File) => void;
  onClear?: () => void;
}

export default function FileInput({
  label,
  value,
  accept = "image/jpeg,image/png,image/webp",
  hint = "JPG, PNG ou WEBP",
  loading = false,
  onChange,
  onClear,
}: FileInputProps) {
  const ref = useRef<HTMLInputElement>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);
  const [isPdf, setIsPdf] = useState(false);
  const [fileName, setFileName] = useState<string | null>(null);

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

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    if (previewUrl?.startsWith("blob:")) URL.revokeObjectURL(previewUrl);
    const url = URL.createObjectURL(file);
    setPreviewUrl(url);
    setIsPdf(file.type === "application/pdf");
    setFileName(file.name);
    onChange?.(file);
    e.target.value = "";
  };

  const handleClear = (e: React.MouseEvent) => {
    e.stopPropagation();
    if (previewUrl?.startsWith("blob:")) URL.revokeObjectURL(previewUrl);
    setPreviewUrl(null);
    setIsPdf(false);
    setFileName(null);
    onClear?.();
  };

  const displaySrc = previewUrl ?? (value ? urlAsset(value) : null);
  const hasPreview = Boolean(displaySrc);

  return (
    <div className={styles.wrap}>
      {label && <span className={styles.label}>{label}</span>}

      <div
        className={`${styles.zone} ${loading ? styles.zoneLoading : ""}`}
        onClick={() => !loading && ref.current?.click()}
      >
        {loading ? (
          <div className={styles.placeholder}>
            <Loader size={20} strokeWidth={1.8} className={styles.spinner} />
          </div>
        ) : hasPreview ? (
          isPdf || value?.endsWith(".pdf") ? (
            <div className={styles.pdfThumb}>
              <FileText size={28} className={styles.pdfIcon} />
            </div>
          ) : (
            // eslint-disable-next-line @next/next/no-img-element
            <img src={displaySrc ?? undefined} alt="" className={styles.preview} />
          )
        ) : (
          <div className={styles.placeholder}>
            <ImagePlus size={20} strokeWidth={1.5} />
          </div>
        )}

        <div className={styles.info}>
          <div className={styles.infoText}>
            {loading ? "Chargement..." : fileName ? fileName : hasPreview ? "Cliquer pour changer" : "Cliquer pour ajouter"}
          </div>
          <div className={styles.infoHint}>{hint}</div>
        </div>

        {hasPreview && !loading && (
          <button type="button" className={styles.clearBtn} onClick={handleClear} title="Supprimer">
            <X size={14} />
          </button>
        )}
      </div>

      <input
        ref={ref}
        type="file"
        accept={accept}
        aria-label={label ?? "Choisir un fichier"}
        className={styles.input}
        onChange={handleChange}
        disabled={loading}
      />
    </div>
  );
}
