"use client";

import { useState } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import styles from "./ConfirmDialog.module.css";

interface ConfirmDialogProps {
  open: boolean;
  title: string;
  description?: string;
  confirmLabel?: string;
  cancelLabel?: string;
  danger?: boolean;
  onConfirm: () => unknown;
  onCancel: () => void;
}

export default function ConfirmDialog({
  open,
  title,
  description,
  confirmLabel = "Confirmer",
  cancelLabel = "Annuler",
  danger = false,
  onConfirm,
  onCancel,
}: ConfirmDialogProps) {
  const [loading, setLoading] = useState(false);

  const handleConfirm = async () => {
    setLoading(true);
    try {
      await onConfirm();
    } finally {
      setLoading(false);
    }
  };

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

  return createPortal(
    <>
      <div className={styles.overlay} onClick={() => !loading && onCancel()} />
      <div className={styles.wrapper}>
        <div className={styles.dialog}>
          <button type="button" className={styles.btnFermer} onClick={onCancel} disabled={loading} aria-label="Fermer">
            <X size={16} />
          </button>
          <h2 className={styles.title}>{title}</h2>
          {description && <p className={styles.description}>{description}</p>}
          <div className={styles.actions}>
            <button type="button" className={styles.btnCancel} onClick={onCancel} disabled={loading}>
              {cancelLabel}
            </button>
            <button
              type="button"
              className={`${styles.btnConfirm} ${danger ? styles.btnConfirmDanger : ""}`}
              onClick={handleConfirm}
              disabled={loading}
            >
              {loading ? <span className={styles.spinner} /> : confirmLabel}
            </button>
          </div>
        </div>
      </div>
    </>,
    document.body,
  );
}
