import { useState } from "react";
import { ISort } from "../../types/sortType";
import CheckIcon from "../icons/CheckIcon";
import ChevronDownIcon from "../icons/ChevronDownIcon";

interface SortButtonProps {
  sortList: ISort[];
  onClick: (id: string) => void;
}

const SortButton = ({ sortList, onClick }: SortButtonProps) => {
  const [isSelected, setIsSelected] = useState(false);

  const handleOnClick = () => {
    setIsSelected((prev) => !prev);
  };

  return (
    <div className="relative">
      <button
        className="text-[#00BED7] text-m leading-5 flex gap-2 items-center"
        onClick={handleOnClick}
      >
        Sort by{" "}
        <div>
          {sortList.find((sort) => sort.isSelected)?.title.toLocaleLowerCase()}{" "}
        </div>
        <div
          className={`transition-all duration-300 ease-in-out ${
            isSelected ? "rotate-180" : "rotate-0"
          }`}
        >
          <ChevronDownIcon />
        </div>
      </button>
      <div
        className={`absolute z-20 flex flex-col bg-white p-2 text-[#0D1922] rounded-lg w-full shadow-lg transition-opacity duration-300 ease-in-out ${
          isSelected ? "opacity-100" : "opacity-0 pointer-events-none hidden"
        }`}
      >
        {sortList.map((sort) => (
          <button
            onClick={() => onClick(sort.id)}
            key={sort.id}
            className="hover:bg-[#F3F3F2] py-2 pl-3 rounded-lg transition-all duration-300 ease-in-out text-left flex items-center gap-2"
          >
            {sort.isSelected && (
              <div className="text-[#00BED7]">
                <CheckIcon />
              </div>
            )}
            {sort.title}
          </button>
        ))}
      </div>
    </div>
  );
};

export default SortButton;
