import React, { useState, useEffect, useRef } from 'react';
import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import { NavLink } from 'react-router-dom';
import ModuleButton from 'components/items/ModuleButton';
import qs from 'query-string';
import CustomIcon from 'components/items/CustomIcon';
import { deepOmit } from 'store/utils/helper';
import generic from 'store/generic';
import { useDispatch } from 'react-redux';
import styleIdentifiers from './moduleList.scss';
import ModuleDropActions from '../ModuleDropActions';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type ModuleListProps = StateProps & DispatchProps & OwnProps;

const ModuleList = (props: ModuleListProps) => {
  const {
    className,
    options,
    children,
    subNav,
    match,
    history,
    noBorderTitle,
    location,
    actions,
    rightActions,
  } = props;

  const nav = (subNav && subNav.list) || subNav || null;

  const [tabActive, setTabActive] = useState(null);
  const [filters, setFitlers] = useState(null);
  const [timer, setTimer] = useState(null);
  const searchInput = useRef(null);

  const dispatch = useDispatch();

  const resetDetail = data => dispatch(generic.actions.detail.reset.action(data));

  useEffect(() => {
    if (location.search) {
      const parseLocation = qs.parse(location.search);
      const value = parseLocation[subNav && subNav.params];
      setTabActive(value);
    }
  }, [location]);

  function loadSearch(res) {
    history.push({
      search: qs.stringify(res),
    });
  }

  function handleSearch(res) {
    let req = filters;
    if (res) req.search = res;
    else req = deepOmit(req, 'search');

    if (timer) clearTimeout(timer);
    const test = setTimeout(() => loadSearch(req), 500);
    setTimer(test);
  }

  function addItem() {
    resetDetail();
    history.push(`${match.url}/create`);
  }

  useEffect(() => {
    setFitlers(qs.parse(location.search));
  }, [match]);

  return (
    <div className={styles('ModuleList', className)}>
      <div className={styles('header')}>
        <div className={styles('header-container', noBorderTitle && !subNav && 'no-border')}>
          <div className={styles('main-header-container')}>
            {options.titleList && (
              <div className={styles('title')}>
                <TextItem path={options.titleList} />
              </div>
            )}
            {!options.noSearch && (
              <div
                className={styles('search-container')}
                onClick={() => searchInput.current.focus()}
              >
                <CustomIcon icon="search" className={styles('icon')} />
                <input
                  onChange={e => handleSearch(e.target.value)}
                  type="text"
                  name="search"
                  ref={searchInput}
                  placeholder="Search"
                />
              </div>
            )}
          </div>
          {actions && (
            <ModuleDropActions
              className={styles('actions')}
              buttonClassName={styles('button-actions')}
              label="Bulk actions"
              actions={actions}
            />
          )}
          {rightActions}
          {!options.noCreate && rightActions === undefined && (
            <div className={styles('add-actions')}>
              <ModuleButton
                action={addItem}
                label={options.addLabel || 'New'}
                iconLeft="plus"
                noMargin
              />
            </div>
          )}
        </div>
      </div>
      {nav && (
        <div className={styles('sub-nav', noBorderTitle && 'no-border')}>
          {nav &&
            Array.isArray(nav) &&
            nav.map((item, key) => (
              <NavLink
                to={`/shop/${subNav.path}?${subNav.params}=${item.value}`}
                className={styles(
                  'sub-nav-item',
                  tabActive === item.value && 'active-sub-nav-item',
                )}
                key={key}
              >
                {item.label}
              </NavLink>
            ))}
        </div>
      )}
      <div className={styles('list-container')}>{children}</div>
    </div>
  );
};

export default ModuleList;
