import React, { FC, forwardRef, useRef, useState, useImperativeHandle} from 'react';
import { v4 as uuidv4 } from 'uuid';
import { styled } from '@mui/material/styles';
import Tooltip, { TooltipProps, tooltipClasses } from '@mui/material/Tooltip';
import { AreaProps, MenuProps, AreaMenuProps } from './AreaMenu.types';
import { ClickAwayListener } from '@mui/material';

const HtmlTooltip = styled(({ className, ...props }: TooltipProps) => (
	<Tooltip {...props} classes={{ popper: className }} />
  ))(({ theme }) => ({
	[`& .${tooltipClasses.tooltip}`]: {
	  backgroundColor: 'white',
	  color: 'rgba(0, 0, 0, 0.87)',
	  maxWidth: "100%",
	  border: '1px solid #dadde9',
	},
}));


export const Area: FC<AreaProps> = ({children}) => {
	return children
}

export const Menu: FC<MenuProps> = ({children}) => {
	return children
}

const idArea = uuidv4()
const idMenu = uuidv4()

export const AreaMenu: FC<AreaMenuProps> = forwardRef(({
	id = "AreaMenu",
	menuPlacement= "bottom",
	children,
	isDisabled,
	clickAway = true,
}, ref) => {

	const [isOpen, setIsOpen] = useState<boolean>(false)

	useImperativeHandle(ref, () => ({
		close: () => { setIsOpen(false) }
	}))
	
	let area, menu

	children.map((child: JSX.Element)  => {
		if(child?.type?.displayName === "Area"){
			area = child
		}
		if(child?.type?.displayName === "Menu"){
			menu = child
		}
	})
	
	return (
		<HtmlTooltip
			data-testid='areaMenu_id'
			id={id}
			open={isOpen}
			placement={menuPlacement}
			title={
				<ClickAwayListener onClickAway={() => {clickAway && setIsOpen(false)}}>
					<div key={idMenu}>
						{menu || children[1]}
					</div>
				</ClickAwayListener>
			}
		>
			<div key={idArea} style={{width: "100%"}} onClick={() => !isDisabled && setIsOpen(!isOpen)}>
				{area || children[0]}
			</div>
		</HtmlTooltip>
	);
});

export default AreaMenu;

