import { useRef, useState } from "react";
import { useClickAway } from "react-use";
import classNames from "classnames";
import { ChevronDownIcon } from "@heroicons/react/solid";

import { FONT_WEIGHT } from "./font-weight.constants";

export const FontWeight = ({
  value,
  onSelect,
}: {
  value?: any;
  onSelect: (t: string) => void;
}) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const selected = FONT_WEIGHT.find((f) => f.value === value);

  useClickAway(ref, () => setOpen(false));

  return (
    <div ref={ref} className="relative">
      <div
        className={`text-white font-medium text-sm ${selected?.value} rounded-lg px-3.5 py-3 bg-dark-600 flex items-center justify-between cursor-pointer`}
        onClick={() => setOpen(!open)}
      >
        {selected?.label}
        <ChevronDownIcon className="w-4 text-dark-200" />
      </div>
      <div
        className={classNames(
          "absolute top-0 left-0 w-full transform translate-y-12 pt-1 rounded-lg z-1",
          {
            "opacity-0 pointer-events-none": !open,
          }
        )}
      >
        <div className="bg-dark-600 rounded-lg shadow grid grid-cols-1 overflow-auto h-[300px]">
          {FONT_WEIGHT.map((font, f) => (
            <div
              key={f}
              className={classNames(`p-2.5 cursor-pointer ${font.value}`, {
                "bg-blue text-white hover:bg-blue hover:text-white":
                  value === font.value,
                "text-dark-100 text-opacity-80 hover:bg-dark-400":
                  value !== font.value,
              })}
              onClick={() => onSelect(font.value)}
            >
              {font.label}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
