import React, { useState, useEffect, useRef } from 'react';

import styles from './ProfileMenuButton.module.css';
import { getAcronym } from '../../utils/strings';

const ProfileMenuButton = ({ username, className, onLogout, onInvite }) => {
  const [isInviteCopied, setIsInviteCopied] = useState(false);
  const acronym = getAcronym(username).slice(0, 2);
  const timeoutIdRef = useRef(null);

  async function handleInvite() {
    try {
      await onInvite();
      setIsInviteCopied(true);
      timeoutIdRef.current = setTimeout(() => {
        setIsInviteCopied(false);
      }, 2000);
    } catch (err) {
      console.log(err);
    }
  }

  useEffect(() => {
    // Cleanup the timeout if the component unmounts before the timeout is complete
    return () => clearTimeout(timeoutIdRef.current);
  }, []);

  return (
    <div className={`${styles.root} ${className}`}>
      <div className={styles.menuContainer}>
        <div className={styles.menuLabel}>{acronym}</div>
        <div className={styles.menuButtons}>
          <button onClick={handleInvite} className={styles.invite}>
            {!isInviteCopied ? (
              'Copy Invite'
            ) : (
              <>
                <span className={styles.checkmark}>✓ </span>Copied!
              </>
            )}
          </button>
          <button onClick={onLogout}>Logout</button>
        </div>
      </div>
    </div>
  );
};

export default ProfileMenuButton;
