import { useEffect, useRef, type ReactNode } from 'react';
import { cn } from '../lib/cn';

export type DrawerSide = 'left' | 'right' | 'top' | 'bottom';

export interface DrawerProps {
  open: boolean;
  onClose: () => void;
  title?: ReactNode;
  children?: ReactNode;
  footer?: ReactNode;
  side?: DrawerSide;
  size?: string;
  className?: string;
}

const sideClasses: Record<DrawerSide, { panel: string; enter: string; exit: string; size: string }> = {
  right: {
    panel: 'inset-y-0 right-0 h-full',
    enter: 'translate-x-0',
    exit: 'translate-x-full',
    size: 'w-full max-w-md',
  },
  left: {
    panel: 'inset-y-0 left-0 h-full',
    enter: 'translate-x-0',
    exit: '-translate-x-full',
    size: 'w-full max-w-md',
  },
  top: {
    panel: 'inset-x-0 top-0 w-full',
    enter: 'translate-y-0',
    exit: '-translate-y-full',
    size: 'h-auto max-h-[80vh]',
  },
  bottom: {
    panel: 'inset-x-0 bottom-0 w-full',
    enter: 'translate-y-0',
    exit: 'translate-y-full',
    size: 'h-auto max-h-[80vh]',
  },
};

export function Drawer({
  open,
  onClose,
  title,
  children,
  footer,
  side = 'right',
  size,
  className,
}: DrawerProps) {
  const ref = useRef<HTMLDivElement>(null);
  const cfg = sideClasses[side];

  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') onClose();
    };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    const focusable = ref.current?.querySelector<HTMLElement>(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    );
    focusable?.focus();

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

  if (!open) return null;

  return (
    <div className="fixed inset-0 z-50" onClick={onClose}>
      <div className="absolute inset-0 bg-text/40 backdrop-blur-sm transition-opacity duration-base" />
      <div
        ref={ref}
        role="dialog"
        aria-modal="true"
        aria-labelledby={title ? 'drawer-title' : undefined}
        onClick={(e) => e.stopPropagation()}
        className={cn(
          'absolute flex flex-col bg-surface border-border shadow-2xl transition-transform duration-base ease-out',
          cfg.panel,
          size || cfg.size,
          (side === 'left' || side === 'right') ? 'border-l border-r' : 'border-t border-b',
          cfg.enter,
          className
        )}
      >
        {title && (
          <div className="flex items-center justify-between px-6 py-4 border-b border-border shrink-0">
            <h2 id="drawer-title" className="text-lg font-semibold text-text">{title}</h2>
            <button
              type="button"
              onClick={onClose}
              aria-label="Close"
              className="inline-flex h-8 w-8 items-center justify-center rounded-md text-text-3 hover:text-text hover:bg-surface-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary-ring"
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="18" y1="6" x2="6" y2="18" />
                <line x1="6" y1="6" x2="18" y2="18" />
              </svg>
            </button>
          </div>
        )}
        <div className="flex-1 overflow-y-auto px-6 py-5 text-text-2">{children}</div>
        {footer && (
          <div className="flex items-center justify-end gap-2 px-6 py-4 border-t border-border bg-surface-2 shrink-0">
            {footer}
          </div>
        )}
      </div>
    </div>
  );
}
