"use client";

import { signOutOfApp } from "@/actions/auth";
import { FC, PropsWithChildren, useCallback, useState } from "react";

export const UserMenu: FC<PropsWithChildren<{ signedIn: boolean }>> = ({
  children,
  signedIn,
}) => {
  const [visible, setVisible] = useState(false);
  const [closing, setClosing] = useState(true);

  const toggle = useCallback(() => {
    setClosing((c) => !c);
    setTimeout(
      () => {
        setVisible((v) => !v);
      },
      visible ? 100 : 0
    );
  }, [visible]);

  return (
    <div
      onClick={signedIn ? toggle : undefined}
      className="relative bg-mixed-200 p-2 rounded-lg cursor-pointer w-[220px]"
    >
      {visible && (
        <div
          data-closing={closing}
          className="absolute bottom-full left-0 right-0 fade-menu"
        >
          <ul className="separated-list w-full">
            <li>
              <a className="block p-2" href="/profile">
                Profile
              </a>
            </li>
            <li>
              <button className="p-2" onClick={() => signOutOfApp()}>
                Sign Out
              </button>
            </li>
          </ul>
        </div>
      )}
      {children}
    </div>
  );
};
