"use client";

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

export interface DrawerProps {
  isOpen: boolean;
  onClose: () => void;
  title?: string;
  description?: string;
  children: React.ReactNode;
  footer?: React.ReactNode;
  side?: "left" | "right";
  width?: "sm" | "md" | "lg";
  className?: string;
}

export const Drawer: React.FC<DrawerProps> = ({
  isOpen,
  onClose,
  title,
  description,
  children,
  footer,
  side = "right",
  width = "md",
  className,
}) => {
  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 {
      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 widthStyles = {
    sm: "max-w-xs",
    md: "max-w-sm sm:max-w-md",
    lg: "max-w-lg",
  };

  const sideStyles = {
    left: "left-0",
    right: "right-0",
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      onClick={(e) => {
        if (e.target === e.currentTarget) {
          onClose();
        }
      }}
      className="fixed inset-0 z-50 overflow-hidden cursor-default"
    >
      {/* Backdrop */}
      <div
        onClick={onClose}
        aria-hidden="true"
        className="fixed inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity -z-10"
      />

      <div
        onClick={(e) => e.stopPropagation()}
        className={cn(
          "fixed inset-y-0 flex max-w-full z-10",
          sideStyles[side]
        )}
      >
        <div
          className={cn(
            "w-screen bg-white shadow-modal flex flex-col h-full",
            widthStyles[width],
            className
          )}
        >
          {/* Header */}
          <div className="flex items-start justify-between p-4 sm:p-5 border-b border-brand-border">
            <div className="space-y-1">
              {title && (
                <h3 className="text-base sm:text-lg font-bold text-brand-text">
                  {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"
              aria-label="Tutup panel"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Content */}
          <div className="flex-1 overflow-y-auto p-4 sm:p-5">{children}</div>

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