import { IconDefinition } from "@fortawesome/fontawesome-common-types";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from "react";
import withRouter, { RouterProps } from "../../../utils/withRouter";

interface LeftMenuSubMenuProps extends RouterProps {
  icon: IconDefinition;
  label: string;
  openMenu?: LOCLeftMenuSubMenu;
  children: (false | JSX.Element)[];
  onClick?: (menuItem: LOCLeftMenuSubMenu) => void;
}

interface LeftMenuSubMenuState {}

class LOCLeftMenuSubMenu extends React.Component<
  LeftMenuSubMenuProps,
  LeftMenuSubMenuState
> {
  state = {};

  handleClick = (): void => {
    const { onClick } = this.props;

    if (onClick !== undefined) onClick(this);
  };

  isChildSelected = (child: JSX.Element): boolean => {
    const { to } = child.props;
    const { pathname } = this.props.router.location;
    let isSelected: boolean = false;
    if (to === "/" ? pathname === to : pathname.toLowerCase().startsWith(to)) {
      isSelected = true;
    }

    return isSelected;
  };

  isAnyChildSelected = (): boolean => {
    const { children } = this.props;

    let childIsSelected = false;
    children.forEach((child) => {
      if (child === false) {
        return;
      }

      if (this.isChildSelected(child)) childIsSelected = true;
    });

    return childIsSelected;
  };

  render() {
    const { icon, label, openMenu } = this.props;

    const selected = this === openMenu || this.isAnyChildSelected();

    let className = "LeftMenuItem leftMenuSubMenu";

    if (selected) {
      className += " leftMenuSubMenuOpen";
    }

    return (
      <div className={className} onClick={this.handleClick}>
        <FontAwesomeIcon className="leftMenuItemIcon" icon={icon} />
        <div className="leftMenuItemLabel">{label}</div>
      </div>
    );
  }
}

const LeftMenuSubMenu = withRouter(LOCLeftMenuSubMenu);
export default LeftMenuSubMenu;
export { LOCLeftMenuSubMenu };
