import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapError from '@capillarytech/cap-ui-library/CapError';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import {
  NOTIFICATION_TITLE_MAX_LENGTH,
  SHOW_CHARACTER_COUNT,
} from '../../constants';

/**
 * NotificationTitleSection component - Notification title input with tags and character count
 */
export const NotificationTitleSection = ({
  value,
  error,
  onChange,
  formatMessage,
  messages,
  tagList,
  titleCountRef,
}) => {
  const renderCharacterCount = () => {
    if (!SHOW_CHARACTER_COUNT) return null;

    const maxLength = NOTIFICATION_TITLE_MAX_LENGTH;

    return (
      <CapLabel type="label2" className="webpush-character-count">
        <span ref={titleCountRef}>
          {formatMessage(messages.characterCount, {
            currentLength: value.length,
            maxLength,
          })}
        </span>
      </CapLabel>
    );
  };

  return (
    <CapRow className="creatives-webpush-title">
      <CapRow className="tooltip-add-label-container webpush-title-taglist">
        {tagList}
      </CapRow>
      <CapHeading type="h4" className="webpush-title">
        <FormattedMessage {...messages.notificationTitle} />
      </CapHeading>
      <CapInput
        id="webpush-notification-title-input"
        value={value}
        onChange={onChange}
        placeholder={formatMessage(messages.notificationTitlePlaceholder)}
        size="default"
        isRequired
        maxLength={NOTIFICATION_TITLE_MAX_LENGTH}
        errorMessage={
          error && (
            <CapError className="webpush-template-title-error">{error}</CapError>
          )
        }
      />
      {renderCharacterCount()}
    </CapRow>
  );
};

NotificationTitleSection.propTypes = {
  value: PropTypes.string.isRequired,
  error: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  formatMessage: PropTypes.func.isRequired,
  messages: PropTypes.object.isRequired,
  tagList: PropTypes.node,
  titleCountRef: PropTypes.object,
};

NotificationTitleSection.defaultProps = {
  error: '',
  tagList: null,
  titleCountRef: null,
};

export default NotificationTitleSection;

