import { createSignal, type JSXElement } from "solid-js";
import { CaretDown } from "@icons/CaretDown";

type Props = {
  label: string;
  pop?: boolean;
  children: HTMLElement[] | JSXElement[] | Element[];
  justify?: "left" | "right" | "center";
  className?: string;
};

const Dropdown = ({
  label,
  pop,
  justify = "center",
  children,
  className,
}: Props) => {
  // @ts-ignore
  const [button, setButton] = createSignal<HTMLButtonElement>();
  const [open, setOpen] = createSignal(false);

  window.addEventListener("click", (e) => {
    if (e.target !== button()) setOpen(false);
  });

  return (
    <div class={`relative flex flex-col ${className ?? ""}`}>
      <button
        type="button"
        ref={(e) => setButton(e)}
        class="flex items-center gap-x-1 leading-6"
        aria-expanded="false"
        onclick={(e) => {
          button()?.setAttribute("clicked", `${!open()}`);
          // setOpen(false);
          setOpen(!open());
          // e.stopPropagation();
        }}
      >
        {label}
        <span
          class="transition-all duration-500"
          classList={{ "rotate-180": open() }}
        >
          <CaretDown className="h-5 w-5 flex-none text-gray-600" />
        </span>
      </button>

      <div
        class={`z-10 transition-all duration-[900ms] ${
          pop ? "absolute rounded-3xl ring-gray-900/5" : ""
        } ${
          open()
            ? (justify === "left"
                ? "!left-0 translate-x-[50%]"
                : justify === "right"
                ? "!right-0 translate-x-[-50%]"
                : "!left-0") +
              (pop ? "mt-3 ring-1 top-full shadow-lg bg-white" : "")
            : "h-0 scale-50 opacity-0 overflow-hidden"
        }`}
      >
        <div class={`p-1 px-2 lg:p-4 flex flex-col gap-1 `}>{children}</div>
      </div>
    </div>
  );
};
export default Dropdown;
