import React, { useEffect, useRef } from 'react';
import { createPortal } from 'react-dom';
import { X } from 'lucide-react';
import { cn } from '@/lib/cn';

/** Tabbable element selector for the focus trap. */
const FOCUSABLE =
  'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';

export function Dialog({
  open,
  onClose,
  title,
  description,
  children,
  footer,
  size = 'md',
}: {
  open: boolean;
  onClose: () => void;
  title?: string;
  description?: string;
  children: React.ReactNode;
  footer?: React.ReactNode;
  size?: 'sm' | 'md' | 'lg';
}) {
  const panelRef = useRef<HTMLDivElement>(null);
  // Stable id so aria-labelledby can point at the title heading.
  const titleId = useRef(`backreload-dlg-${Math.random().toString(36).slice(2, 9)}`).current;

  // Effect: while open — close on Escape, lock scroll, trap Tab focus inside
  // the panel, and restore focus to whatever element opened the dialog when
  // it closes. (Hooks must run unconditionally, so this sits before the
  // `open` early-return.)
  useEffect(() => {
    if (!open) return;
    const previouslyFocused = document.activeElement as HTMLElement | null;

    // Lock background scroll.
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';

    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        onClose();
        return;
      }
      // Tab focus trap: keep Tab/Shift+Tab cycling inside the panel.
      if (e.key !== 'Tab' || !panelRef.current) return;
      const focusable = Array.from(
        panelRef.current.querySelectorAll<HTMLElement>(FOCUSABLE),
      ).filter((el) => !el.hasAttribute('disabled'));
      if (focusable.length === 0) {
        e.preventDefault();
        return;
      }
      const first = focusable[0];
      const last  = focusable[focusable.length - 1];
      const active = document.activeElement as HTMLElement | null;
      if (e.shiftKey && active === first) {
        e.preventDefault();
        last.focus();
      } else if (!e.shiftKey && active === last) {
        e.preventDefault();
        first.focus();
      }
    };
    document.addEventListener('keydown', onKey);

    // Move focus into the dialog on mount — pick the first focusable element,
    // or the panel itself if nothing inside is interactive.
    queueMicrotask(() => {
      if (!panelRef.current) return;
      const first = panelRef.current.querySelector<HTMLElement>(FOCUSABLE);
      (first ?? panelRef.current).focus();
    });

    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = prevOverflow;
      // Hand focus back to the element that opened the dialog so keyboard
      // users don't get dumped at the top of the page.
      previouslyFocused?.focus?.();
    };
  }, [open, onClose]);

  if (!open) return null;
  const widths = { sm: 'max-w-sm', md: 'max-w-lg', lg: 'max-w-2xl' };

  const content = (
    <div className="fixed inset-0 z-[100000] flex items-center justify-center p-4">
      <div className="absolute inset-0 bg-ink-900/30 backdrop-blur-sm" onClick={onClose} />
      <div
        ref={panelRef}
        role="dialog"
        aria-modal="true"
        aria-labelledby={title ? titleId : undefined}
        tabIndex={-1}
        className={cn('relative bg-white rounded-2xl shadow-pop w-full focus:outline-none', widths[size])}
      >
        <div className="px-5 pt-5 pb-3 flex items-start justify-between">
          <div>
            {title && <h3 id={titleId} className="text-base font-semibold text-ink-900">{title}</h3>}
            {description && <p className="text-xs text-ink-500 mt-1">{description}</p>}
          </div>
          <button onClick={onClose} aria-label="Close dialog" className="text-ink-400 hover:text-ink-700 p-1 -m-1 rounded">
            <X className="h-4 w-4" />
          </button>
        </div>
        <div className="px-5 py-3">{children}</div>
        {footer && <div className="px-5 py-3 border-t border-ink-100 flex justify-end gap-2">{footer}</div>}
      </div>
    </div>
  );

  // Portal to the plugin root element. Rendering the modal deep inside the app
  // layout traps its `position: fixed` overlay inside whatever stacking context
  // a wrapper div happens to create — which is why the backdrop stopped short
  // of the WP admin bar (#wpadminbar, z-index 99999). As a *direct child* of
  // #backreload-root (which creates no stacking context of its own) the overlay
  // escapes to the viewport, so z-index 100000 reliably covers the admin bar.
  // We portal into #backreload-root rather than <body> so our scoped Tailwind
  // styles still apply.
  const host = document.getElementById('backreload-root');
  return host ? createPortal(content, host) : content;
}
