import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import classNames from 'clsx';
import Image from 'next/image';

import { Tooltip } from '@/mui/components';

import logoText from '@/assets/img/logo-text.png';

import styles from './index.module.scss';

const useOutsideClick = (ref, callback) => {
  const fn = (e) => {
    try {
      if (e.type === 'blur' && document.activeElement?.tagName === 'IFRAME') {
        callback();
      } else if (ref.current && e.target && !ref.current.contains(e.target)) {
        callback();
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      callback();
    }
  };

  useEffect(() => {
    window.addEventListener('click', fn);
    window.addEventListener('blur', fn);

    return () => {
      window.removeEventListener('click', fn);
      window.removeEventListener('blur', fn);
    };
  });
};

function ItemMenu({ content = '', title = '', icon = '', ...props }) {
  const ref = useRef(null);
  const [active, setActive] = useState(null);

  useOutsideClick(ref, () => {
    setActive(false);
  });

  useEffect(() => {
    if (props.isListHide) {
      setActive(false);
    }
  }, [props.isListHide]);

  const handleClick = () => {
    setActive((state) => !state);
  };

  const renderList = (listProps = {}) => {
    if (props.list?.[0] && typeof props.list[0] === 'function') {
      return props.list[0](listProps);
    }

    return props.list;
  };

  return (
    <div ref={ref} className={classNames(props.className)}>
      <div
        className={classNames(styles.Content, {
          [styles.Content___active]: active,
        })}
        tabIndex={-1}
        onKeyUp={null}
        role="button"
        onClick={handleClick}
      >
        {icon && (
          <Tooltip title={title} placement="bottom">
            <div className={styles.ContentIcon}>{icon}</div>
          </Tooltip>
        )}

        <span>{content}</span>
      </div>
      <div
        className={classNames(styles.List, {
          [styles.List___active]: active,
        })}
      >
        <div className={styles.ImgWrapper}>
          <Image src={logoText} alt="Logo" width={74} height={12} />
        </div>
        {renderList({
          isMenuActive: active,
        })}
      </div>
    </div>
  );
}

ItemMenu.propTypes = {
  className: PropTypes.string.isRequired,
  content: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
  title: PropTypes.string,
  icon: PropTypes.node,
  list: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.node, PropTypes.func])).isRequired,
  isListHide: PropTypes.bool.isRequired,
};

export default ItemMenu;
