import type { JSX } from "solid-js";
import { Show, createEffect, onCleanup, splitProps } from "solid-js";
import { createDismiss } from "../../utilities/dismiss/create-dismiss";
import { useDatePickerContext } from "./date-picker-context";

export interface DatePickerContentProps extends JSX.HTMLAttributes<HTMLDivElement> {
  children?: JSX.Element;
}

/** Floating calendar panel. Renders only when open; dismissed by outside click or Escape. */
export function DatePickerContent(props: DatePickerContentProps): JSX.Element {
  const [local, rest] = splitProps(props, ["children", "style"]);
  const ctx = useDatePickerContext();

  const dismiss = createDismiss({
    getContainer: () => ctx.contentRef(),
    onDismiss: () => ctx.setOpen(false),
  });

  createEffect(() => {
    if (ctx.isOpen()) {
      dismiss.attach();
    } else {
      dismiss.detach();
    }
    onCleanup(() => dismiss.detach());
  });

  return (
    <Show when={ctx.isOpen()}>
      <div
        ref={(el) => ctx.setContentRef(el)}
        id={ctx.contentId()}
        role="dialog"
        aria-modal={false}
        data-state="open"
        style={
          typeof local.style === "string"
            ? `${styleToString(ctx.floatingStyle())};${local.style}`
            : { ...ctx.floatingStyle(), ...(local.style as JSX.CSSProperties) }
        }
        {...rest}
      >
        {local.children}
      </div>
    </Show>
  );
}

function styleToString(style: JSX.CSSProperties): string {
  return Object.entries(style).map(([k, v]) => `${k}:${v}`).join(";");
}
