"use client";

import React, { useEffect } from "react";
import { createPortal } from "react-dom";
import { X } from "lucide-react";
import { AnimatePresence, motion } from "framer-motion";

interface ConfirmModalProps {
  isOpen: boolean;
  onClose: () => void;
  onConfirm: () => void;
  title?: string;
  description?: React.ReactNode;
  confirmLabel?: string;
  cancelLabel?: string;
  /** Styles the confirm button for destructive actions (red). */
  destructive?: boolean;
  /** Disables the confirm button and shows the busy label, e.g. while a request is in flight. */
  loading?: boolean;
  loadingLabel?: string;
}

const ConfirmModal: React.FC<ConfirmModalProps> = ({
  isOpen,
  onClose,
  onConfirm,
  title = "Are you sure?",
  description,
  confirmLabel = "Confirm",
  cancelLabel = "Cancel",
  destructive = false,
  loading = false,
  loadingLabel,
}) => {
  useEffect(() => {
    if (!isOpen) return;

    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape" && !loading) onClose();
    };

    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    document.addEventListener("keydown", handleKeyDown);

    return () => {
      document.body.style.overflow = originalOverflow;
      document.removeEventListener("keydown", handleKeyDown);
    };
  }, [isOpen, loading, onClose]);

  if (typeof document === "undefined") return null;

  return createPortal(
    <AnimatePresence>
      {isOpen && (
        <motion.div
          role="dialog"
          aria-modal="true"
          aria-labelledby="confirm-modal-title"
          onClick={() => !loading && onClose()}
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2 }}
          className="fixed inset-0 z-[100] flex items-center justify-center bg-black/50 px-4 backdrop-blur-sm"
        >
          <motion.div
            onClick={(e) => e.stopPropagation()}
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            exit={{ opacity: 0, scale: 0.95 }}
            transition={{ duration: 0.2 }}
            className="relative w-full max-w-[440px] bg-white rounded-[19px] shadow-xl"
          >
            {/* Close button */}
            <button
              onClick={onClose}
              disabled={loading}
              aria-label="Close"
              className="absolute top-[11px] right-[12px] w-[29px] h-[29px] bg-white rounded-full border border-[#DBDBDB] flex items-center justify-center hover:bg-neutral-50 transition-colors cursor-pointer z-10 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <X size={16} className="text-[#737373]" strokeWidth={1.5} />
            </button>

            {/* Content */}
            <div className="flex flex-col items-center gap-[14px] px-[25px] pt-[35px] pb-[32px]">
              <div className="w-full flex flex-col items-center gap-1.5">
                <h2
                  id="confirm-modal-title"
                  className="self-stretch text-center font-sans text-[24px] font-bold leading-[34px] tracking-[-0.02em] text-black"
                >
                  {title}
                </h2>
                {description && (
                  <p className="max-w-[360px] text-center font-serif text-[16px] leading-[24px] tracking-[-0.01em] text-neutral-500">
                    {description}
                  </p>
                )}
              </div>

              {/* Actions */}
              <div className="flex items-center justify-center gap-3 mt-1">
                <button
                  onClick={onClose}
                  disabled={loading}
                  className="h-11 px-[23px] py-[7px] rounded-[37px] border border-[#DBDBDB] bg-white flex items-center justify-center font-sans text-[16px] font-semibold leading-[120%] tracking-[-0.01em] text-[#393939] hover:bg-neutral-50 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {cancelLabel}
                </button>
                <button
                  onClick={onConfirm}
                  disabled={loading}
                  className={`h-11 px-[23px] py-[7px] rounded-[37px] shadow-[0px_1px_2px_0px_rgba(0,0,0,0.03)] flex items-center justify-center font-sans text-[16px] font-semibold leading-[120%] tracking-[-0.01em] text-white transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed ${
                    destructive
                      ? "bg-red-500 hover:bg-red-600"
                      : "bg-[#08A1EE] hover:bg-[#0791d4]"
                  }`}
                >
                  {loading ? (loadingLabel ?? confirmLabel) : confirmLabel}
                </button>
              </div>
            </div>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>,
    document.body,
  );
};

export default ConfirmModal;
