import React, { forwardRef, useCallback, useState } from 'react';
import Popover from '@material-ui/core/Popover';
import Box from '@material-ui/core/Box';
import { PopoverProps } from './types';
import { useStyles } from './styles';

export const PopupFocus = forwardRef<HTMLElement, PopoverProps>((props, ref) => {
  const { trigger, content, anchorOrigin, transformOrigin, mountNode } = props;
  const classes = useStyles();
  const [open, setOpen] = useState<boolean>(false);
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const [focused, setFocused] = useState<boolean>(false);

  const handleFocus = useCallback(
    (event: React.FocusEvent<HTMLButtonElement>) => {
      if (focused) {
        setFocused(false);
      } else {
        setAnchorEl(event.currentTarget);
        setOpen(true);
        setFocused(true);
      }
    },
    [focused],
  );

  const handleClose = useCallback(() => {
    setAnchorEl(null);
    setOpen(false);
  }, []);

  return (
    <>
      {React.cloneElement(trigger, { onFocus: handleFocus, ref })}
      <Popover
        open={open}
        anchorEl={anchorEl}
        onClose={handleClose}
        container={mountNode}
        anchorOrigin={anchorOrigin}
        transformOrigin={transformOrigin}>
        <Box className={classes.box}>{content}</Box>
      </Popover>
    </>
  );
});
