/**
 * CommunicationStrategyStep Component
 *
 * Dropdown for selecting Communication Strategy: Single template, Channel priority, A/B Test, etc.
 */

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

const CommunicationStrategyStep = ({
  value,
  onChange,
  options: optionsProp,
  disabled,
  error,
  intl,
}) => {
  const { formatMessage } = intl || {};

  // Normalize options: create custom labels with strategy name and channel type
  const options = useMemo(() => optionsProp?.map((option) => {
    const channelTypeText = option?.isMultiChannel
      ? formatMessage(messages.multipleChannel)
      : formatMessage(messages.singleChannel);

    const customLabel = (
      <CapRow align="middle" type="flex" justify="space-between">
        <CapHeading type="h5">{option?.label}</CapHeading>
        <CapHeading type="label3">{channelTypeText}</CapHeading>
      </CapRow>
    );

    return {
      key: option?.value,
      value: option?.value,
      label: customLabel,
      disabled: option?.disabled,
    };
  }), [optionsProp, formatMessage]);

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

  // Normalize value to undefined if null/empty to show placeholder
  // CapSelect shows placeholder when value is undefined
  const selectValue = (value === null || value === '') ? undefined : value;

  return (
    <CapRow useLegacy className="communication-strategy-step">
      <CapHeading type="h3" className="heading-style">
        {formatMessage(messages.communicationStrategyHeading)}
      </CapHeading>

      <CapSelect
        value={selectValue}
        onChange={handleChange}
        placeholder={formatMessage(messages.communicationStrategyPlaceholder)}
        options={options}
        style={{ width: '20.375rem' }}
        disabled={disabled}
      />

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

CommunicationStrategyStep.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  options: PropTypes.array,
  disabled: PropTypes.bool,
  error: PropTypes.string,
  intl: PropTypes.object.isRequired,
};

CommunicationStrategyStep.defaultProps = {
  value: null,
  error: null,
  disabled: false,
  options: [],
};

export default injectIntl(CommunicationStrategyStep);
