"use client";

import cx from "classnames";
import React, { ReactNode } from "react";
import { useStatic } from "@/utils/hooks";
import { Bar, BarItem } from "../Bar";
import { IconButton } from "../Button";
import { ButtonProps } from "../Button/Button";
import DropdownButtonStatic from "./Dropdown.static";
import { DropdownToggleButton } from "./DropdownToggleButton";

export const CLASS_ROOT = "dropdown";

export type DropdownButtonProps = {
  className?: string;
  children?: ReactNode;
  iconName?: string;
  type?: ButtonProps["type"];
};

export type DropdownProps = {
  button: DropdownButtonProps;
  children: ReactNode;
  hasFocusTrap?: boolean;
  hasSpacing?: boolean;
  id: string;
  isInteractive?: boolean;
  placement?: "left" | "center" | "right";
  className?: string;
  [key: string]: any;
};

const placements: Record<"left" | "center" | "right", string> = {
  left: "bottom-start",
  center: "bottom",
  right: "bottom-end",
};

const Dropdown: React.FC<DropdownProps> = ({
  button,
  className,
  hasFocusTrap = false,
  hasSpacing = true,
  children,
  id,
  isInteractive = false,
  placement = "left",
  ...other
}) => {
  const [dropdownRef] = useStatic(DropdownButtonStatic);

  const classes = cx(
    "dropdown",
    {
      [`${CLASS_ROOT}-spacing`]: hasSpacing,
    },
    className,
  );

  return (
    <>
      {button && (
        <DropdownToggleButton
          {...button}
          id={id}
          className={button.className || ""}
        />
      )}
      <div
        ref={dropdownRef}
        id={`dropdown-${id}`}
        className={classes}
        data-dropdown=""
        data-dropdown-placement={placements[placement]}
        data-dropdown-interactive={isInteractive}
        data-dropdown-focus-trap={hasFocusTrap}
        {...other}
      >
        {hasFocusTrap && (
          <Bar className={"mb-small justify-content-end"}>
            <BarItem>
              <IconButton
                iconName="delete"
                isSquare
                size="small"
                className={`${CLASS_ROOT}__close`}
                aria-label="Zatvoriť"
                id={`close-btn-${id}`}
                data-toggle={JSON.stringify([
                  {
                    target: `#btn-${id}`,
                    action: "click",
                  },
                ])}
              />
            </BarItem>
          </Bar>
        )}
        {children}
      </div>
    </>
  );
};

Dropdown.displayName = "Dropdown";

export { Dropdown };
