import React, { useEffect, useRef, useState } from "react";
import './avatars.css';
import Profile from '../../../assets/images/user-7.jpg';
import Iconsvg from '../../Ui/Icon/Icon'


type Props = {
    name: string,
    designation: string,
    size? : 'default' | 'small' | 'medium' | 'large',
    borderRadius?: string
}

const Avatars = (props:Props) => {
    const {name, designation, size, borderRadius } = props;
    const style = {
        borderRadius: borderRadius ? borderRadius : '0'
    }
    const [show, setShow] = useState<boolean>(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const showMenu = () => {
        setShow(!show)
    };

    useEffect(() => {
        const pageClickEvent = (e:any) => {
            if (dropdownRef.current !== null && !dropdownRef.current.contains(e.target)) {
                setShow(!show);
              }
        };
        if (show) {
            window.addEventListener('click', pageClickEvent);
        }
      return () => {    
        window.removeEventListener('click', pageClickEvent);
      }
    }, [show])
    

    return (
        <>
            <div className={`avatars-dropdown ${size ? `avatar-${size}`: ''}`} >
                <div className={`avatars`} onClick={showMenu}>
                    <button type="button" className="ava-button">
                        <span className="ava-area">
                            <img style={style} src={Profile} className="profile-image" alt="pofile" />
                            <span className="ava-text">
                                <span className="ava-name">{name}</span>
                                <span className="dropdown-icon"><Iconsvg name="dropDown" /></span>
                                <span className="ava-des">{designation}</span>
                            </span>
                        </span>
                    </button>
                </div>
                <div ref={dropdownRef} className={`dropdown-menu dropdown-menu-end ${show ? 'show' : ''}`}>
                    <div className="dropdown-header">Welcome</div>
                    <ul>
                        <li className="dropdown-item">My Account</li>
                        <li className="dropdown-item">Settings</li>
                        <li className="dropdown-item">Lock Screen</li>
                        <li className="dropdown-item">Log out</li>
                    </ul>
                </div>
            </div>
        </>
    );
};

export default Avatars;