import React, { useRef } 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 CapEmojiPicker from '@capillarytech/cap-ui-library/CapEmojiPicker';
import CapDivider from '@capillarytech/cap-ui-library/CapDivider';
import CapAskAira from '@capillarytech/cap-ui-library/CapAskAira';
import { MESSAGE_MAX_LENGTH, SHOW_CHARACTER_COUNT } from '../../constants';
import { useAiraTriggerPosition } from '../hooks/useAiraTriggerPosition';

const InputWrapper = ({
  children,
  inputRef,
  error,
  value,
  onChange,
  isAiContentBotDisabled,
}) => {
  const wrapperRef = useRef(null);
  const airaRootStyle = useAiraTriggerPosition({ wrapperRef, inputRef, error });

  return (
    <div className="webpush-message-input-wrapper" ref={wrapperRef}>
      {children}
      {!isAiContentBotDisabled && (
        <CapAskAira.ContentGenerationBot
          text={value || ''}
          setText={(text) => onChange(text)}
          iconPlacement="float-br"
          iconSize="1.6rem"
          rootStyle={airaRootStyle}
        />
      )}
    </div>
  );
};

InputWrapper.propTypes = {
  children: PropTypes.node.isRequired,
  inputRef: PropTypes.oneOfType([
    PropTypes.shape({ current: PropTypes.any }),
    PropTypes.func,
  ]),
  error: PropTypes.string,
  value: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  isAiContentBotDisabled: PropTypes.bool,
};

InputWrapper.defaultProps = {
  inputRef: null,
  error: '',
  value: '',
  isAiContentBotDisabled: false,
};

/**
 * MessageSection component - Message textarea with tags, emoji picker, and character count
 */
export const MessageSection = ({
  value,
  error,
  onChange,
  formatMessage,
  messages,
  tagList,
  messageCountRef,
  messageTextAreaRef,
  handleMessageTextAreaRef,
  isAiContentBotDisabled,
}) => {
  const renderCharacterCount = () => {
    if (!SHOW_CHARACTER_COUNT) return null;

    const maxLength = MESSAGE_MAX_LENGTH;

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

  return (
    <>
      <CapRow className="creatives-webpush-message">
        <CapRow className="tooltip-add-label-container webpush-message-taglist">
          {tagList}
        </CapRow>
        <CapHeading type="h4" className="webpush-message">
          <FormattedMessage {...messages.message} />
        </CapHeading>
        <InputWrapper
          inputRef={messageTextAreaRef}
          error={error}
          value={value}
          onChange={onChange}
          isAiContentBotDisabled={isAiContentBotDisabled}
        >
          <CapEmojiPicker.Wrapper
            value={value}
            onChange={onChange}
            textAreaRef={messageTextAreaRef}
          >
            <CapInput.TextArea
              id="webpush-message-input"
              value={value}
              onChange={onChange}
              placeholder={formatMessage(messages.messagePlaceholder)}
              size="default"
              isRequired
              autosize={{ minRows: 3, maxRows: 5 }}
              setInputRef={handleMessageTextAreaRef}
              errorMessage={
                error && (
                  <CapError className="webpush-template-message-error">
                    {error}
                  </CapError>
                )
              }
            />
          </CapEmojiPicker.Wrapper>
        </InputWrapper>
        {renderCharacterCount()}
      </CapRow>
      <CapDivider className="webpush-message-divider" />
    </>
  );
};

MessageSection.propTypes = {
  value: PropTypes.string.isRequired,
  error: PropTypes.string,
  onChange: PropTypes.func.isRequired,
  formatMessage: PropTypes.func.isRequired,
  messages: PropTypes.object.isRequired,
  tagList: PropTypes.node,
  messageCountRef: PropTypes.object,
  messageTextAreaRef: PropTypes.object,
  handleMessageTextAreaRef: PropTypes.func.isRequired,
  isAiContentBotDisabled: PropTypes.bool,
};

MessageSection.defaultProps = {
  error: '',
  tagList: null,
  messageCountRef: null,
  messageTextAreaRef: null,
  isAiContentBotDisabled: false,
};

export default MessageSection;

