import * as React from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import { Form } from 'react-final-form';
import Input from 'components/formItems/Input';

import ModuleButton from 'components/items/ModuleButton';
import { api } from 'store/apis';
import PageFilterForm from 'components/forms/PageFilterForm';
import styleIdentifiers from './headerCms.scss';

const styles = classNames.bind(styleIdentifiers);

export interface HeaderCmsProps {
  logout: Function;
  updateContent: Function;
  noAction?: boolean;
}

interface HeaderCmsState {}

export default class HeaderCms extends React.Component<HeaderCmsProps, HeaderCmsState> {
  logout = (): void => {
    const { logout } = this.props;

    if (logout) logout();
  };

  search = values => {
    const { globalSearch } = this.props;

    if (values.filter && values.filter.length > 0 && values.filter.length < 3) return;

    if (this.timeout) clearTimeout(this.timeout);

    this.timeout = setTimeout(() => {
      globalSearch(values.filter);
    }, 200);
  };

  updateContent = (dev: boolean): void => {
    const { updateContent } = this.props;

    if (updateContent)
      updateContent({
        dev: dev === true,
      });
  };

  render(): JSX {
    const { noAction, search } = this.props;
    return (
      <div className={styles('HeaderCms')}>
        <div className={styles('left')}>
          <Form onSubmit={this.search} initialValues={search} component={PageFilterForm} />
        </div>
        <div className={styles('right')}>
          {api.app.updateContentDev && (
            <ModuleButton
              label="Update staging content"
              noMargin
              small
              color="blue"
              relative
              action={(): void => this.updateContent(true)}
            />
          )}
          {!noAction && (
            <ModuleButton
              label="Update prod content"
              noMargin
              small
              color="blue"
              relative
              action={this.updateContent}
            />
          )}
          {!noAction && (
            <ModuleButton
              small
              label="Logout"
              noMargin
              color="grey"
              relative
              action={this.logout}
            />
          )}
        </div>
      </div>
    );
  }
}
