/**
 * DynamicControlsStep Component
 */

import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapSwitch from '@capillarytech/cap-ui-library/CapSwitch';
import messages from '../../messages';
import './DynamicControlsStep.scss';

const DynamicControlsStep = ({
  value,
  onChange,
  controls,
  error,
  intl,
}) => {
  const { formatMessage } = intl || {};
  // formatMessage used for section title only
  const dynamicControls = value?.dynamicControls || {};

  const handleToggle = (key, checked) => {
    onChange({
      ...value,
      dynamicControls: { ...dynamicControls, [key]: checked },
    });
  };

  if (!controls?.length) return null;

  return (
    <CapRow className="dynamic-controls-step">
      <CapHeading type="h3" className="heading-style">
        {formatMessage(messages.dynamicControlsTitle)}
      </CapHeading>

      {controls.map(({ key, label, description }) => {
        const checked = !!dynamicControls[key];
        const displayLabel = label || key;

        return (
          <CapRow
            key={key}
            type="flex"
            align="top"
            justify="space-between"
            className="dynamic-controls-step__row"
          >
            <CapRow useLegacy className="dynamic-controls-step__label-wrap">
              <CapHeading type="h4" className="dynamic-controls-step__label">
                {displayLabel}
              </CapHeading>
              {description && (
                <CapHeading type="label4" className="dynamic-controls-step__desc">
                  {description}
                </CapHeading>
              )}
            </CapRow>
            <CapSwitch
              checked={checked}
              onChange={(val) => handleToggle(key, val)}
              className="dynamic-controls-step__switch"
            />
          </CapRow>
        );
      })}

      {error && (
        <CapRow useLegacy className="validation-error dynamic-controls-step__error">
          {error}
        </CapRow>
      )}
    </CapRow>
  );
};

DynamicControlsStep.propTypes = {
  value: PropTypes.shape({
    dynamicControls: PropTypes.object,
  }),
  onChange: PropTypes.func.isRequired,
  controls: PropTypes.arrayOf(
    PropTypes.shape({
      key: PropTypes.string.isRequired,
      label: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
      description: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
    }),
  ),
  error: PropTypes.string,
  intl: PropTypes.object.isRequired,
};

DynamicControlsStep.defaultProps = {
  value: {},
  controls: [],
  error: null,
};

export default injectIntl(DynamicControlsStep);
