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

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

// Import actions here
import bookingActions from 'store/booking/actions';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import WorkspaceCard from 'components/listItems/WorkspaceCard';
import BookingCard from 'components/listItems/BookingCard';
import GoogleMapItem from 'components/pageItems/GoogleMapItem';

import { render } from 'react-dom';
import moment from 'moment';
import MapStructure from 'components/structure/MapStructure';
import actionsBuilder from 'store/appActions';
import booking from 'store/booking';
import qs from 'query-string';
import Pagination from 'components/items/Pagination';
import styleIdentifiers from './myBookings.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type MyBookingsProps = StateProps & DispatchProps & OwnProps;

const LIMIT = 50;

const MyBookings = (props: MyBookingsProps) => {
  const {
    history,
    location: { search },
  } = props;
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  const profile = useSelector((state: StoreState) => state.account.profile.data);
  const bookings = useSelector((state: StoreState) => state.booking.list);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const { bookingList } = actionsBuilder(dispatch, ['list']);

  const searchParams = qs.parse(search);

  useEffect(() => {
    const load = loading => {
      bookingList({
        page: searchParams.page,
        limit: LIMIT,
        noLoading: !loading,
        noFeedback: !loading,
        noReset: !loading,
        data: {
          status: ['processing', 'validated'],
        },
      });
    };

    load(true);

    // polling
    const handler = setInterval(load, 5000);

    return () => {
      clearInterval(handler);
    };
  }, [search]);

  // polling

  return (
    <div className={styles('my-bookings')}>
      <div className={styles('container')}>
        <h1 className={styles('title')}>
          <TextItem path="pages.myBookings.myBooking" />
        </h1>

        <div className={styles('list-wrapper')}>
          {bookings?.data?.length > 0 &&
            bookings.data.map((item, index) => {
              return <BookingCard type="user" booking={item} key={index} history={history} />;
            })}
          <Pagination count={bookings?.count} limit={LIMIT} current={searchParams.page} />
          {bookings && bookings.loaded && bookings.data && !bookings.data.length && (
            <div className={styles('no-results')}>
              <TextItem path="pages.myBookings.noResults" />
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default MyBookings;
