import React, { useRef } from "react";
import { useState } from "react";
import classNames from "classnames";

export type Props = {
  className?: string;
  selected?: string;
  setSelected: (option: string) => void;
  options: string[];
};

const Dropdown = ({ selected, setSelected, options, className }: Props) => {
  const [isActive, setIsActive] = useState<boolean>(false);

  const dropdownRef = useRef<HTMLDivElement>(null);
  const handleClickOutsideDropdown = (e: any) => {
    if (isActive && !dropdownRef.current?.contains(e.target as Node)) {
      setIsActive(false);
    }
  };
  window.addEventListener("click", handleClickOutsideDropdown);

  return (
    <div className={classNames("", className)} ref={dropdownRef}>
      <div
        className="group  border-gray-200 hover:border-gray-500 p-2 
        select-none rounded 
        flex items-center justify-between"
        onClick={(e) => setIsActive(!isActive)}
      >
        {selected}
        <span
          className="border-r-4 border-l-4 border-t-4 border-b-4 border-r-transparent 
          border-l-transparent border-t-black border-b-transparent  h-0 w-0 mt-1 
          transition-all duration-300

          "
        ></span>
      </div>
      {isActive && (
        <div
          className="float-left mt-1 border border-gray-200 hover:border-gray-500
         rounded"
        >
          {options.map((option) => (
            <div
              className="p-1 hover:bg-gray-200 select-none"
              onClick={(e) => {
                setSelected(option);
                setIsActive(false);
              }}
            >
              {option}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default Dropdown;

//group-active:border-t-transparent group-active:border-b-black group-active:mb-2
