import { useRef, useState } from "react";
import classNames from "classnames";
import { useClickAway } from "react-use";

import { useUser } from "utils/auth";
import { FormattedMessage } from "react-intl";

export const UserMenu = ({ children }: any) => {
  const { logout, user } = useUser();

  const [open, setOpen] = useState(false);
  const ref = useRef(null);

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

  return (
    <div ref={ref} className="relative">
      <div className="cursor-pointer" onClick={() => setOpen(!open)}>
        {children}
      </div>
      <div
        className={classNames(
          "absolute bottom-0 right-0 transform translate-y-full max-w-[200px] pt-4 w-[200px] transition-all duration-100",
          {
            "opacity-0 pointer-events-none translate-y-3/4": !open,
            "translate-y-full": open,
          }
        )}
      >
        <div className="bg-dark-500 rounded-lg w-full shadow-lg">
          <div className="px-4 pt-4 pb-3 text-white font-title font-bold text-sm">
            {user.username}#{user.discriminator}
          </div>
          <div className="px-2 pb-4">
            <div
              className="flex items-center justify-start gap-3 bg-[#f02727] text-white group transition-all duration-100 p-2 rounded-md cursor-pointer"
              onClick={() => logout()}
            >
              <svg
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
                strokeWidth="1.5"
                stroke="currentColor"
                className="w-6 h-6 text-white transition-all duration-100"
              >
                <path
                  strokeLinecap="round"
                  strokeLinejoin="round"
                  d="M15.75 9V5.25A2.25 2.25 0 0013.5 3h-6a2.25 2.25 0 00-2.25 2.25v13.5A2.25 2.25 0 007.5 21h6a2.25 2.25 0 002.25-2.25V15M12 9l-3 3m0 0l3 3m-3-3h12.75"
                />
              </svg>
              <p className="font-semibold tracking-wider text-sm">
                <FormattedMessage id="navigation.menus.logOut" />
              </p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};
