import { useRef, useState } from "react";
import CloseIcon from "./icons/CloseIcon";
import HandOnIcon from "./icons/HandOnIcon";
import Button from "./ui/Button";
import MoreIcon from "./icons/MoreIcon";
import { useOnClickOutside } from "usehooks-ts";
import Tooltip from "./Tooltip";
import IUser from "../types/IUser";

interface UserProps {
  user: IUser;
  onTransferControl: (userId: string) => void;
  onKickUser: (userId: string) => void;
  className?: string;
  tooltip?: boolean;
}

function User({
  user,
  onTransferControl,
  onKickUser,
  className,
  tooltip = false,
}: UserProps) {
  const [isShowMore, setIsShowMore] = useState(false);
  const moreRef = useRef(null);

  function handleClickOutside() {
    setIsShowMore(false);
  }

  useOnClickOutside(moreRef, handleClickOutside);

  function handleClickTransferControl() {
    onTransferControl(user.id);
    setIsShowMore(false);
  }

  function handleClickKickUser() {
    onKickUser(user.id);
    setIsShowMore(false);
  }

  return (
    <div ref={moreRef} className="relative">
      <Button
        variant="tertiary"
        icon={<MoreIcon />}
        onlyIcon
        onClick={() => setIsShowMore((prev) => !prev)}
        className="group relative"
      >
        {tooltip && <Tooltip text="Действия" />}
      </Button>

      {isShowMore && (
        <div
          className={`absolute top-[calc(100%+18px)] bg-white rounded-lg py-2 z-10 shadow ${className}`}
        >
          <button
            className="flex items-center gap-2 px-4 py-1 hover:bg-[#E6ECF2] transition-colors w-full"
            onClick={handleClickTransferControl}
          >
            <span className="text-[#77828C]">
              <HandOnIcon />
            </span>
            <span className="text-sm whitespace-nowrap">
              Передать управление
            </span>
          </button>
          <button
            className="flex items-center gap-2 px-4 py-1 hover:bg-[#E6ECF2] transition-colors w-full"
            onClick={handleClickKickUser}
          >
            <span className="text-[#EB5757]">
              <CloseIcon />
            </span>
            <span className="text-sm">Исключить</span>
          </button>
        </div>
      )}
    </div>
  );
}

export default User;
