/* eslint-disable react-hooks/exhaustive-deps */
import { useEffect, useState } from "react";
import { useClickAway } from "@uidotdev/usehooks";
import ArrowDownIcon from "./icons/ArrowDownIcon";
import Button from "./Button";

interface Props {
  options: string[]; // ["StroyProject"]
  onChange: (option: string | undefined) => void;
}

export default function Select({ options, onChange }: Props) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedOption, setSelectedOption] = useState<string | undefined>();
  const ref = useClickAway<HTMLDivElement>(() => setIsOpen(false));

  function handleClickOption(option: string) {
    setSelectedOption(option);
    onChange(option);
    setIsOpen(false);
  }

  useEffect(() => {
    if (selectedOption && !options.includes(selectedOption)) {
      setSelectedOption(undefined);
    }
  }, [options]);

  return (
    <div
      ref={ref}
      className="relative outline-black/10 outline w-[13.889vw] rounded-[0.833vw]"
    >
      <Button
        variant="secondary"
        className="px-[0.833vw] py-[0.417vw] !justify-between w-full"
        onClick={(e) => {
          e.preventDefault();
          setIsOpen(!isOpen);
        }}
      >
        <p className="text-[0.972vw] leading-[115%]">
          {selectedOption || "Выберите из списка"}
        </p>
        <div
          className={`w-[1.389vw] transition-transform h-[1.389vw]${
            isOpen ? "rotate-180" : ""
          }`}
        >
          <ArrowDownIcon />
        </div>
      </Button>
      {isOpen && (
        <div className="absolute top-full w-full rounded-[0.833vw] outline outline-black/10 z-1">
          {options.map((option) => (
            <Button
              key={option}
              variant="secondary"
              className="px-[0.833vw] py-[0.417vw] !justify-start w-full !first:rounded-t-[0.556vw] !last:rounded-b-[0.556vw]"
              onClick={() => handleClickOption(option)}
            >
              <div className="flex gap-[0.278vw] items-center">
                <p className="text-[0.972vw] leading-[115%]">{option}</p>
              </div>
            </Button>
          ))}
        </div>
      )}
    </div>
  );
}
