"use client";

import { useEffect, useId } from "react";

type AdminDrawerProps = {
  open: boolean;
  title: string;
  subtitle?: string;
  onClose: () => void;
  children: React.ReactNode;
  widthClassName?: string;
};

export function AdminDrawer({
  open,
  title,
  subtitle,
  onClose,
  children,
  widthClassName = "max-w-xl",
}: AdminDrawerProps) {
  const titleId = useId();

  useEffect(() => {
    if (!open) return;

    function onKey(event: KeyboardEvent) {
      if (event.key === "Escape") onClose();
    }

    document.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      document.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [open, onClose]);

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-[60] flex justify-end bg-black/40" role="presentation" onClick={onClose}>
      <aside
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        className={`flex h-full w-full ${widthClassName} flex-col border-l border-[#e4d9cb] bg-[#faf7f2] shadow-2xl`}
        onClick={(event) => event.stopPropagation()}
      >
        <header className="flex items-start justify-between gap-3 border-b border-[#e4d9cb] px-4 py-4 sm:px-5">
          <div className="min-w-0">
            <h2 id={titleId} className="truncate text-lg font-semibold text-[#1a2228]">
              {title}
            </h2>
            {subtitle ? <p className="mt-1 text-sm text-[#5c5248]">{subtitle}</p> : null}
          </div>
          <button
            type="button"
            onClick={onClose}
            className="inline-flex min-h-11 min-w-11 items-center justify-center rounded-xl border border-[#d7cbb9] text-[15px] font-semibold text-[#3d342c]"
            aria-label="Close details"
          >
            ✕
          </button>
        </header>
        <div className="min-h-0 flex-1 overflow-y-auto px-4 py-4 sm:px-5">{children}</div>
      </aside>
    </div>
  );
}
