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

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

// Import actions here

import classNames from 'classnames/bind';

import { required, email, composeValidators } from 'store/utils/validation';
import TextItem from 'components/items/TextItem';
import ProjectButton from 'components/items/ProjectButton';
import ProjectInput from 'components/formItems/ProjectInput';
import actionsBuilder from 'store/appActions';

import EditAssetWorkSpaceForm from 'components/forms/EditAssetWorkSpaceForm';

import EditInfoWorkSpaceForm from 'components/forms/EditInfoWorkSpaceForm';
import EditHourWorkSpaceForm from 'components/forms/EditHourWorkSpaceForm';

import DateRangePicker from 'components/formItems/DateRangePicker';
import qs from 'query-string';
import styleIdentifiers from './manageWorkspaceForm.scss';
import ManageCharacteristicForm from '../ManageCharacteristicForm';

const styles = classNames.bind(styleIdentifiers);

export interface StateProps {}

export interface DispatchProps {}

export interface OwnProps {
  onSubmit: Function;
}

export type ManageWorkspaceFormProps = StateProps & DispatchProps & OwnProps;

const ManageWorkspaceForm = (props: ManageWorkspaceFormProps) => {
  const {
    handleSubmit,
    location: { search },
    submitting,
    values,
    valid,
    form,
    errors,
    submitFailed,
  } = props;

  const searchParams = qs.parse(search);
  // mapStateToProps
  const content = useSelector((state: StoreState) => state.content.raw);
  const lg = useSelector((state: StoreState) => state.content.lg);

  const features = useSelector(
    (state: StoreState) => state.general.feature && state.general.feature.data,
  );
  const equipments = useSelector(
    (state: StoreState) => state.general.equipment && state.general.equipment.data,
  );

  const [activeStep, setActiveStep] = useState(searchParams.tab === 'calendar' ? 4 : 1);

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

  const actions = actionsBuilder(dispatch, ['dialog.show', 'dialog.hide']);

  console.log('props', props);

  const managePictures = () => {
    actions.appDialogShow({
      id: 'custom',
      large: true,
      children: (
        <div>
          <h2>
            <TextItem path="pages.workspaceDetail.image.image" />
          </h2>
          <p>
            <TextItem path="pages.workspaceDetail.image.text" />
          </p>
          <Form component={EditAssetWorkSpaceForm} onSubmit={() => history.push('/')} />
        </div>
      ),
    });
  };

  const checkError = step => {
    if (!submitFailed) return false;

    const errorKeys = Object.keys(errors);

    for (let i = 0; i < errorKeys.length; i++) {
      const key = errorKeys[i];
      if (step === 1) {
        if (['address', 'minStay', 'maxCapacity', 'workspaceType'].indexOf(key) >= 0) return true;
      }
      if (step === 4) {
        if (['availability'].indexOf(key) >= 0) return true;
      }
    }
    return false;
  };

  return (
    <form className={styles('manage-workspace-form')} onSubmit={handleSubmit}>
      <div className={styles('top')}>
        <div className={styles('left')}>
          <h1>
            <TextItem
              path={
                !values._id
                  ? 'pages.workspaceDetail.newWorkspace'
                  : 'pages.workspaceDetail.editWorkspace'
              }
            />
          </h1>
          <div className={styles('details')}>
            {/* <img src={star} alt="" /> */}
            {/* <p>
            <TextItem path="4,3/5 (183)" />
          </p>
          <p>
            <TextItem path="•  Malmedy, Belgique" />
          </p> */}
          </div>
        </div>
        <div className={styles('action-wrapper')}>
          {/* {values._id && (
            <ProjectButton
              noMargin
              relative
              color="red"
              label="pages.workspaceDetail.actions.suspend"
              rounded
              customClassName={styles('button')}
            />
          )} */}
        </div>
      </div>
      <div className={styles('image-wrapper')}>
        <div className={styles('full')}>
          <Field
            noMargin
            component={ProjectInput}
            name="mainImages.main"
            seed="upload"
            accept="image/*"
            validate={required}
            customClassName={styles('custom-dropzone')}
            uploadPreviewClassName={styles('custom-preview')}
          />
        </div>
        <div className={styles('grid')}>
          <div className={styles('item')}>
            <Field
              noMargin
              component={ProjectInput}
              name="mainImages.one"
              seed="upload"
              accept="image/*"
              customClassName={styles('custom-dropzone')}
              uploadPreviewClassName={styles('custom-preview')}
            />
          </div>
          <div className={styles('item')}>
            <Field
              noMargin
              component={ProjectInput}
              name="mainImages.two"
              seed="upload"
              accept="image/*"
              customClassName={styles('custom-dropzone')}
              uploadPreviewClassName={styles('custom-preview')}
            />
          </div>
          <div className={styles('item')}>
            <Field
              noMargin
              component={ProjectInput}
              name="mainImages.three"
              seed="upload"
              accept="image/*"
              customClassName={styles('custom-dropzone')}
              uploadPreviewClassName={styles('custom-preview')}
            />
          </div>
          <div className={styles('item')}>
            <Field
              noMargin
              component={ProjectInput}
              name="mainImages.four"
              seed="upload"
              accept="image/*"
              customClassName={styles('custom-dropzone')}
              uploadPreviewClassName={styles('custom-preview')}
            />
          </div>
        </div>
      </div>
      <div className={styles('bottom')}>
        <div className={styles('toggle-wrapper')}>
          <div className={styles('toggle-button')}>
            <div
              className={styles('button', activeStep === 1 && 'active', checkError(1) && 'error')}
              onClick={() => setActiveStep(1)}
            >
              <p>
                <TextItem path="pages.workspaceDetail.information.information" />
              </p>
            </div>
            <div
              className={styles('button', activeStep === 2 && 'active', checkError(2) && 'error')}
              onClick={() => setActiveStep(2)}
            >
              <p>
                <TextItem path="pages.workspaceDetail.characteristic.characteristic" />
              </p>
            </div>
            <div
              className={styles('button', activeStep === 3 && 'active', checkError(3) && 'error')}
              onClick={() => setActiveStep(3)}
            >
              <p>
                <TextItem path="pages.workspaceDetail.equipment.equipment" />
              </p>
            </div>
            <div
              className={styles('button', activeStep === 4 && 'active', checkError(4) && 'error')}
              onClick={() => setActiveStep(4)}
            >
              <p>
                <TextItem path="pages.workspaceDetail.calendar.calendar" />
              </p>
            </div>
          </div>
          <div className={styles('toggle-content')}>
            <div className={styles('content', 'info', activeStep === 1 && 'active')}>
              <h2>
                <TextItem path="pages.workspaceDetail.information.roomInfo" />
              </h2>
              <EditInfoWorkSpaceForm />
            </div>
            <div className={styles('content', 'feature', activeStep === 2 && 'active')}>
              <h2>
                <TextItem path="pages.workspaceDetail.characteristic.roomCharacteristic" />
              </h2>
              <ManageCharacteristicForm name="features" list={features} />
            </div>
            <div className={styles('content', 'equipment', activeStep === 3 && 'active')}>
              <h2>
                <TextItem path="pages.workspaceDetail.equipment.roomEquipment" />
              </h2>
              <ManageCharacteristicForm name="equipments" list={equipments} />
            </div>
            <div className={styles('content', 'calendar', activeStep === 4 && 'active')}>
              <div className={styles('wrapper')}>
                <div className={styles('calendar-wrapper')}>
                  <h2>
                    <TextItem path="forms.calendar.calendar" />
                  </h2>
                  <p>
                    <TextItem path="forms.calendar.text" />
                  </p>
                  <div>
                    <Field
                      component={DateRangePicker}
                      // mapping={{
                      //   startDate: 'dateFrom',
                      //   endDate: 'dateTo',
                      // }}
                      label="forms.calendar.period"
                      minDate={new Date()}
                      name="availability.dates"
                      seed="daterange"
                      validate={required}
                    />
                    <Field
                      component={ProjectInput}
                      classic
                      type="checkbox"
                      name="availability.noWeekend"
                      seed="checkbox"
                      label="forms.calendar.notAvailable"
                    />
                  </div>
                </div>
                <div className={styles('hour-wrapper')}>
                  <h2>
                    <TextItem path="forms.hour.hour" />
                  </h2>
                  <p>
                    <TextItem path="forms.hour.text" />
                  </p>
                  <EditHourWorkSpaceForm values={values} base="availability" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div className={styles('action-wrapper')}>
        {activeStep > 1 && (
          <ProjectButton
            relative
            color="border-primary"
            label="pages.workspaceDetail.actions.previous"
            action={() => setActiveStep(activeStep - 1)}
            rounded
            customClassName={styles('button')}
          />
        )}

        {activeStep <= 3 && (
          <ProjectButton
            relative
            color="primary"
            label="pages.workspaceDetail.actions.next"
            action={() => setActiveStep(activeStep + 1)}
            rounded
            customClassName={styles('button')}
          />
        )}
        {activeStep === 4 && (
          <ProjectButton
            relative
            color="primary"
            label="pages.workspaceDetail.actions.save"
            type="submit"
            rounded
            customClassName={styles('button')}
          />
        )}
      </div>
    </form>
  );
};

export default ManageWorkspaceForm;
