import PropTypes from 'prop-types';
import React from 'react';
import {
  MenuItem,
  Nav,
  Navbar,
  NavDropdown,
  NavItem,
  Radio,
  Well,
} from 'react-bootstrap';
import { ComboSearch } from 'react-combo-search';
import { getPDF } from '../../../api/icat/icatPlus';
import {
  DOC_VIEW,
  LIST_VIEW,
  NEW_EVENT_VISIBLE,
} from '../../../constants/eventTypes';
import LogbookPager from '../LogbookPager';
import EventListMenuButton from './EventListMenuButton';
import NewlyAvailableEventsDialogue from './NewlyAvailableEventsDialogue';

/**
 * The menu displayed above the event list
 */
class EventListMenu extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isNavbarExpanded: false,
    };

    this.getSelectPickerData = this.getSelectPickerData.bind(this);
    this.onSelectNavbar = this.onSelectNavbar.bind(this);
    this.onToggleNavbar = this.onToggleNavbar.bind(this);
    this.onSearch = this.onSearch.bind(this);
  }

  render() {
    const {
      investigationId,
      isNewButtonEnabled,
      eventCountBySelectionFilter,
      selectionFilter,
      sessionId,
      setView,
      isSortingLatestEventsFirst,
      view,
    } = this.props;

    return (
      <Navbar
        fluid
        expanded={this.state.isNavbarExpanded}
        onSelect={this.onSelectNavbar}
        onToggle={this.onToggleNavbar}
        style={{
          background: 'none',
          border: 'none',
          WebkitBoxShadow: 'none',
          boxShadow: 'none',
          position: 'sticky',
          top: 0,
          backgroundColor: 'white',
          zIndex: 1,
          marginTop: 10,
        }}
      >
        <Navbar.Header>
          <Navbar.Toggle />
          <Nav style={{ marginLeft: 0 }}>
            <NavItem eventKey={1} href="#" className="logbookNavItem">
              <EventListMenuButton
                text="New"
                glyph="plus"
                tooltipText="Create a new event"
                isEnabled={isNewButtonEnabled}
                isVisible={!this.props.logbookContext.isReleased}
              />
            </NavItem>

            <NavItem
              eventKey={2}
              href={`/investigation/${this.props.investigationId}/camera`}
              target="_blank"
              className="logbookNavItem"
            >
              <EventListMenuButton
                text="Take a photo"
                glyph="camera"
                tooltipText="Take a photo"
                isEnabled
                isVisible={!this.props.logbookContext.isReleased}
              />
            </NavItem>
          </Nav>
        </Navbar.Header>

        <Navbar.Collapse>
          <Nav>
            <NavDropdown
              eventKey={3}
              title={
                <div className="btn btn-sm btn-primary">
                  {' '}
                  View <span className="caret" />
                </div>
              }
              id="nav-dropdown"
              className="logbookNavItem"
            >
              <MenuItem eventKey={3.1} onSelect={() => setView(DOC_VIEW)}>
                {' '}
                <Radio checked={view === DOC_VIEW} readOnly>
                  {' '}
                  Classic (user's commented logs)
                </Radio>{' '}
              </MenuItem>
              <MenuItem eventKey={3.2} onSelect={() => setView(LIST_VIEW)}>
                {' '}
                <Radio checked={view === LIST_VIEW} readOnly>
                  {' '}
                  Full (all logs)
                </Radio>{' '}
              </MenuItem>
              <MenuItem divider />
              <MenuItem
                eventKey={3.3}
                onSelect={() => {
                  if (isSortingLatestEventsFirst) {
                    this.props.onSortingButtonClicked();
                  }
                }}
              >
                <Radio checked={!isSortingLatestEventsFirst} readOnly>
                  {' '}
                  Oldest log on top
                </Radio>
              </MenuItem>
              <MenuItem
                eventKey={3.4}
                onSelect={() => {
                  if (!isSortingLatestEventsFirst) {
                    this.props.onSortingButtonClicked();
                  }
                }}
              >
                <Radio checked={isSortingLatestEventsFirst} readOnly>
                  {' '}
                  Latest log on top
                </Radio>
              </MenuItem>

              {!this.props.logbookContext.isReleased && (
                <>
                  <MenuItem divider />
                  <MenuItem eventKey={3.5}>
                    <span style={{ paddingLeft: 20 }}>
                      {this.props.autorefreshEventList
                        ? 'Stop refreshing logs'
                        : 'Start refreshing logs'}
                    </span>
                  </MenuItem>
                </>
              )}
            </NavDropdown>
            <NavItem
              eventKey={4}
              href={
                !isNewButtonEnabled || eventCountBySelectionFilter === 0
                  ? null
                  : getPDF(sessionId, investigationId, selectionFilter)
              }
              target="_blank"
              className="logbookNavItem"
            >
              <EventListMenuButton
                text="PDF"
                glyph="download"
                tooltipText="Download as PDF"
                isEnabled={
                  !(!isNewButtonEnabled || eventCountBySelectionFilter === 0)
                }
              />
            </NavItem>
            <NavItem eventKey={5} className="logbookNavItem">
              <div className="hidden-xs hidden-sm">
                <NewlyAvailableEventsDialogue
                  autorefreshEventList={this.props.autorefreshEventList}
                  eventCountByPeriodicRefresher={this.props.periodicdata}
                  eventCountSinceLastRefresh={
                    this.props.eventCountSinceLastRefresh
                  }
                  onIconClicked={this.props.getEvents}
                />
              </div>
            </NavItem>

            <NavItem className="logbookNavItem">
              <div className="hidden-xs hidden-sm hidden-md">
                <LogbookPager
                  activePage={this.props.activePage}
                  eventCount={this.props.eventCountBySelectionFilter}
                  onPageClicked={this.props.onPageClicked}
                />
              </div>
            </NavItem>
          </Nav>

          <Nav pullRight>
            <NavItem
              eventKey={6}
              className="logbookNavItem logbookNavItem--combo"
            >
              <div className="comboSearchContainer">
                <ComboSearch
                  onSearch={this.onSearch}
                  selectData={[
                    { value: 'Everywhere', text: 'Everywhere' },
                    { value: 'Content', text: 'Content' },
                    { value: 'Title', text: 'Title' },
                    { value: 'category', text: 'Category' },
                    { value: 'Author', text: 'Author' },
                    // { value: 'Tag', text: 'Tag' },
                    { value: 'Creation date', text: 'Creation date' },
                  ]}
                  datePickerCriteria="Creation date"
                  selectPickerData={this.getSelectPickerData()}
                />
              </div>
              <Well
                style={{
                  display: 'inline-block',
                  padding: 4,
                  marginBottom: 0,
                  borderTopLeftRadius: 0,
                  borderBottomLeftRadius: 0,
                  color: '#666',
                }}
              >
                <b>{eventCountBySelectionFilter} found</b>
              </Well>
            </NavItem>
          </Nav>
        </Navbar.Collapse>
      </Navbar>
    );
  }

  getSelectPickerData() {
    const selectPickerData = {
      category: ['Info', 'Error', 'Command', 'Comment', 'Debug'],
    };

    if (this.props.availableTags) {
      selectPickerData.Tag = this.props.availableTags.map((tag) => ({
        value: tag._id,
        text: tag.name,
      }));
    }

    return selectPickerData;
  }
  /**
   * Callback triggered when the user clicks the button to expand the navbar in mobile layout
   */
  onToggleNavbar() {
    this.setState({ isNavbarExpanded: !this.state.isNavbarExpanded });
  }

  /**
   * Callback triggered when the user clicks an element of the navbar.
   * @param {*} eventKey key of the element
   */
  onSelectNavbar(eventKey) {
    // if (eventKey != 6) {
    //     this.onToggleNavbar();
    // }
    if (eventKey === 1) {
      if (this.props.isNewButtonEnabled) {
        this.props.setNewEventVisibility(NEW_EVENT_VISIBLE);
      }
    }

    if (eventKey === 3.5) {
      this.props.onRefreshEventListMenuItemClicked();
    }
  }

  onSearch(data) {
    return this.props.searchEvents(data);
  }
}

EventListMenu.propTypes = {
  /** Available tags for the proposal */
  availableTags: PropTypes.array,
  /** Event count by selection filter */
  eventCountBySelectionFilter: PropTypes.number,
  /** Number of event recieved since last refresh */
  eventCountSinceLastrefresh: PropTypes.number,
  /** Callback function used to trigger event list update */
  getEvents: PropTypes.func,
  /** Identifier of the current investigation */
  investigationId: PropTypes.string,
  /** whether the event list refreshes automatically when a new event has arrived */
  autorefreshEventList: PropTypes.bool,
  /** Whether the New button is enabled or not */
  isNewButtonEnabled: PropTypes.bool,
  /** Context in which the logbook is run */
  logbookContext: PropTypes.object,
  /** Function called when the user clicks on sorting buttons */
  onSortingButtonClicked: PropTypes.func.isRequired,
  /** Callback function which reloads the events based on search criteria*/
  searchEvents: PropTypes.func,
  /** Selection filter for mongo request (used for PDF request) */
  selectionFilter: PropTypes.object,
  /** Session identifier */
  sessionId: PropTypes.string.isRequired,
  /** Function triggered when the user clicks on the 'start/stop refreshing logs' menu item */
  onRefreshEventListMenuItemClicked: PropTypes.func,
  /** Callback function triggered when the user clicks on the new event button */
  setNewEventVisibility: PropTypes.func,
  /** Callback function executed when the user clicks the view buttons */
  setView: PropTypes.func,
  /** Whether the events are currently sorted lqtest first. False if oldest first. */
  isSortingLatestEventsFirst: PropTypes.bool.isRequired,
  /**  Current view */
  view: PropTypes.oneOf([DOC_VIEW, LIST_VIEW]),
};

export default EventListMenu;
