// 3rd-Party Libraries
import React, { useReducer } from 'react';
import PropTypes from 'prop-types';

// Components
import { Button, Input, Textarea } from '@ui/components';

// Constants
import { TutorialStepProp } from '@ui/compositions/Tutorials/Modal/proptypes/tutorials';

// Permissions
import { PermissionContext } from '@ui/compositions/Tutorials/Modal';

// Style
let classes = {};
/* istanbul ignore next */
if (typeof window !== 'undefined' || typeof _COMPILED_ === 'undefined') classes = require('./style.module.scss');

export default function TutorialStep({
  step,
  index,
  lastIndex,
  shiftOrder,
  navStep,
  handleClick,
  deleteStep,
  updateStep,
}) {
  const { body, className, title, isOpen } = step;

  const TutorialStepClasses = () =>
    [className, classes.TutorialStep, !isOpen && classes.TutorialStep_close].filter(e => e).join(' ');

  const [dirtyInput, setInputState] = useReducer((prevState, state) => ({ ...prevState, ...state }), {
    title: false,
    description: false,
  });

  const handleChange = target => {
    const { id, name, value } = target;
    const [, key] = id.split('-');
    updateStep({ [key]: value });
    setInputState({ [name]: true });
  };

  const onClick = event => {
    const { target } = event;
    if (!isOpen && target.nodeName !== 'I') handleClick();
  };

  return (
    <PermissionContext.Consumer>
      {/* eslint-disable jsx-a11y/no-autofocus */}
      {readOnly => (
        <section className={TutorialStepClasses()} onClick={onClick} onKeyDown={onClick} role="button" tabIndex="0">
          <header className={classes['TutorialStep-Header']}>
            <Input
              key={`tutorialStep-title-${index}`}
              autoComplete="off"
              autoFocus
              className={[classes['TutorialStep-Header-Input'], dirtyInput.title ? 'Input_dirty' : 'Input_clean'].join(
                ' '
              )}
              id={`tutorialStep-title-${index}`}
              name="title"
              onChange={e => handleChange(e.target)}
              placeholder={'Step Name'}
              readOnly={readOnly || !isOpen}
              required
              value={title}
            />
            {!readOnly && (
              <React.Fragment>
                <Button
                  bem={{ shale_text: true }}
                  className={classes['TutorialStep-Header-Button']}
                  disabled={index === 0}
                  onClick={() => shiftOrder(-1)}
                  size="sm"
                  text
                >
                  <i className="fa fa-arrow-circle-up" />
                </Button>
                <Button
                  bem={{ shale_text: true }}
                  className={classes['TutorialStep-Header-Button']}
                  disabled={index === lastIndex}
                  onClick={() => shiftOrder(1)}
                  size="sm"
                  text
                >
                  <i className="fa fa-arrow-circle-down" />
                </Button>
                {isOpen && (
                  <Button
                    bem={{ red_text: true }}
                    className={[classes['TutorialStep-Header-Button'], classes['TutorialStep-Header-Button_red']].join(
                      ' '
                    )}
                    disabled={lastIndex === 0}
                    onClick={() => deleteStep(index)}
                    size="sm"
                  >
                    <i className="icon icon-trash2" />
                  </Button>
                )}
              </React.Fragment>
            )}
          </header>
          <div className={classes['TutorialStep-Body']}>
            {readOnly ? (
              <div className={classes['TutorialStep-Body-Description']}>{body}</div>
            ) : (
              <Textarea
                key={`tutorialStep-body-${index}`}
                className={dirtyInput.description ? 'TextArea_dirty' : 'TextArea_clean'}
                id={`tutorialStep-body-${index}`}
                name="description"
                onChange={event => handleChange(event.target)}
                placeholder={'Description'}
                readOnly={readOnly}
                resize={readOnly ? 'none' : 'vertical'}
                value={body}
              />
            )}
          </div>
          {readOnly && isOpen && index !== lastIndex && (
            <footer className={classes['TutorialStep-Footer']}>
              <Button
                bem={{ shale_text: true }}
                className={classes['TutorialStep-Footer-Button']}
                onClick={() => navStep(1)}
                text
              >
                Next <i className="fa fa-arrow-circle-down" />
              </Button>
            </footer>
          )}
        </section>
      )}
      {/* eslint-enable jsx-a11y/no-autofocus */}
    </PermissionContext.Consumer>
  );
}

TutorialStep.propTypes = {
  deleteStep: PropTypes.func,
  handleClick: PropTypes.func,
  index: PropTypes.number,
  lastIndex: PropTypes.number,
  navStep: PropTypes.func,
  shiftOrder: PropTypes.func,
  step: TutorialStepProp,
  updateStep: PropTypes.func,
};

TutorialStep.defaultProps = {
  step: {},
};
