import {
  Icon, IconArrowsAnticlockwise, IconArrowsInfo, IconArrowsPlus,
  IconBasicGear,
} from '@bthlabs/homehub-icons';
import {withRango} from '@bthlabs/rango';
import Popup from '@bthlabs/react-custom-popup';
import ClassName from 'classnames';
import React from 'react';

import {IconBTHLabs} from 'src/assets';

import {AboutModal} from './AboutModal';
import {DummyWidget} from './DummyWidget';

import './StartMenu.scss';

export const ControlledStartMenu = (props) => {
  const rangoSettings = props.settings;
  const popupAnchorRef = React.useRef();
  const toolbarExpandTimeout = React.useRef(null);
  const [popupVisible, setPopupVisible] = React.useState(false);
  const [toolbarExpanded, setToolbarExpanded] = React.useState(
    rangoSettings.READ_ONLY
  );
  const [aboutModalVisible, setAboutModalVisible] = React.useState(false);

  const onStartButtonClick = React.useCallback(
    () => {
      setPopupVisible(true);
    },
    [setPopupVisible]
  );

  const onPopupLayout = (layout) => {
    let height = window.outerWidth < 768 ? 48 : 432;
    return [0, layout[1] - height];
  };

  const onPopupOverlayClick = React.useCallback(
    () => {
      setPopupVisible(false);
    },
    [setPopupVisible]
  );

  const onWidgetClick = React.useCallback(
    (event) => {
      if (props.hasDashboards) {
        props.onAddService(event.currentTarget.dataset.service);
      } else {
        event.stopPropagation();
        event.preventDefault();
      }
    },
    [props]
  );

  const onToolbarMouseEnter = React.useCallback(
    () => {
      if (rangoSettings.READ_ONLY) {
        return;
      }

      if (toolbarExpandTimeout.current === null) {
        toolbarExpandTimeout.current = window.setTimeout(
          () => {
            if (toolbarExpandTimeout.current !== null) {
              setToolbarExpanded(true);
            }
          },
          1000
        );
      }
    },
    [toolbarExpandTimeout, setToolbarExpanded, rangoSettings]
  );

  const onToolbarMouseLeave = React.useCallback(
    () => {
      if (rangoSettings.READ_ONLY) {
        return;
      }

      if (toolbarExpandTimeout.current !== null) {
        window.clearTimeout(toolbarExpandTimeout.current);
        toolbarExpandTimeout.current = null;
      }

      setToolbarExpanded(false);
    },
    [toolbarExpandTimeout, setToolbarExpanded, rangoSettings]
  );

  const onAboutItemClick = React.useCallback(
    () => {
      setAboutModalVisible(true);
    },
    [setAboutModalVisible]
  );

  const onAboutModalClose = React.useCallback(
    () => {
      setAboutModalVisible(false);
    },
    [setAboutModalVisible]
  );

  const onReloadButtonClick = React.useCallback(
    () => {
      window.location.reload();
    },
    []
  );

  const buttonClassName = ClassName('StartButton', {
    active: popupVisible,
  });
  const toolbarClassName = ClassName('toolbar', {
    expanded: toolbarExpanded,
  });
  const startMenuClassName = ClassName('StartMenu', {
    'read-only': rangoSettings.READ_ONLY,
  });
  return (
    <React.Fragment>
      <a
        _hint="StartButton"
        ref={popupAnchorRef}
        className={buttonClassName}
        onClick={onStartButtonClick}
      >
        <Icon icon={IconBTHLabs} size="24px" />
      </a>

      <Popup
        anchor={popupAnchorRef}
        visible={popupVisible}
        onLayout={onPopupLayout}
        onOverlayClick={onPopupOverlayClick}
      >
        <div
          _hint="StartMenu"
          className={startMenuClassName}
          onClick={onPopupOverlayClick}
        >
          <div
            className={toolbarClassName}
            onMouseEnter={onToolbarMouseEnter}
            onMouseLeave={onToolbarMouseLeave}
          >
            <div className="toolbar-inner">
              <div
                _hint="About"
                className="toolbar-item"
                onClick={onAboutItemClick}
              >
                <span className="toolbar-item-icon">
                  <Icon icon={IconArrowsInfo} />
                </span>
                About HomeHub
              </div>
              <div className="toolbar-extend">
                {!rangoSettings.READ_ONLY &&
                  <div
                    _hint="AddDashboard"
                    className="toolbar-item"
                    onClick={props.onAddDashboard}
                  >
                    <span className="toolbar-item-icon">
                      <Icon icon={IconArrowsPlus} />
                    </span>
                    Add Dashboard
                  </div>
                }
                <div
                  _hint="Reload"
                  className="toolbar-item"
                  onClick={onReloadButtonClick}
                >
                  <span className="toolbar-item-icon">
                    <Icon icon={IconArrowsAnticlockwise} />
                  </span>
                  Reload
                </div>
                {false &&
                  <React.Fragment>
                    <div className="toolbar-item">
                      <span className="toolbar-item-icon">
                        <Icon className="toolbar-item-icon" icon={IconBasicGear} />
                      </span>
                      Settings
                    </div>
                  </React.Fragment>
                }
              </div>
            </div>
          </div>
          {!rangoSettings.READ_ONLY &&
            <div _hint="Widgets" className="widgets">
              {Object.keys(props.services).map((key) => {
                const ServiceObject = props.services[key];
                const Widget = props.widgets[ServiceObject.widget] || DummyWidget;

                if (props.offlineMode && !ServiceObject.availableOffline) {
                  return null;
                }

                if (!props.offlineMode && !ServiceObject.availableOnline) {
                  return null;
                }

                const className = ClassName('widget', {
                  disabled: !props.hasDashboards,
                });
                return (
                  <div
                    _hint="Widget"
                    key={key}
                    className={className}
                    data-service={key}
                    onClick={onWidgetClick}
                  >
                    <Icon icon={Widget.icon || IconBasicGear} size={48} />
                    <p>{Widget.title || 'Unnamed Widget'}</p>
                  </div>
                );
              })}
            </div>
          }
          <AboutModal
            build={rangoSettings.HOMEHUB.build}
            show={aboutModalVisible}
            version={rangoSettings.HOMEHUB.version}
            onClose={onAboutModalClose}
          />
        </div>
      </Popup>
    </React.Fragment>
  );
};
ControlledStartMenu.displayName = 'StartMenu';

export const StartMenu = withRango(ControlledStartMenu);
