import { useState, useRef, useEffect } from "react";

type Option = {
  value: string;
  label: string;
};

type SelectProps = {
  options: Option[];
  placeholder?: string;
  value: string;
  onChange: (value: string) => void;
  dropDirection?: "up" | "down" | "auto";
  className?: string;
};

export default function Select({ options, placeholder = "Select option...", value, onChange, dropDirection = "down", className }: SelectProps) {
  const [open, setOpen] = useState(false);
  const ref = useRef<HTMLDivElement>(null);
  const [direction, setDirection] = useState<"up" | "down">("down");
  const buttonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (open && dropDirection === "auto" && buttonRef.current) {
      requestAnimationFrame(() => {
        const rect = buttonRef.current!.getBoundingClientRect();
        const dropdownHeight = 200;
        const spaceBelow = window.innerHeight - rect.bottom;
        const spaceAbove = rect.top;
  
        if (spaceBelow < dropdownHeight && spaceAbove > dropdownHeight) {
          setDirection("up");
        } else {
          setDirection("down");
        }
      });
    }
  }, [open, dropDirection]);  

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        setOpen(false);
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const selectedOption = options.find(o => o.value === value);

  return (
    <div ref={ref} className="relative">
      <button
        ref={buttonRef} 
        type="button"
        onClick={() => setOpen(prev => !prev)}
        className={`relative py-2 px-4 pe-10 w-full cursor-pointer bg-white border border-gray-200 rounded-lg text-start text-sm text-gray-800 hover:border-gray-300 focus:border-blue-500 focus:ring focus:ring-blue-500/50 dark:bg-neutral-900 dark:border-neutral-700 dark:text-neutral-400 ${className}`}
      >
        {selectedOption ? selectedOption.label : placeholder}
        <span className="absolute top-1/2 right-3 -translate-y-1/2 pointer-events-none">
          <svg className="w-4 h-4 text-gray-500 dark:text-neutral-500" fill="none" stroke="currentColor" strokeWidth="2.5" viewBox="0 0 24 24">
            <path d="M7 10l5 5 5-5" />
          </svg>
        </span>
      </button>
      {open && (
        <ul
          className={`absolute z-50 ${
            (dropDirection === "auto" ? direction : dropDirection) === "up"
              ? "bottom-full mb-2"
              : "top-full mt-2"
          } w-full bg-white border border-gray-200 rounded-lg shadow-lg max-h-60 overflow-y-auto text-sm dark:bg-neutral-900 dark:border-neutral-700`}
        >
          {options.map((option) => (
            <li
              key={option.value}
              onClick={() => {
                onChange(option.value);
                setOpen(false);
              }}
              className={`py-2 px-4 cursor-pointer hover:bg-gray-100 dark:hover:bg-neutral-800 dark:text-neutral-200 ${
                option.value === value ? "bg-gray-100 dark:bg-neutral-800 font-medium" : ""
              }`}
            >
              {option.label}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}