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

import { FONT_FAMILY } from "./font-family.constants";

export const FontFamilySelector = ({
  value,
  onSelect,
}: {
  value?: any;
  onSelect: (t: string) => void;
}) => {
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  const selected = FONT_FAMILY.find((f) => f.label === 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 z-1 rounded-lg",
          {
            "opacity-0 pointer-events-none": !open,
          }
        )}
      >
        <div className="bg-dark-600 rounded-lg shadow grid grid-cols-1 overflow-auto h-[300px]">
          {FONT_FAMILY.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.label,
                "text-dark-100 text-opacity-80 hover:bg-dark-500":
                  value !== font.label,
              })}
              onClick={() => onSelect(font.label)}
            >
              {font.label}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};
