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

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

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

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

  const dropDownRef = useRef<HTMLDivElement>(null);

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

  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("relative", className)}>
      {/* Select Button */}
      <button
        className={clsx(
          "w-full bg-[#F3F3F3] 2xl:py-[0.972vw] py-3.5 2xl:px-[1.111vw] px-4 flex justify-between items-center 2xl:gap-[0.833vw] gap-3 select-none cursor-pointer transition-colors",
          "2xl:rounded-[1.111vw] rounded-2xl",
          "hover:bg-[#F0F0F0]",
          isOpen && "ring-1 ring-[#7B60F3]"
        )}
        onClick={() => setIsOpen(!isOpen)}
      >
        <p className="text-m text-ellipsis line-clamp-1 text-left">
          {selectedOption || "Не выбрано"}
        </p>
        <div
          className={clsx(
            "2xl:size-[1.389vw] size-5 text-[#7D7D7D] shrink-0 transition-transform",
            isOpen && "rotate-180"
          )}
        >
          <ChevronDownIcon />
        </div>
      </button>

      {/* Dropdown Menu */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            ref={dropDownRef}
            className="absolute left-0 2xl:top-[calc(100%+0.556vw)] top-[calc(100%+8px)] z-10 w-full bg-white 2xl:rounded-[1.111vw] rounded-2xl shadow-[0px_4px_40px_0px_rgba(0,0,0,0.05),0px_2px_2px_0px_rgba(0,0,0,0.05)] 2xl:p-[0.833vw] p-3 2xl:space-y-[0.278vw] space-y-1 overflow-auto"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            {options.map((option) => (
              <button
                key={option}
                className={clsx(
                  "w-full flex items-center 2xl:gap-[0.278vw] gap-1 2xl:p-[0.833vw] p-3 2xl:rounded-[0.556vw] rounded-lg text-left transition-colors hover:bg-[#F3F3F3]"
                )}
                onClick={() => {
                  setSelectedOption(option);
                  setIsOpen(false);
                }}
              >
                <div
                  className={clsx(
                    "2xl:size-[1.111vw] size-4 shrink-0 text-[#7B60F3]",
                    option !== selectedOption && "opacity-0"
                  )}
                >
                  <CheckIcon />
                </div>
                <span className="text-s">{option}</span>
              </button>
            ))}
          </motion.div>
        )}
      </AnimatePresence>
    </div>
  );
}

export default Select;
