/**
 * MessageTypeStep Component
 *
 * Radio group for selecting Message Type: Promotional | Transactional
 */

import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import CapRadio from '@capillarytech/cap-ui-library/CapRadio';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import { CAP_SPACE_24 } from '@capillarytech/cap-ui-library/styled/variables';
import { MESSAGE_TYPES_OPTIONS } from '../../constants';
import messages from '../../messages';
import '../../CommunicationFlow.scss';

const MessageTypeStep = ({
  value,
  defaultOption,
  options: optionsProp,
  onChange,
  error,
  intl,
}) => {
  const { formatMessage } = intl || {};
  const options = optionsProp || MESSAGE_TYPES_OPTIONS;

  // Use defaultOption value if value is null/undefined
  const selectedValue = value || defaultOption?.value;

  const handleChange = (messageType) => {
    onChange(messageType);
  };

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

      <CapRow align="middle" type="flex" gap={CAP_SPACE_24}>
        {options?.map((option) => (
          <CapRadio
            key={option?.value}
            checked={selectedValue === option?.value}
            onChange={() => handleChange(option?.value)}
            disabled={option?.disabled}
          >
            {option?.label}
          </CapRadio>
        ))}
      </CapRow>

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

MessageTypeStep.propTypes = {
  value: PropTypes.oneOf(['promotional', 'transactional']),
  defaultOption: PropTypes.shape({
    value: PropTypes.string.isRequired,
    label: PropTypes.node.isRequired,
  }),
  options: PropTypes.arrayOf(PropTypes.shape({
    value: PropTypes.string.isRequired,
    label: PropTypes.node.isRequired,
  })),
  onChange: PropTypes.func.isRequired,
  error: PropTypes.string,
  intl: PropTypes.object.isRequired,
};

MessageTypeStep.defaultProps = {
  value: null,
  defaultOption: null,
  options: null,
  error: null,
};

export default injectIntl(MessageTypeStep);
