import React, { useRef, useState } from "react";
import classnames from "classnames";
import Icon from "@/components/Icon";
import { isChild } from "@/utils/isChild";

interface IProps {
  className?: string;
}

const TableItemDropdown: React.FC<React.PropsWithChildren<IProps>> = ({
  children,
  className
}) => {
  const dropdownRef = useRef<HTMLDivElement>(null);

  const [opened, setOpened] = useState(false);

  const handleClick = () => {
    setOpened(true);

    const handleClose = (e: any) => {
      if (!isChild(e.target as any, dropdownRef.current as any)) {
        setOpened(false);

        window.removeEventListener("mousedown", handleClose);
      }
    };

    window.addEventListener("mousedown", handleClose);
  };

  return (
    <div ref={dropdownRef} className="relative">
      <div
        className="text-[#464A54] flex gap-2 items-center"
        onClick={handleClick}
      >
        <Icon className="w-3 h-3 text-inherit" src="/images/icons/cog.svg" />

        <Icon
          className="w-3 h-3 text-inherit"
          src="/images/icons/chevron-down.svg"
        />
      </div>

      {opened && (
        <div className={classnames("absolute bg-[#fff] z-10 bottom-[-4px] right-0 translate-y-full drop-shadow-2xl rounded-b", className)}>
          {children}
        </div>
      )}
    </div>
  );
};

export default TableItemDropdown;
