import { JSX, ParentComponent, Show, createSignal, splitProps, onCleanup, onMount } from "solid-js";
import { Portal } from "solid-js/web";

interface DialogProps {
  open: boolean;
  onClose: () => void;
  children: JSX.Element;
}

export const Dialog: ParentComponent<DialogProps> = (props) => {
  const [local] = splitProps(props, ["open", "onClose", "children"]);
  let overlayRef: HTMLDivElement | undefined;

  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === "Escape" && local.open) {
      local.onClose();
    }
  };

  const handleOverlayClick = (e: MouseEvent) => {
    if (e.target === overlayRef) {
      local.onClose();
    }
  };

  onMount(() => {
    document.addEventListener("keydown", handleKeyDown);
    onCleanup(() => {
      document.removeEventListener("keydown", handleKeyDown);
    });
  });

  // Lock body scroll when dialog is open
  const originalOverflow = document.body.style.overflow;
  if (local.open) {
    document.body.style.overflow = "hidden";
  }
  onCleanup(() => {
    if (!local.open) {
      document.body.style.overflow = originalOverflow;
    }
  });

  return (
    <Portal>
      <Show when={local.open}>
        <div
          ref={overlayRef}
          class={[
            "fixed inset-0 z-50",
            "bg-ink/40 backdrop-blur-sm",
            "animate-fade-in",
            "flex items-center justify-center p-4",
          ].join(" ")}
          onClick={handleOverlayClick}
          role="dialog"
          aria-modal="true"
        >
          <div
            class={[
              "relative w-full max-w-lg",
              "bg-canvas rounded-panel shadow-2xl",
              "animate-scale-in",
              "border border-border",
              "max-h-[90vh] overflow-y-auto",
            ].join(" ")}
            onClick={(e) => e.stopPropagation()}
          >
            {local.children}
          </div>
        </div>
      </Show>
    </Portal>
  );
};

// Dialog Header
export const DialogHeader: ParentComponent<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
  const [local, rest] = splitProps(props, ["children", "class"]);
  return (
    <div class={["p-6 pb-4", local.class || ""].join(" ")} {...rest}>
      {local.children}
    </div>
  );
};

// Dialog Title
export const DialogTitle: ParentComponent<JSX.HTMLAttributes<HTMLHeadingElement>> = (props) => {
  const [local, rest] = splitProps(props, ["children", "class"]);
  return (
    <h2
      class={[
        "font-display text-xl font-semibold text-ink",
        local.class || "",
      ].join(" ")}
      {...rest}
    >
      {local.children}
    </h2>
  );
};

// Dialog Description
export const DialogDescription: ParentComponent<JSX.HTMLAttributes<HTMLParagraphElement>> = (props) => {
  const [local, rest] = splitProps(props, ["children", "class"]);
  return (
    <p
      class={[
        "text-sm text-ink-muted mt-1",
        local.class || "",
      ].join(" ")}
      {...rest}
    >
      {local.children}
    </p>
  );
};

// Dialog Content
export const DialogContent: ParentComponent<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
  const [local, rest] = splitProps(props, ["children", "class"]);
  return (
    <div class={["p-6", local.class || ""].join(" ")} {...rest}>
      {local.children}
    </div>
  );
};

// Dialog Footer
export const DialogFooter: ParentComponent<JSX.HTMLAttributes<HTMLDivElement>> = (props) => {
  const [local, rest] = splitProps(props, ["children", "class"]);
  return (
    <div
      class={[
        "p-6 pt-4 border-t border-border",
        "flex flex-col-reverse sm:flex-row sm:justify-end gap-3",
        local.class || "",
      ].join(" ")}
      {...rest}
    >
      {local.children}
    </div>
  );
};

// Dialog Close Button
interface DialogCloseButtonProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
  onClose: () => void;
}

export const DialogCloseButton: ParentComponent<DialogCloseButtonProps> = (props) => {
  const [local, rest] = splitProps(props, ["onClose", "children", "class"]);
  return (
    <button
      class={[
        "absolute top-4 right-4",
        "p-2 rounded-lg",
        "text-ink-muted hover:text-ink hover:bg-canvas-subtle",
        "transition-colors duration-200",
        local.class || "",
      ].join(" ")}
      onClick={local.onClose}
      aria-label="Close dialog"
      {...rest}
    >
      <svg
        xmlns="http://www.w3.org/2000/svg"
        width="20"
        height="20"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="2"
        stroke-linecap="round"
        stroke-linejoin="round"
      >
        <path d="M18 6 6 18" />
        <path d="m6 6 12 12" />
      </svg>
    </button>
  );
};

// Hook for dialog state
export function useDialog(initialOpen = false) {
  const [isOpen, setIsOpen] = createSignal(initialOpen);

  return {
    isOpen,
    open: () => setIsOpen(true),
    close: () => setIsOpen(false),
    toggle: () => setIsOpen((prev) => !prev),
  };
}
