import { useRef, useState } from "react";
import ChevronDown from "./icons/ChevronDown";
import CheckIcon from "./icons/CheckIcon";
import { useOnClickOutside } from "usehooks-ts";

interface CalcSelectProps {
  label: string;
  placeholder: string;
  defaultOption: string;
  options: string[];
  handleSelect: (option: string) => void;
}

function CalcSelect({
  label,
  placeholder,
  defaultOption = "",
  options,
  handleSelect,
}: CalcSelectProps) {
  const [selectedOption, setSelectedOption] = useState<string>(defaultOption);
  const [isShow, setIsShow] = useState<boolean>(false);
  const ref = useRef<HTMLDivElement>(null);
  useOnClickOutside(ref, () => setIsShow(false));

  function handleClick(option: string) {
    setSelectedOption(option);
    setIsShow(false);
    handleSelect(option);
  }

  return (
    <div ref={ref} className="relative z-10">
      <div
        className={`border ${
          isShow ? "border-[#798FFF]" : "border-[#3D425C]"
        } 2xl:p-6 2xl:pr-8 p-4 pr-6 flex flex-col justify-center h-24 cursor-pointer transition-colors`}
        onClick={() => setIsShow((prev) => !prev)}
      >
        <div className="relative h-full cursor-pointer">
          <div className="flex flex-col justify-between h-full ">
            <label className="2xl:text-base text-sm opacity-50 font-gilroy font-medium leading-none cursor-pointer">
              {label}
            </label>
            <input
              readOnly
              type="text"
              placeholder={placeholder}
              className="2xl:text-base text-sm w-full bg-transparent outline-none cursor-pointer"
              value={selectedOption}
            />
          </div>
        </div>
        <span className="absolute self-end">
          <ChevronDown />
        </span>
      </div>
      {isShow && (
        <div className="absolute max-h-[411.5px] overflow-y-auto flex flex-col border border-[#3D425C] w-full py-2 backdrop-blur-[14px] bg-[#14161F] bg-opacity-50">
          {options.map((option, index) => (
            <button
              key={index}
              className="2xl:pl-6 2xl:pr-8 2xl:py-3 pl-4 pr-6 py-2 2xl:text-base text-sm hover:bg-white hover:bg-opacity-10 transition-colors w-full text-left flex justify-between"
              onClick={() => handleClick(option)}
            >
              <span>{option}</span>
              {option === selectedOption && <CheckIcon />}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

export default CalcSelect;
