import React, { useState } from 'react';
import classNames from 'classnames/bind';
import CustomIcon from 'components/items/CustomIcon';
import { NavLink } from 'react-router-dom';
import { config } from 'config/general';
import TextItem from 'components/items/TextItem';
import styleIdentifiers from './nav.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type NavProps = StateProps & DispatchProps & OwnProps;

const Nav = (props: NavProps) => {
  const { navigation, className, profile, accountResource } = props;
  const [nav, setNav] = useState(navigation);

  const toggle = (item: Record<string, any>) => {
    item.closed = !item.closed;
    setNav(nav.slice());
  };

  const renderContent = (item: Record<string, any>) => (
    <React.Fragment>
      {item.icon && <CustomIcon className={styles('icon')} icon={item.icon} />}
      <TextItem path={item.title} replace={accountResource} />
    </React.Fragment>
  );

  const renderItem = (item: Record<string, any>, index: number) => {
    if (item.accountType) {
      let found = false;

      const options = config.accountOptions;

      const profileType = profile && profile[options.typeField];

      const allowedTypes = Array.isArray(item.accountType) ? item.accountType : [item.accountType];

      const userTypes = Array.isArray(profileType) ? profileType : [profileType];

      for (let i = 0; i < allowedTypes.length; i++) {
        const type = allowedTypes[i];

        for (let j = 0; j < userTypes.length; j++) {
          const userType = userTypes[j];

          if (type === userType) found = true;
        }
      }

      if (!found) return false;
    }

    if (profile && profile.types && !profile.types.includes('admin') && item.admin) return false;

    if (item.links) {
      return (
        <div key={index} className={styles('group')}>
          <div className={styles('item')} onClick={() => toggle(item)}>
            {renderContent(item)}
          </div>
          {!item.closed && <div className={styles('items')}>{item.links.map(renderItem)}</div>}
        </div>
      );
    }

    if (item.link) {
      return (
        <NavLink
          className={styles('item')}
          key={item.link || index}
          to={item.link}
          activeClassName={styles('state-active')}
          isActive={(match, location) => {
            return location?.pathname?.indexOf(item.link) >= 0;
          }}
        >
          {renderContent(item)}
        </NavLink>
      );
    }
    return (
      <div key={index} className={styles('category')}>
        {renderContent(item)}
      </div>
    );
  };

  if (!nav) return false;

  return <div className={styles('Nav', className)}>{nav.map(renderItem)}</div>;
};

export default Nav;
