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 { withRouter } from 'react-router-dom';
// Import actions here
import accountActions from 'store/account/actions';

import ImageGallery from 'components/global/ImageGallery';

import classNames from 'classnames/bind';
import TextItem from 'components/items/TextItem';
import BookingForm from 'components/forms/BookingForm';
import { pushRoute } from 'store/utils/routes';
import ProjectButton from 'components/items/ProjectButton/ProjectButton';
import Quantity from 'components/items/Quantity';
import ListItems from 'components/items/ListItems';
import CustomIcon from 'components/items/CustomIcon';
import { formMutators, getContentList } from 'store/utils/helper';
import qs from 'query-string';
import isEmpty from 'lodash/isEmpty';
import find from 'lodash/find';

import moment from 'moment';
import app from 'store/app';
import ProjectModal from 'components/items/ProjectModal';
import messagerie from 'store/messagerie';
import MoreInfoCheckoutForm from 'components/forms/MoreInfoCheckoutForm';
import SeoHandler from 'components/global/SeoHandler';
import { syncAction } from 'store/utils/actions';
import account from 'store/account';
import styleIdentifiers from './workspaceDetail.scss';

// assets
import unlike from './assets/unlike.svg';
import like from './assets/like.svg';
import share from './assets/share.svg';

import star from './assets/star.svg';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {}

export type WorkspaceDetailProps = StateProps & DispatchProps & OwnProps;

const WorkspaceDetail = (props: WorkspaceDetailProps) => {
  const {
    history,
    workspace,
    mine,
    location: { search },
  } = props;
  // mapStateToProps
  const lg = useSelector((state: StoreState) => state.content.lg);
  const content = useSelector((state: StoreState) => state.content.raw);
  const equipments = useSelector(
    (state: StoreState) => state.general.equipment && state.general.equipment.data,
  );
  const features = useSelector(
    (state: StoreState) => state.general.feature && state.general.feature.data,
  );

  let currentSearch = useSelector((state: StoreState) => state.workspace.list?.requestData);
  if (!currentSearch || isEmpty(currentSearch)) currentSearch = qs.parse(search);

  const profile = useSelector(
    (state: StoreState) => state.account.profile && state.account.profile.data,
  );

  let isFavorite;

  if (profile && profile.getFavorites) {
    isFavorite = find(profile.getFavorites, favorite => {
      return favorite.ressourceId === workspace._id;
    });
  }

  // Allow to dispatch actions
  const dispatch = useDispatch();

  const dialogShow = data => dispatch(app.actions.dialog.show.action(data));
  const createRoom = data => dispatch(messagerie.actions.createRoom.request.action(data));
  const addMessageToRoom = data =>
    dispatch(messagerie.actions.addMessageToRoom.request.action(data));
  const saveRedirect = syncAction(dispatch, account.actions.saveRedirect.action);

  const edit = () => {
    history.push(pushRoute('editWorkspace.id', lg, { id: workspace._id }));
  };

  const displayGallery = index => {
    const list = [];

    const keys = Object.keys(workspace.mainImages);

    for (let i = 0; i < keys.length; i += 1) {
      const key = keys[i];
      const elem = workspace.mainImages[key];

      if (elem && elem.large) list.push(elem.large);
    }

    dialogShow({
      id: 'custom',
      children: <ImageGallery id="custom" images={list} current={index} />,
    });
  };

  const handleReservation = values => {
    const data = {
      hoursTo: values.hoursTo,
      hoursFrom: values.hoursFrom,
      search: values.search,
      dateFrom: values.dateFrom,
      dateTo: values.dateTo,
      // types
      individual: values.individual,
      open: values.open,
      meeting: values.meeting,
      people: values.people || 1,
      dates: undefined,
    };

    if (!profile) {
      // not loggued
      dialogShow({
        id: 'custom',
        children: (
          <ProjectModal
            title="items.needLogged.title"
            message="items.needLogged.textReservation"
            buttonRight="items.needLogged.button"
            button="general.actions.cancel"
            buttonBottom="items.needLogged.actionBottom"
            actionBottom={() => {
              saveRedirect({
                pathname: location.pathname,
                search: qs.stringify(data),
              });
              history.push(pushRoute('register', lg));
            }}
            actionRight={() => {
              saveRedirect({
                pathname: location.pathname,
                search: qs.stringify(data),
              });
              history.push(pushRoute('login', lg));
            }}
          />
        ),
      });
      return;
    }

    history.push({
      pathname: pushRoute('checkout.id.step1', lg, { id: workspace._id }),
      search: qs.stringify(data),
    });
  };

  const likeWorkspace = () => {
    if (!isFavorite) {
      dispatch(
        accountActions.addFavoriteToAccount.request.action({
          data: {
            ressourceId: workspace._id,
            ressourceType: 'workspaces',
          },
        }),
      );
    } else {
      dispatch(
        accountActions.removeFavoriteToAccount.request.action({
          data: {
            ressourceId: workspace._id,
          },
        }),
      );
    }
  };

  console.log('current search', currentSearch);

  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('mailBox.id', lg, {
                  id: workspace.createdBy,
                }),
              });
            },
          });
        },
      });
    }
  };

  const ownerName = `${workspace?.getOwner?.firstName} ${workspace.getOwner.lastName.charAt(0)}.`;

  return (
    <div className={styles('workspace-detail')}>
      <SeoHandler
        path="seo.detailWorkspace"
        replace={{
          ...workspace,
          type: getContentList(content, 'lists.workspaceType', workspace.workspaceType, lg),
        }}
      />
      <div className={styles('top')}>
        <div>
          <h1>
            {`${workspace.title} - `}
            <TextItem path="lists.workspaceType" item={workspace.workspaceType} />
          </h1>
          <div className={styles('details')}>
            {workspace.score && (
              <div className={styles('score')}>
                <img src={star} className={styles('icon')} alt="" />
                <TextItem path={workspace.score} />
              </div>
            )}
            {workspace?.address && (
              <div className={styles('localisation')}>
                {`${workspace.address.city}, ${workspace.address.country}`}
              </div>
            )}
          </div>
        </div>
        <div className={styles('action-wrapper')}>
          {mine && (
            <ProjectButton
              noMargin
              label="general.actions.edit"
              color="border-primary"
              customClassName={styles('button')}
              action={edit}
            />
          )}
          {/* <img src={share} alt="share" className={styles('icon')} /> */}

          {profile && (
            <img
              src={isFavorite ? like : unlike}
              alt="like"
              className={styles('icon', isFavorite && 'liked')}
              onClick={() => likeWorkspace()}
            />
          )}
        </div>
      </div>
      <div className={styles('image-wrapper')}>
        <div className={styles('full', 'custom-preview')} onClick={() => displayGallery(0)}>
          {workspace.mainImages.main && <img src={workspace.mainImages.main.medium} alt="full" />}
        </div>
        <div className={styles('grid')}>
          {workspace.mainImages && (
            <>
              {workspace.mainImages.one && (
                <div className={styles('item', 'custom-preview')} onClick={() => displayGallery(1)}>
                  <img src={workspace.mainImages.one.small} alt="grid" />
                </div>
              )}
              {workspace.mainImages.two && (
                <div className={styles('item', 'custom-preview')} onClick={() => displayGallery(2)}>
                  <img src={workspace.mainImages.two.small} alt="grid" />
                </div>
              )}
              {workspace.mainImages.three && (
                <div className={styles('item', 'custom-preview')} onClick={() => displayGallery(3)}>
                  <img src={workspace.mainImages.three.small} alt="grid" />
                </div>
              )}
              {workspace.mainImages.four && (
                <div className={styles('item', 'custom-preview')} onClick={() => displayGallery(4)}>
                  <img src={workspace.mainImages.four.small} alt="grid" />
                </div>
              )}
            </>
          )}
        </div>
      </div>
      <div className={styles('bottom')}>
        <div className={styles('detail-wrapper')}>
          <div className={styles('detail')}>
            <div className={styles('item')}>
              <p className={styles('green')}>
                <Quantity suffix=" €/h" value={workspace.finalPrice} />
              </p>
            </div>
            <hr />
            <div className={styles('item')}>
              <p className={styles('label')}>
                <TextItem path="pages.workspaceDetail.details.capacity.capacity" />
              </p>
              <p>
                <TextItem path="$num" replace={{ num: workspace.maxCapacity }} />
                <TextItem path="pages.workspaceDetail.details.capacity.person" />
              </p>
            </div>
            <hr />
            {workspace.minStay && (
              <div className={styles('item')}>
                <p className={styles('label')}>
                  <TextItem path="pages.workspaceDetail.details.locationMin" />
                </p>
                <p>
                  <Quantity suffix="h" fixed={0} value={workspace.minStay} />
                </p>
              </div>
            )}
          </div>
          <div className={styles('description')}>
            <h2>
              <TextItem path="pages.workspaceDetail.Description" />
            </h2>
            <div className={styles('content')}>{workspace.content}</div>
          </div>
          <div className={styles('features')}>
            <h2>
              <TextItem path="pages.workspaceDetail.Caracteristique" />
            </h2>
            <ListItems list={workspace.featureIds} dataList={features} />
          </div>
          <div className={styles('equipments')}>
            <h2>
              <TextItem path="pages.workspaceDetail.Equipement" />
            </h2>
            <ListItems list={workspace.equipmentIds} dataList={equipments} />
          </div>
          {profile && profile._id !== workspace?.createdBy && (
            <div className={styles('contact-owner')}>
              <h2>
                <TextItem
                  path="pages.workspaceDetail.contactOwner"
                  replace={{
                    name: ownerName,
                  }}
                />
              </h2>
              <Form
                component={MoreInfoCheckoutForm}
                onSubmit={handleSubmit}
                button="pages.workspaceDetail.contactButton"
                initialValues
                relativeButton
                customClassName={styles('form')}
              />
            </div>
          )}
        </div>

        <div className={styles('form-wrapper')}>
          <h2>
            <TextItem
              path="forms.booking.title"
              replace={{
                name: ownerName,
              }}
            />
          </h2>
          <p>
            <TextItem path="forms.booking.text" />
          </p>
          <Form
            mutators={{ ...formMutators }}
            component={BookingForm}
            initialValues={currentSearch}
            // initialValues={{
            //   dateFrom: moment('01-12-2020', 'DD-MM-YYYY'),
            //   dateTo: moment('04-12-2020', 'DD-MM-YYYY'),
            // }}
            workspace={workspace}
            onSubmit={handleReservation}
          />
        </div>
      </div>
    </div>
  );
};

export default withRouter(WorkspaceDetail);
