import React, { useEffect, useRef, useState } from 'react';
import Iconsvg from '../../Ui/Icon/Icon';
import './drop-down.css';


type Props = {
    label: string,
    clickable: boolean,
    size? : 'default' | 'small' | 'medium' | 'large',
    variant?: 'default' |'primary' | 'secondary',
    placement: 'top' | 'bottom',
    iconName:any,
}

const menuOptions = [
    {
        label: 'Action',
        value: 'action'
    },
    {
        label: 'Anther action',
        link: 'anotherAction'
    },
    {
        label: 'Somthing else here',
        link: 'somthingElseHere'
    }
]

const DropDown = (props:Props) => {
    const {label, size, clickable, iconName, variant, placement } = props;
    const [show, setShow] = useState<boolean>(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const showMenu = () => {
        setShow(!show)
    };

    const onMouseOver = () => {
        setShow(!show)
    }

    const onMouseLeave = () => {
        setShow(false)
    }

    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={`menu-dropdown ${size ? `menu-${size}`: ''} ${variant ?  `menu-background-${variant}` : ''}`} >
                {/* Click Drpdown */}
                {clickable && 
                    <button type="button" className="menu-button" onClick={showMenu}>
                    {label} <span className="dropdown-icon"><Iconsvg name="dropDown" /></span>
                    </button>
                }
                {/* Hover Dropdown */}
                {!clickable && 
                    <button type="button" className="menu-button" onMouseOver={onMouseOver} onMouseLeave={onMouseLeave}>
                        {label} <span className="dropdown-icon"><Iconsvg name={iconName} /></span>
                    </button>
                }
                {/* Menu Options */}
                <div ref={dropdownRef} className={`dropdown-menu dropdown-menu-end ${show ? 'show' : ''} ${placement ? `drop-postion-${placement}` : ''}`}>
                    <div className="dropdown-header">Dropdown header</div>
                    <ul>
                        {
                            menuOptions && menuOptions.map((item, index) => (
                                <li onClick={showMenu} className='dropdown-item' key={index}>{item.label}</li>
                            ))
                        }
                    </ul>
                </div>
            </div>
        </>
    );
}

export default DropDown;