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

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

// Import actions here

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import { pushRoute } from 'store/utils/routes';
// assets
import { compareSearchObj, formatAddress, formMutators } from 'store/utils/helper';
import qs from 'query-string';
import WorkspaceCard from 'components/listItems/WorkspaceCard';
import { treatmentSearch } from 'store/workspace/sagas';
import MapStructure from 'components/structure/MapStructure';
import SeoHandler from 'components/global/SeoHandler';
import general from 'store/general';
import { useLocation, useHistory } from 'react-router-dom';
import FiltersForm from 'components/forms/FiltersForm';

import { Form } from 'react-final-form';
import useAction from 'components/hooks/action';
import workspace from 'store/workspace';
import styleIdentifiers from './SearchHandler.module.scss';

const styles = classNames.bind(styleIdentifiers);

export interface SearchHandlerProps {}

const SearchHandler = (props: SearchHandlerProps) => {
  const { noLoading, noSeo, full, limit = 5 } = props;

  const location = useLocation();
  const history = useHistory();

  const { search } = location;

  // const [geolocation, setGeolocation] = useState<GeolocationPosition>();
  const [geolocationError, setGeolocationError] = useState(false);
  const [geoLoading, setGeoLoading] = useState(false);

  const lg = useSelector((state: StoreState) => state.content.lg);
  const workspaces = useSelector((state: StoreState) => state.workspace.list);
  const selection = useSelector((state: StoreState) => state.geoloc.geoloc?.data?.loc);
  const profile = useSelector((state: StoreState) => state.account.profile?.data);
  const geolocation = useSelector((state: StoreState) => state.general.position);

  const setPosition = useAction(general.actions.setPosition, true);
  const workspaceList = useAction(workspace.actions.list);

  const searchParams = useMemo(() => qs.parse(search), [search]);

  const positionError = error => {
    console.log('error', error);
    setGeolocationError(true);
    setGeoLoading(false);
  };

  useEffect(() => {
    if (geolocation) setGeoLoading(false);
  }, [geolocation]);

  useEffect(() => {
    // If no specific search provided + no geolocation from user => get geolocation from user
    if (!searchParams.location && !geolocation) {
      setGeoLoading(true);
      navigator.geolocation.getCurrentPosition(setPosition, positionError, {
        timeout: 8000,
      });

      // if geolocation error and profile address => use that adress as a location.
      if (geolocationError && profile?.address) {
        searchParams.location = formatAddress(profile.address);
      }
      // if no geolocation error => wait
      else if (!geolocationError) {
        return;
      }
    }

    const params = treatmentSearch(searchParams, geolocation, limit);

    const requestData = workspaces?.requestData;

    const isSame = compareSearchObj(requestData, params, []);

    if (isSame && !requestData._ids) return;

    workspaceList({
      data: params,
      noLoading,
    });
  }, [
    noLoading,
    location,
    geolocationError,
    profile,
    geolocation,
    searchParams,
    limit,
    setPosition,
    workspaceList,
  ]);

  const submit = values => {
    const data = {
      ...values,
      page: undefined,
      dates: undefined,
    };

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

  const initial = {
    ...searchParams,
    individual: searchParams.individual === 'true',
    open: searchParams.open === 'true',
    meeting: searchParams.meeting === 'true',
  };

  const center =
    selection?.coordinates ||
    (geolocation?.coords && [geolocation?.coords.longitude, geolocation?.coords.latitude]);

  return (
    <MapStructure
      relative
      count={workspaces?.count}
      limit={limit}
      currentPage={searchParams.page}
      list={workspaces}
      center={center}
      className={styles('search-handler', full && 'full')}
    >
      {!noSeo && (
        <SeoHandler
          path="seo.search"
          // title replacement
          title={searchParams?.location && 'seo.home.titleLocation'}
          replace={searchParams}
        />
      )}
      <h1 className={styles('title')}>
        <TextItem
          path={searchParams?.location ? 'pages.home.nearbyLocation' : 'pages.home.nearbySpace'}
          replace={searchParams}
        />
      </h1>
      <Form
        mutators={{
          ...formMutators,
        }}
        initialValues={initial}
        component={FiltersForm}
        onSubmit={submit}
      />
      <div className={styles('list-wrapper')}>
        {geoLoading && (
          <TextItem tag="div" className={styles('searching')} path="pages.home.locationSearch" />
        )}
        {workspaces?.data &&
          workspaces.data.map((item, index) => {
            return <WorkspaceCard key={index} view="home" item={item} />;
          })}
        {!geoLoading && !workspaces?.loading && workspaces?.data && !workspaces.data.length && (
          <div className={styles('no-results')}>
            <TextItem path="pages.home.notFound" />
          </div>
        )}
      </div>
    </MapStructure>
  );
};

export default SearchHandler;
