import React, { useState, useEffect } from 'react';

// Redux part
import { useSelector, useDispatch } from 'react-redux';
import { StoreState } from 'store/rootReducer';

// Import actions here
import wActions from 'store/workspace/actions';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import Button from 'components/items/Button';

import { NavLink, withRouter } from 'react-router-dom';

import config from 'config/general';
import CustomIcon from 'components/items/CustomIcon';
import DropDownMenu from 'components/pageItems/DropDownMenu';
import Menu from 'components/global/Menu';
import SearchForm from 'components/forms/SearchForm';
import HeaderSearchForm from 'components/forms/HeaderSearchForm';
import { Form } from 'react-final-form';
import ProjectButton from 'components/items/ProjectButton';
import auth from 'store/auth';
import app from 'store/app';
import { pushRoute } from 'store/utils/routes';
import CustomDropdown from 'components/enhancers/CustomDropdown';
import Popup from 'components/pageItems/Popup';
import { formMutators } from 'store/utils/helper';
import qs from 'query-string';
import DateItem from 'components/items/DateItem';
import isEmpty from 'lodash/isEmpty';
import { syncAction } from 'store/utils/actions';
import ProjectModal from 'components/items/ProjectModal';
import Avatar from 'components/items/Avatar';
import styleIdentifiers from './projectHeader.scss';
// assets
import logo from './assets/logo-wf.svg';
import mail from './assets/mail.svg';
import cross from './assets/cross.svg';
import more from './assets/more.svg';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type ProjectHeaderProps = StateProps & DispatchProps & OwnProps;

const Dropdown = CustomDropdown(Avatar);

const ProjectHeader = (props: ProjectHeaderProps) => {
  const {
    history,
    location: { search },
  } = props;
  const [popupActive, setPopupActive] = useState(0);

  // mapStateToProps
  const session = useSelector((state: StoreState) => state.session.data);
  const profile = useSelector(
    (state: StoreState) => state.account.profile && state.account.profile.data,
  );
  const currentOrder = useSelector((state: StoreState) => state.order.current?.data);
  const lg = useSelector((state: StoreState) => state.content.lg);

  const currentSearch = useSelector(
    (state: StoreState) =>
      (state.workspace && state.workspace.list && state.workspace.list.requestData) || {},
  );

  const dispatch = useDispatch();

  const dialogShow = syncAction(dispatch, app.actions.dialog.show.action);

  const handleSubmit = values => {
    console.log('values', values);

    const data = {
      ...qs.parse(search),
      hoursFrom: values.hoursFrom,
      hoursTo: values.hoursTo,
      location: values.location,
      dateFrom: values.dateFrom,
      dateTo: values.dateTo,
      // types
      individual: values.individual,
      open: values.open,
      meeting: values.meeting,
      // unset dates
      dates: undefined,
    };

    history.push({
      pathname: pushRoute('search', lg),
      search: qs.stringify(data),
    });

    setPopupActive(0);
  };

  const searchParams = {
    workspaceTypes: [],
    ...currentSearch,
    ...qs.parse(search),
  };

  const init = !isEmpty(searchParams) && {
    individual:
      searchParams.individual === 'true' ||
      searchParams.workspaceTypes.indexOf('individual') >= 0 ||
      undefined,
    open:
      searchParams.open === 'true' || searchParams.workspaceTypes.indexOf('open') >= 0 || undefined,
    meeting:
      searchParams.meeting === 'true' ||
      searchParams.workspaceTypes.indexOf('meeting') >= 0 ||
      undefined,
    location: searchParams.location,
    dateFrom: searchParams.dateFrom,
    dateTo: searchParams.dateTo,
    hoursFrom: searchParams.hoursFrom,
    hoursTo: searchParams.hoursTo,
  };

  const hasSearch = init.location || init.dateFrom || init.dateTo || init.hoursFrom || init.hoursTo;

  const hasOrder = currentOrder?.getBookingInput?.ressourceId && currentOrder?.lines?.length > 0;

  const addWorkspace = () => {
    if (profile?.payoutInfo?.stripeInfo?.detailsSubmitted) {
      history.push(pushRoute('addWorkspace', lg));
      return;
    }

    dialogShow({
      id: 'custom',
      children: (
        <ProjectModal
          title="pages.mySpaces.noPayoutTitle"
          message="pages.mySpaces.noPayoutMessage"
          actionRight={() => {
            history.push(pushRoute('payout', lg));
          }}
        />
      ),
    });
  };

  return (
    <div className={styles('project-header')}>
      <Popup
        activeClassName={styles(popupActive && 'activePopup')}
        wrapperClassName={styles('wrapper-popup')}
        close={() => setPopupActive(!popupActive)}
      >
        <Form
          mutators={{ ...formMutators }}
          initialValues={init}
          component={HeaderSearchForm}
          onSubmit={handleSubmit}
        />
        <img
          src={cross}
          alt=""
          className={styles('close', popupActive)}
          onClick={() => setPopupActive(!popupActive)}
        />
      </Popup>
      <div className={styles('header-container')}>
        <div className={styles('content')}>
          <div className={styles('left')}>
            <NavLink exact to="/">
              <div className={styles('logo')}>
                <img src={logo} alt="logo" />
              </div>
            </NavLink>
          </div>
          <div
            className={styles('center', popupActive === 1 && 'active')}
            onClick={() => setPopupActive(popupActive === 1 ? null : 1)}
          >
            <div className={styles('search')}>
              {hasSearch && (
                <>
                  {init.location && <div className={styles('location')}>{init.location}</div>}
                  {init.dateFrom && init.dateTo && (
                    <div className={styles('dates')}>
                      <DateItem date={init.dateFrom} format="DD/MM" />
                      <span>{' - '}</span>
                      <DateItem date={init.dateTo} format="DD/MM" />
                    </div>
                  )}
                  {init.hoursFrom && init.hoursTo && (
                    <div className={styles('hours')}>{`${init.hoursFrom} - ${init.hoursTo}`}</div>
                  )}
                </>
              )}
              {!hasSearch && <TextItem path="general.header.search" />}
            </div>
          </div>
          {profile && (
            <div className={styles('right')}>
              <div className={styles('add')} onClick={addWorkspace}>
                <img src={more} alt="" className={styles('more')} />
              </div>
              <NavLink to={pushRoute('mailBox', lg)}>
                <div className={styles('messages')}>
                  {/* <div className={styles('indic')} /> */}
                  <img src={mail} alt="" />
                </div>
              </NavLink>
              <Dropdown
                indic={hasOrder}
                toggleContent
                profile={profile}
                noArrow
                contentClassName={styles('menu')}
              >
                <Menu />
              </Dropdown>
            </div>
          )}
          {!session && (
            <div className={styles('right')}>
              <NavLink to={pushRoute('login', lg)} className={styles('login')}>
                <ProjectButton noMargin color="primary" label="general.header.login" />
              </NavLink>
              <NavLink to={pushRoute('register', lg)} className={styles('register')}>
                <ProjectButton noMargin color="border-primary" label="general.header.signup" />
              </NavLink>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default withRouter(ProjectHeader);
