"use client";

import React, { useEffect } from "react";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";

export interface ModalProps {
  isOpen: boolean;
  onClose: () => void;
  title?: string;
  description?: string;
  children: React.ReactNode;
  footer?: React.ReactNode;
  maxWidth?: "sm" | "md" | "lg" | "xl" | "2xl" | "max-w-sm" | "max-w-md" | "max-w-lg" | "max-w-xl" | "max-w-2xl" | string;
  className?: string;
  hideOnPrint?: boolean;
}

export const Modal: React.FC<ModalProps> = ({
  isOpen,
  onClose,
  title,
  description,
  children,
  footer,
  maxWidth = "md",
  className,
  hideOnPrint = true,
}) => {
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if ((e.key === "Escape" || e.key === "Esc") && isOpen) {
        e.preventDefault();
        e.stopPropagation();
        onClose();
      }
    };

    if (isOpen) {
      document.body.style.overflow = "hidden";
      window.addEventListener("keydown", handleKeyDown);
    } else {
      // Pastikan body scroll dikembalikan normal jika tidak ada dialog lain yang aktif
      const otherDialogs = document.querySelectorAll('[role="dialog"]');
      if (otherDialogs.length <= 1) {
        document.body.style.overflow = "";
      }
    }

    return () => {
      window.removeEventListener("keydown", handleKeyDown);
      const otherDialogs = document.querySelectorAll('[role="dialog"]');
      if (otherDialogs.length <= 1) {
        document.body.style.overflow = "";
      }
    };
  }, [isOpen, onClose]);

  if (!isOpen) return null;

  const maxWidthStyles: Record<string, string> = {
    sm: "max-w-sm",
    md: "max-w-md",
    lg: "max-w-lg",
    xl: "max-w-xl",
    "2xl": "max-w-2xl",
  };

  const resolvedMaxWidth = maxWidth.startsWith("max-w-")
    ? maxWidth
    : maxWidthStyles[maxWidth] || "max-w-md";

  return (
    <div
      role="dialog"
      aria-modal="true"
      data-print-hidden={hideOnPrint ? "true" : undefined}
      onClick={(e) => {
        // Klik pada area luar (wrapper padding atau flex gap) langsung menutup modal
        if (e.target === e.currentTarget) {
          onClose();
        }
      }}
      className={cn(
        "fixed inset-0 z-50 flex items-center justify-center p-4 overflow-y-auto cursor-default",
        hideOnPrint
          ? "print:hidden no-print print-hidden"
          : "print:p-0 print:static print:block print:inset-auto print:z-auto print:bg-transparent"
      )}
    >
      {/* Backdrop */}
      <div
        onClick={onClose}
        aria-hidden="true"
        className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity print:hidden -z-10"
      />

      {/* Dialog Body */}
      <div
        onClick={(e) => e.stopPropagation()}
        className={cn(
          "relative w-full bg-white rounded-lg shadow-modal border border-brand-border overflow-hidden z-10 animate-in fade-in zoom-in-95 duration-150 print:border-none print:shadow-none print:rounded-none print:w-full print:max-w-none print:static print:overflow-visible print:p-0 print:m-0",
          resolvedMaxWidth,
          className
        )}
      >
        {/* Header */}
        <div className="flex items-start justify-between p-5 border-b border-brand-border print:hidden">
          <div className="space-y-1">
            {title && (
              <h3 className="text-lg font-bold text-brand-text leading-snug">
                {title}
              </h3>
            )}
            {description && (
              <p className="text-xs text-brand-secondary">{description}</p>
            )}
          </div>
          <button
            onClick={onClose}
            className="p-1 rounded-md text-brand-secondary hover:text-brand-text hover:bg-slate-100 transition-colors print:hidden"
            aria-label="Tutup dialog"
          >
            <X className="w-5 h-5" />
          </button>
        </div>

        {/* Content */}
        <div className="p-5 max-h-[calc(85vh-130px)] overflow-y-auto print:max-h-none print:overflow-visible print:p-0 print:h-auto">
          {children}
        </div>

        {/* Footer */}
        {footer && (
          <div className="flex items-center justify-end gap-2.5 p-4 bg-slate-50 border-t border-brand-border print:hidden">
            {footer}
          </div>
        )}
      </div>
    </div>
  );
};
