"use client";

import { useState } from "react";
import { createPortal } from "react-dom";
import { X, ZoomIn, ZoomOut, RotateCw, RefreshCw, Download, ExternalLink } from "lucide-react";
import styles from "./ImageViewerModal.module.css";

interface ImageViewerModalProps {
  open: boolean;
  url: string | null;
  title?: string;
  onClose: () => void;
}

export default function ImageViewerModal({ open, url, title = "Aperçu de l'image", onClose }: ImageViewerModalProps) {
  const [scale, setScale] = useState(1);
  const [rotation, setRotation] = useState(0);

  if (!open || !url || typeof document === "undefined") return null;

  const handleReset = () => {
    setScale(1);
    setRotation(0);
  };

  return createPortal(
    <div className={styles.overlay} onClick={onClose}>
      <div className={styles.container} onClick={(e) => e.stopPropagation()}>
        <div className={styles.topBar}>
          <span className={styles.title}>{title}</span>
          <div className={styles.toolbar}>
            <button type="button" onClick={() => setScale((s) => Math.min(s + 0.25, 3))} className={styles.toolBtn} title="Zoom +">
              <ZoomIn size={18} />
            </button>
            <button type="button" onClick={() => setScale((s) => Math.max(s - 0.25, 0.5))} className={styles.toolBtn} title="Zoom -">
              <ZoomOut size={18} />
            </button>
            <button type="button" onClick={() => setRotation((r) => (r + 90) % 360)} className={styles.toolBtn} title="Pivoter">
              <RotateCw size={18} />
            </button>
            <button type="button" onClick={handleReset} className={styles.toolBtn} title="Réinitialiser">
              <RefreshCw size={18} />
            </button>
            <div className={styles.divider} />
            <a href={url} download target="_blank" rel="noreferrer" className={styles.toolBtn} title="Télécharger">
              <Download size={18} />
            </a>
            <a href={url} target="_blank" rel="noreferrer" className={styles.toolBtn} title="Plein écran">
              <ExternalLink size={18} />
            </a>
            <button type="button" onClick={onClose} className={styles.closeBtn} title="Fermer">
              <X size={20} />
            </button>
          </div>
        </div>

        <div className={styles.stage}>
          {/* eslint-disable-next-line @next/next/no-img-element */}
          <img
            src={url}
            alt={title}
            className={styles.image}
            style={{ transform: `scale(${scale}) rotate(${rotation}deg)` }}
          />
        </div>
      </div>
    </div>,
    document.body,
  );
}
