"use client";

import { useEffect, type ReactNode } from "react";
import { cn } from "@/lib/utils";
import { XIcon } from "@/components/dashboard-icons";

type ModalSize = "sm" | "md" | "lg" | "xl" | "full";

type ModalProps = {
  open: boolean;
  onClose: () => void;
  size?: ModalSize;
  children: ReactNode;
};

const sizeClasses: Record<ModalSize, string> = {
  sm: "max-w-md",
  md: "max-w-3xl",
  lg: "max-w-4xl",
  xl: "max-w-5xl",
  full: "max-w-7xl",
};

export function Modal({ open, onClose, size = "md", children }: ModalProps) {
  useEffect(() => {
    if (!open) return;

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") onClose();
    };

    document.addEventListener("keydown", onKeyDown);
    document.body.style.overflow = "hidden";

    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <>
      <div className="modal-overlay fixed inset-0 z-50 flex items-center justify-center bg-slate-950/55 p-4 backdrop-blur-sm">
        <button
          type="button"
          aria-label="Close modal"
          className="absolute inset-0 cursor-default"
          onClick={onClose}
        />

        <div className={cn("modal-content relative z-10 w-full overflow-hidden rounded-2xl border border-border/80 bg-card shadow-[0_30px_100px_rgba(15,23,42,0.25)]", sizeClasses[size])}>
          <button
            type="button"
            aria-label="Close"
            onClick={onClose}
            className="absolute right-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full border border-border/60 bg-background text-muted-foreground shadow-sm transition-colors hover:bg-accent hover:text-foreground"
          >
            <XIcon className="h-4 w-4" />
          </button>
          {children}
        </div>
      </div>

      <style>{`
        .modal-overlay {
          animation: modal-fade-in 0.15s ease-out;
        }
        .modal-content {
          animation: modal-scale-in 0.2s cubic-bezier(0.16, 1, 0.3, 1);
        }
        @keyframes modal-fade-in {
          from { opacity: 0; }
          to { opacity: 1; }
        }
        @keyframes modal-scale-in {
          from {
            opacity: 0;
            transform: scale(0.92) translateY(12px);
          }
          to {
            opacity: 1;
            transform: scale(1) translateY(0);
          }
        }
      `}</style>
    </>
  );
}
