import * as React from 'react';
import classNames from 'classnames/bind';
import CustomDropdown from 'components/enhancers/CustomDropdown';

import { NavLink } from 'react-router-dom';
import { config, viewConfig, headerNav as navigation } from 'config/general';
import { fire } from 'store/utils/firebase';
import CustomIcon from 'components/items/CustomIcon';
import Logo from 'components/items/Logo';
import TextItem from 'components/items/TextItem';
import { IoIosArrowDown } from 'react-icons/io';
import styleIdentifiers from './header.scss';

const styles = classNames.bind(styleIdentifiers);

const UserItem = (props: {}): JSX => {
  const { user, active, close } = props;

  let name = user.firstName;
  if (name && user.lastName) name += ` ${user.lastName}`;

  if (!name) name = user[config.keyAdmin] || user.name || user.email || 'user';

  return (
    <div className={styles('content-drop')} onClick={() => active && close(false)}>
      <div className={styles('info')}>
        {user ? (
          <>
            <div className={styles('name')}>{name}</div>
            <div className={styles('type')}>{user.type || user.pro_type}</div>
          </>
        ) : (
          <div className={styles('name')}>Admin</div>
        )}
      </div>
      <div className={styles('icon', 'circle')}>
        <span>{name.charAt(0)}</span>
      </div>
      <div className={styles('arrow', active && 'active')}>
        <IoIosArrowDown />
      </div>
    </div>
  );
};

const EnhancedDropdown = CustomDropdown(UserItem);

export interface HeaderProps {
  logout: Function;
  history: {};
  paragraphUser: {} | null;
  user: {};
  location: {};
  logoutFirebase: Function;
}

interface HeaderState {}

export default class Header extends React.Component<HeaderProps, HeaderState> {
  logout = (): void => {
    const { logout, logoutFirebase } = this.props;

    if (config.firebase && fire && logoutFirebase) {
      logoutFirebase();
    } else if (logout) logout();
  };

  checkIfNavIsActive = (item: string): boolean => {
    const { location } = this.props;

    return location.pathname.includes(item);
  };

  navRedirect = (item: {}): void => {
    const { paragraphUser } = this.props;

    if (item.to.indexOf('paragraph') >= 0) {
      const isLogged = paragraphUser && paragraphUser.loaded && paragraphUser.data;
      if (!isLogged) {
        return '/paragraph/login';
      }
    }
    return '';
  };

  renderItem = (item: {}, key: number): JSX => {
    const navRedirect = this.navRedirect(item);
    return (
      <NavLink
        to={navRedirect || item.to}
        className={styles('nav-item', this.checkIfNavIsActive(item.link) && 'nav-item-active')}
        key={key}
      >
        {item.icon && item.icon.position === 'left' && (
          <CustomIcon
            className={styles('icon', `icon-${item.icon.position}`)}
            icon={item.icon.name}
          />
        )}
        <div className={styles('text')}>{item.title}</div>
        {item.icon && item.icon.position === 'right' && (
          <CustomIcon
            className={styles('icon', `icon-${item.icon.position}`)}
            icon={item.icon.name}
          />
        )}
      </NavLink>
    );
  };

  selectResource = item => {
    const { selectResource, showSuccess, history } = this.props;

    const options = config.accountOptions;

    const accountResourceOptions = options.accountResourceOptions;

    if (accountResourceOptions.reloadReset) item.forceReload = true;

    selectResource(item);

    if (accountResourceOptions.changeSuccess) {
      showSuccess({
        data: accountResourceOptions.changeSuccess,
      });
    }

    // FORCE RELOAD
    history.push(accountResourceOptions.reloadUrl || '/');
  };

  render(): JSX {
    const { user } = this.props;

    const options = config.accountOptions;

    const accountResourceOptions = options.accountResourceOptions;

    const profile = user && user.profile && user.profile.data;

    const resourceData = user && user.resource && user.resource.data;

    const selectedResource = user && user.selectedResource;

    return (
      <div className={styles('Header', viewConfig.headerColor, config.staging && 'staging')}>
        <div className={styles('left')}>
          {!viewConfig.logoHeader && (
            <div className={styles('logo-text')}>
              <span className={styles('name')}>{config.project}</span>
              {config.subname && <div className={styles('subname')}>{config.subname}</div>}
              {!config.subname && <div className={styles('small')}>Admin</div>}
            </div>
          )}
          {viewConfig.logoHeader && (
            <div className={styles('logo-img')}>
              <Logo type={viewConfig.logoHeader} />
            </div>
          )}
          <div className={styles('nav')}>
            {navigation && navigation.map((item, key) => this.renderItem(item, key))}
          </div>
        </div>
        <div className={styles('right')}>
          {!config.noLogin && (
            <EnhancedDropdown
              user={profile}
              contentClass={styles('content-submenu')}
              arrowStyle={{ marginTop: '8px' }}
            >
              <div className={styles('submenu')}>
                {accountResourceOptions && !accountResourceOptions.hideFromHeader && resourceData && (
                  <div className={styles('account-data')}>
                    {resourceData.map((item, key) => (
                      <div
                        className={styles(
                          'resource',
                          'item',
                          item[config.idKey] === selectedResource[config.idKey] && 'active',
                        )}
                        key={key}
                        onClick={() => this.selectResource(item)}
                      >
                        {item[accountResourceOptions.menuKey || 'title']}
                      </div>
                    ))}
                  </div>
                )}
                <div className={styles('links')}>
                  {config.adminAccount && (
                    <NavLink
                      className={styles('item')}
                      to={config.adminAccountUrl || '/account/profile'}
                    >
                      <CustomIcon className={styles('icon')} icon="cog" />

                      <TextItem path="admin.buttons.profile" />
                    </NavLink>
                  )}
                  <div className={styles('item', 'logout')} onClick={() => this.logout()}>
                    <CustomIcon className={styles('icon')} icon="sign-out-alt" />
                    <TextItem path="admin.buttons.logout" />
                  </div>
                </div>
              </div>
            </EnhancedDropdown>
          )}
        </div>
      </div>
    );
  }
}
