"use client";

import { DragEvent, useCallback, useRef, useState } from "react";
import styles from "./PhotoField.module.css";

type Photo = { id: string; url: string };

type Props = {
  photos: Photo[];
  maxPhotos?: number;
  loading?: boolean;
  apiBaseUrl: string;
  onAdd: (files: File[]) => void;
  onRemove: (photoId: string) => void;
};

export function PhotoField({
  photos,
  maxPhotos = 5,
  loading = false,
  apiBaseUrl,
  onAdd,
  onRemove,
}: Props) {
  const [dragOver, setDragOver] = useState(false);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const canAdd = photos.length < maxPhotos;
  const remaining = maxPhotos - photos.length;

  const handleFiles = useCallback(
    (rawFiles: FileList | File[]) => {
      const accepted = Array.from(rawFiles)
        .filter((f) => f.type.startsWith("image/"))
        .slice(0, remaining);
      if (accepted.length > 0) onAdd(accepted);
    },
    [remaining, onAdd],
  );

  const onDragOver = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    if (canAdd) setDragOver(true);
  };

  const onDragLeave = (e: DragEvent<HTMLDivElement>) => {
    if (!e.currentTarget.contains(e.relatedTarget as Node)) {
      setDragOver(false);
    }
  };

  const onDrop = (e: DragEvent<HTMLDivElement>) => {
    e.preventDefault();
    setDragOver(false);
    if (!canAdd || loading) return;
    handleFiles(e.dataTransfer.files);
  };

  const openPicker = () => {
    if (!canAdd || loading) return;
    fileInputRef.current?.click();
  };

  return (
    <div
      className={`${styles.photoField} ${dragOver && canAdd ? styles.dragOver : ""}`}
      onDragOver={onDragOver}
      onDragLeave={onDragLeave}
      onDrop={onDrop}
    >
      {/* Hidden file input */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/png,image/jpeg,image/webp"
        multiple
        style={{ display: "none" }}
        onChange={(e) => {
          if (e.target.files) handleFiles(e.target.files);
          e.target.value = "";
        }}
      />

      {/* Thumbnails */}
      <div className={styles.photoList}>
        {photos.map((ph) => (
          <div key={ph.id} className={styles.photoItem}>
            {/* eslint-disable-next-line @next/next/no-img-element */}
            <img src={`${apiBaseUrl}${ph.url}`} alt="" />
            <button
              type="button"
              className={styles.photoRemove}
              onClick={() => onRemove(ph.id)}
              disabled={loading}
              aria-label="Supprimer"
            >
              ✕
            </button>
          </div>
        ))}

        {/* Add button */}
        {canAdd && (
          <button
            type="button"
            className={styles.photoAdd}
            disabled={loading}
            onClick={openPicker}
          >
            <span className={styles.plusIcon}>+</span>
            <span className={styles.photoAddLabel}>
              {remaining > 1 ? `${remaining} restantes` : "Photo"}
            </span>
          </button>
        )}
      </div>

      {/* Drop hint */}
      <p className={styles.dropHint}>
        {canAdd
          ? dragOver
            ? "Relâchez pour ajouter"
            : `Glissez-déposez jusqu'à ${remaining} photo${remaining > 1 ? "s" : ""} ici`
          : `Maximum ${maxPhotos} photos atteint`}
      </p>
    </div>
  );
}
