import React, { useEffect, useRef } from 'react';
import styled from 'styled-components';
import { useOutsideClick } from '../hooks/useOutsideAlerter';
import ModalPortal from './Abstractions/ModalPortal';

interface IListMenuOption {
  id: string;
  text: string;
}

export interface IRelativeMenuProps {
  options: IListMenuOption[];
  onSelected: (selectedOptionId: string) => void;
  fontSize?: number;
  onOutsideClick?: () => void;
  pos: { x: number; y: number };
}

export const RelativeListMenu: React.FC<IRelativeMenuProps> = ({
  options,
  onSelected,
  onOutsideClick,
  fontSize = 0.8,
  pos,
}) => {
  const ref = useRef(null);

  useOutsideClick(ref, 'relative-context-menu');

  useEffect(() => {
    document.addEventListener('clickOutside', event => {
      const e = event as CustomEvent;

      if (e.detail.id === 'relative-context-menu') {
        if (onOutsideClick) {
          onOutsideClick();
        }
      }
    });

    return () => {
      document.removeEventListener('clickOutside', _e => {});
    };
  }, []);

  return (
    <ModalPortal>
      <Container fontSize={fontSize} ref={ref} {...pos}>
        <ul className="rpgui-list-imp" style={{ overflow: 'hidden' }}>
          {options.map((params, index) => (
            <ListElement
              key={params?.id || index}
              onPointerDown={() => {
                onSelected(params?.id);
              }}
            >
              {params?.text || 'No text'}
            </ListElement>
          ))}
        </ul>
      </Container>
    </ModalPortal>
  );
};

interface IContainerProps {
  fontSize?: number;
  x: number;
  y: number;
}

const Container = styled.div<IContainerProps>`
  position: absolute;
  top: ${props => props.y}px;
  left: ${props => props.x}px;

  display: flex;
  flex-direction: column;
  width: max-content;
  justify-content: start;
  align-items: flex-start;

  li {
    font-size: ${props => props.fontSize}em;
  }
`;

const ListElement = styled.li`
  margin-right: 0.5rem;
`;
