import { useClickAway } from "@uidotdev/usehooks";
import clsx from "clsx";
import { useEffect, useRef, useState } from "react";
import ChevronDownIcon from "../icons/ChevronDownIcon";

interface SelectProps {
  options: string[];
  onSelect: (value: string) => void;
  className?: string;
  defaultOption?: string;
}

function Select({
  options,
  onSelect,
  className,
  defaultOption: defaultValue = "",
}: SelectProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedOption, setSelectedOption] = useState(defaultValue);

  const ref = useClickAway<HTMLDivElement>(() => setIsOpen(false));

  const dropDownRef = useRef<HTMLDivElement>(null);

  useEffect(() => setSelectedOption(defaultValue), [defaultValue]);

  useEffect(() => onSelect(selectedOption), [onSelect, selectedOption]);

  function handleScroll() {
    if (!dropDownRef.current) return;
    dropDownRef.current.style.maxHeight = `calc(100vh - ${
      dropDownRef.current?.getBoundingClientRect().y
    }px - 0.278vw)`;
  }

  useEffect(() => {
    handleScroll();
    document.addEventListener("scroll", handleScroll);

    return () => document.removeEventListener("scroll", handleScroll);
  }, [isOpen]);

  return (
    <div
      ref={ref}
      className={clsx(
        "bg-[#F3F3F3] 2xl:p-[1.111vw] p-4 flex justify-between items-center 2xl:gap-[0.556vw] gap-2 relative select-none cursor-pointer",
        isOpen
          ? "2xl:rounded-t-[1.111vw] rounded-t-2xl"
          : "2xl:rounded-[1.111vw] rounded-2xl",
        className
      )}
      onClick={() => setIsOpen(!isOpen)}
    >
      <p className="text-m">{selectedOption}</p>
      <div
        className={clsx(
          "2xl:size-[1.111vw] size-4 text-[#7D7D7D]",
          isOpen && "rotate-180"
        )}
      >
        <ChevronDownIcon />
      </div>
      {isOpen && (
        <div
          className="absolute left-0 top-full z-10 w-full 2xl:rounded-b-[1.111vw] rounded-b-2xlo overflow-hidden"
          ref={dropDownRef}
        >
          {options.map((option) => (
            <p
              key={option}
              className="bg-[#F3F3F3] 2xl:p-[1.111vw] p-4 text-m hover:bg-[#f0f0f0] transition-colors"
            >
              {option}
            </p>
          ))}
        </div>
      )}
    </div>
  );
}

export default Select;
