import React, { useState, useEffect } from 'react';
import { Form } from 'react-final-form';

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

import qs from 'query-string';

// Import actions here
import messagerieActions from 'store/messagerie/actions';

import workspaceActions from 'store/workspace/actions';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import MoreInfoCheckoutForm from 'components/forms/MoreInfoCheckoutForm';
import moment from 'moment';
import Quantity from 'components/items/Quantity';

import booking from 'store/booking';
import { push } from 'connected-react-router';
import { pushRoute } from 'store/utils/routes';
import order from 'store/order';
import BackButton from 'components/items/BackButton';
import styleIdentifiers from './checkoutStep1.scss';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type CheckoutStep1Props = StateProps & DispatchProps & OwnProps;

const CheckoutStep1 = (props: CheckoutStep1Props) => {
  const { location, match, history } = props;

  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  // Allow to dispatch actions
  const dispatch = useDispatch();

  const searchData = qs.parse(location.search);

  const lastSearch = useSelector((state: StoreState) => state.workspace.list?.requestData);

  const currentSearch = {
    ...lastSearch,
    ...searchData,
  };

  const profile = useSelector((state: StoreState) => state.account.profile?.data);
  const workspace = useSelector((state: StoreState) => state.workspace.detail?.data);

  const currentOrder = useSelector((state: StoreState) => state.order.current);

  const createRoom = data => dispatch(messagerieActions.createRoom.request.action(data));
  const addMessageToRoom = data =>
    dispatch(messagerieActions.addMessageToRoom.request.action(data));

  const creatOrder = data => dispatch(order.actions.add.request.action(data));

  // console.log('currentSearch', currentSearch);

  useEffect(() => {
    // check that there is a search + workspace loaded
    if (!currentSearch || !workspace) return;

    // if (!currentOrder) return;
    // check that you are not loading your order
    // if (!currentOrder?.loaded || currentOrder?.loading) return;

    // const data = currentOrder?.data;

    // const lines = data?.lines || [];

    // check that the current order is related to the current workspace
    // if (lines[0]?.productId === workspace._id) return;

    // If none of the above => create order
    const orderData = {
      input: {
        durationType: 'slot',
        slot: {
          startDate: currentSearch.dateFrom,
          endDate: currentSearch.dateTo,
          startTime: currentSearch.hoursFrom,
          endTime: currentSearch.hoursTo,
        },
        ressourceId: workspace._id,
        capacity: currentSearch.people && Number(currentSearch.people),
        ressourceModel: 'workspaces',
      },
    };
    console.log('create order', orderData);

    creatOrder({
      data: orderData,
      callbackError: err => {
        console.log('err', err);
      },
    });
  }, [workspace]);

  const handleSubmit = values => {
    if (values.message) {
      createRoom({
        accountIds: [profile._id, workspace.createdBy],
        callback: res => {
          addMessageToRoom({
            data: {
              roomId: res._id,
              message: values.message,
            },
            callback: res2 => {
              console.log(res2);
              return history.push({
                pathname: pushRoute('checkout.id.step2', lg, {
                  id: match?.params.id,
                }),
              });
            },
          });
        },
      });
    } else {
      history.push({
        pathname: pushRoute('checkout.id.step2', lg, {
          id: match?.params.id,
        }),
      });
    }
  };

  const currentOrderData = currentOrder?.data;

  if (!currentSearch?.dateFrom || !currentSearch?.dateTo) return <Redirect to="/" />;

  if (!currentOrderData?.getBookingInput) return <BackButton />;

  const {
    capacity,
    comments,
    slot: { endDate, endTime, startDate, startTime },
  } = currentOrderData?.getBookingInput;

  const workspaceData = workspace || {};
  const { workspaceType, pricingPerHour, currency } = workspaceData;

  return (
    <div className={styles('checkout-step1')}>
      {workspace && (
        <>
          <h1>
            <TextItem path="pages.checkout.summary" />
          </h1>
          <div className={styles('detail-wrapper')}>
            <h2>
              <TextItem path="pages.checkout.rental" />
              <TextItem path="lists.workspaceType" item={workspaceType} />
              <TextItem path="pages.checkout.detail.at" />
              <TextItem path={workspace.place.formattedAddress} />
              {moment(startDate) === moment(endDate) && (
                <>
                  <TextItem path="pages.checkout.detail.on" />
                  <TextItem path={moment(endDate).format('DD-MM-YYYY')} />
                </>
              )}
              {moment(startDate) !== moment(endDate) && (
                <div>
                  <TextItem path="pages.checkout.detail.from" />
                  <TextItem path={moment(startDate).format('DD-MM-YYYY')} />
                  <TextItem path="pages.checkout.detail.to" />
                  <TextItem path={moment(endDate).format('DD-MM-YYYY')} />
                </div>
              )}
            </h2>
            <div className={styles('detail')}>
              <div className={styles('item')}>
                <p className={styles('green')}>
                  <Quantity value={pricingPerHour} suffix="€/h" />
                </p>
              </div>
              <hr />
              <div className={styles('item')}>
                <p className={styles('label')}>
                  <TextItem path="pages.checkout.detail.participant" />
                </p>
                <p>
                  <TextItem path={capacity} />
                </p>
              </div>
              <hr />
              <div className={styles('item')}>
                <p className={styles('label')}>
                  <TextItem path="pages.checkout.detail.startTime" />
                </p>
                <p>
                  <TextItem path={startTime} />
                </p>
              </div>
              <hr />
              <div className={styles('item')}>
                <p className={styles('label')}>
                  <TextItem path="pages.checkout.detail.finishTime" />
                </p>
                <p>
                  <TextItem path={endTime} />
                </p>
              </div>
            </div>
          </div>

          <div className={styles('tips')}>
            <h2>
              <TextItem path="pages.checkout.tips.title" />
            </h2>
            <p>
              <TextItem path="pages.checkout.tips.text" />
            </p>
          </div>

          <div className={styles('form-wrapper')}>
            <Form
              component={MoreInfoCheckoutForm}
              onSubmit={handleSubmit}
              customClassName={styles('form')}
            />
          </div>
        </>
      )}
    </div>
  );
};

export default CheckoutStep1;
