import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { injectIntl, intlShape } from 'react-intl';
import PhoneInput from 'react-phone-input-2';
import 'react-phone-input-2/lib/style.css';
import { cloneDeep } from 'lodash';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import CapColumn from '@capillarytech/cap-ui-library/CapColumn';
import CapHeading from '@capillarytech/cap-ui-library/CapHeading';
import CapHeader from "@capillarytech/cap-ui-library/CapHeader";
import CapSelect from '@capillarytech/cap-ui-library/CapSelect';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapTooltip from '@capillarytech/cap-ui-library/CapTooltip';
import CapTooltipWithInfo from '@capillarytech/cap-ui-library/CapTooltipWithInfo';
import { CAP_SPACE_04 } from '@capillarytech/cap-ui-library/styled/variables';
import globalMessages from '../../v2Containers/Cap/messages';import CapTagListWithInput from '../CapTagListWithInput';

import { isUrl, isValidText } from '../../v2Containers/Line/Container/Wrapper/utils';
import messages from './messages';
import { CTA_OPTIONS, BTN_MAX_LENGTH, URL_MAX_LENGTH, PHONE_NUMBER_MAX_LENGTH,invalidVarRegex, HANDLERS } from './constants';
import './index.scss';
import { INITIAL_SUGGESTIONS, RCS_BUTTON_TYPES} from '../../v2Containers/Rcs/constants';

const { TextArea } = CapInput;


export const CapActionButton = (props) => {
  const {
    intl,
    buttonType,
    updateButtonChange,
    deleteButtonHandler,
    suggestions = [],
    isEditFlow,
    isFullMode,
    maxButtons,
    tags = [],
    injectedTags = {},
    location = {},
    selectedOfferDetails = [],

    onContextChange,
  } = props;
  const [urlError, setUrlError] = useState(false);
  const [buttonError, setButtonError] = useState(false);
  const updateHandler = (type, value, index) => {
    let clonedCta = cloneDeep(suggestions[index]);
    clonedCta = {
      ...clonedCta,
      [type]: value,
    };
    updateButtonChange(clonedCta, index);
  };
  const updateDisplayAndPostback = (value, index) => {
    // Clone once and update both fields
    const cloned = {
      ...cloneDeep(suggestions[index]),
      text: value,
      postback: value,
    };
    updateButtonChange(cloned, index);
  };

  const onCtaTypeChange = (value, index) => {
    let clonedCta = cloneDeep(suggestions[index]);
    clonedCta = {
      ...clonedCta,
      type: value,
      text: '',
      phoneNumber: '',
      postback: '',
      url: value === RCS_BUTTON_TYPES.PHONE_NUMBER ? null : '',
      isSaved: false,
    };
    setUrlError(false);
    setButtonError(false);
    updateButtonChange(clonedCta, index);
  };

  const onButtonTextChange = ({target}) => {
    const { value, id } = target;
    let errorMessage = '';
    if (value.length > BTN_MAX_LENGTH) {
      errorMessage = formatMessage(messages.ctaButtonTextLengthError);
    } if (!isValidText(value)) {
      errorMessage = formatMessage(messages.ctaButtonErrorMessage);
    }
    setButtonError(errorMessage);
    updateDisplayAndPostback(value, id);
  };

  const renderLength = (len, max) => (
    <CapHeading type="label1" className="rcs-render-btn-length">
      {formatMessage(messages.templateMessageLength, {
        currentLength: len,
        maxLength: max,
      })}
    </CapHeading>
  );

  const onUrlChange = ({ target }) => {
    let { value, id } = target;
    let errorMessage = false;
    if (!isUrl(value)) {
      errorMessage = formatMessage(messages.ctaWebsiteUrlErrorMessage);
    } else if (value.match(invalidVarRegex)?.length > 0) {
      errorMessage = formatMessage(messages.staticUrlWithVarErrorMessage);
    }
    setUrlError(errorMessage);
    updateHandler(HANDLERS.URL, value, id);
  };

  const onPhoneNoChange = (value, index) => {
    updateHandler(HANDLERS.PHONE_NUMBER, value, index);
  };

  const ctaSaveDisabled = (index) => {
    const { type, text, phoneNumber, url } = suggestions[index] || {};
    if (text === '' || buttonError) {
      return true;
    } if (type === RCS_BUTTON_TYPES.PHONE_NUMBER && phoneNumber.length < 5) {
      return true;
    } if (type === RCS_BUTTON_TYPES.CTA && (url === '' || urlError)) {
      return true;
    }
    return false;
  };

  const saveCta = (index) => {
    updateHandler(HANDLERS.IS_SAVED, true, index);
  };

  const editCta = (index) => {
    updateHandler(HANDLERS.IS_SAVED, false, index);
  };

  const addSuggestions = () => {
    let newSuggestion = cloneDeep(INITIAL_SUGGESTIONS?.[0] ?? {});
    newSuggestion.index = suggestions?.length;
    updateButtonChange(newSuggestion, suggestions?.length);
  };

  const renderCtaOptions = (label, tooltipLabel, isDisabled) => {
    if (isDisabled) {
      return (
        <CapRow>
          <CapColumn span={23}>{label}</CapColumn>
          <CapColumn span={1}>
            <CapTooltipWithInfo
              // autoAdjustOverflow
              placement="right"
              title={tooltipLabel}
            />
          </CapColumn>
        </CapRow>
      );
    }
    return label;
  };

  const { formatMessage } = intl;
  const renderedContent = () => {
    const renderArray = [];
    const addBtnDisabled = suggestions.length >= maxButtons || !suggestions[suggestions.length - 1]?.isSaved;

    const ctaOptions = CTA_OPTIONS.map((option) => {
      const { value, label } = option;
      const isDisabled = suggestions.length >= maxButtons && !suggestions[suggestions.length - 1];
      return {
        value,
        label: renderCtaOptions(label, formatMessage(messages.ctaButtonTypeDisabled), isDisabled),
        disabled: isDisabled,
      };
    });

    suggestions.forEach((cta) => {
      const {
        index, type, text, isSaved,
      } = cta || {};

      const url = type !== RCS_BUTTON_TYPES.CTA ? null : cta.url;
      const phoneNumber = type !== RCS_BUTTON_TYPES.PHONE_NUMBER ? null : cta.phoneNumber;
      if (isFullMode && !isEditFlow && !isSaved) {
        renderArray.push(
          <div className="rcs-button-cta-create-container" key={`cta-edit-${index}`}>
            <CapRow className="rcs-button-cta-create margin-t-16">
              <CapColumn span={12}>
                {/* Type of action */}
                <CapHeading type="h4" className="cta-label">
                  {formatMessage(messages.ctaType)}
                </CapHeading>
                <CapSelect
                  id="rcs-cta-type"
                  options={ctaOptions || []}
                  onChange={(value) => onCtaTypeChange(value, index)}
                  value={type}
                  disabled={false}
                />
              </CapColumn>
              <CapColumn span={12}>
                <CapHeading type="h4" className="cta-label">
                  {formatMessage(messages.ctaButtonText)}
                  <CapTooltipWithInfo
                    infoIconProps={{
                      style: { marginLeft: CAP_SPACE_04 },
                    }}
                    autoAdjustOverflow
                    placement="right"
                    title={formatMessage(messages.ctaButtonTextTooltip)}
                  />
                </CapHeading>
                <CapInput
                  id={index}
                  className="rcs-cta-button-text"
                  onChange={onButtonTextChange}
                  placeholder={formatMessage(messages.ctaButtonTextPlaceholder)}
                  value={text}
                  size="large"
                  maxLength={BTN_MAX_LENGTH}
                  errorMessage={buttonError}
                />
                {renderLength(text.length, BTN_MAX_LENGTH)}
              </CapColumn>
            </CapRow>
            {type === RCS_BUTTON_TYPES.PHONE_NUMBER && (
              <>
                <CapRow>
                  <CapColumn span={11}>
                    {/* phone number */}
                    <CapHeading type="h4" className="cta-label">
                      {formatMessage(messages.ctaPhoneNo)}
                    </CapHeading>
                    <PhoneInput
                      placeholder={formatMessage(messages.ctaPhoneNoPlaceholder)}
                      autoFormat={false}
                      countryCodeEditable={false}
                      value={phoneNumber}
                      onChange={(value) => onPhoneNoChange(value, index)}
                      country="in"
                      className="cta-phone-number"
                    />
                    {renderLength(phoneNumber.length, PHONE_NUMBER_MAX_LENGTH)}
                  </CapColumn>
                </CapRow>
                <CapRow className="rcs-cta-save-delete-btn">
                  <CapTooltip
                    title={ctaSaveDisabled(index) && formatMessage(messages.ctaSaveDisabled)}
                    placement="bottom"
                  >
                    <div className="button-disabled-tooltip-wrapper">
                      <CapButton
                        onClick={() => saveCta(index)}
                        disabled={ctaSaveDisabled(index)}
                        className="rcs-cta-save-btn"
                      >
                        {formatMessage(globalMessages.save)}
                      </CapButton>
                    </div>
                  </CapTooltip>
                  <CapButton
                    onClick={() => deleteButtonHandler(index)}
                    className="rcs-cta-delete-btn"
                    type="secondary"
                  >
                    {formatMessage(globalMessages.delete)}
                  </CapButton>
                </CapRow>
              </>
            )}
            {type === RCS_BUTTON_TYPES.CTA && (
              <>
                <CapRow>
                  <CapColumn span={24}>
                    <CapHeading type="h4" className="cta-label">
                      {formatMessage(messages.ctaWebsite)}
                    </CapHeading>
                    <CapInput
                      id={index}
                      className="rcs-cta-url"
                      onChange={onUrlChange}
                      placeholder={formatMessage(messages.ctaStaticPlaceholder)}
                      value={url}
                      size="large"
                      maxLength={URL_MAX_LENGTH}
                      errorMessage={urlError}
                    />
                    {renderLength(url.length, URL_MAX_LENGTH)}
                  </CapColumn>
                </CapRow>
                <CapRow className="rcs-cta-save-delete-btn">
                  <CapTooltip
                    title={
                      ctaSaveDisabled(index) && formatMessage(messages.ctaSaveDisabled)
                    }
                    placement="bottom"
                  >
                    <div className="button-disabled-tooltip-wrapper">
                      <CapButton
                        onClick={() => saveCta(index)}
                        disabled={ctaSaveDisabled(index)}
                        className="rcs-cta-save-btn"
                      >
                        {formatMessage(globalMessages.save)}
                      </CapButton>
                    </div>
                  </CapTooltip>
                  <CapButton
                    onClick={() => deleteButtonHandler(index)}
                    className="rcs-cta-delete-btn"
                    type="secondary"
                  >
                    {formatMessage(globalMessages.delete)}
                  </CapButton>
                </CapRow>
              </>
            )}
            {type === RCS_BUTTON_TYPES.QUICK_REPLY && (
              <CapRow className="rcs-cta-save-delete-btn">
                <CapTooltip
                  title={ctaSaveDisabled(index) && formatMessage(messages.ctaSaveDisabled)}
                  placement="bottom"
                >
                  <div className="button-disabled-tooltip-wrapper">
                    <CapButton
                      onClick={() => saveCta(index)}
                      disabled={ctaSaveDisabled(index)}
                      className="rcs-cta-save-btn"
                    >
                      {formatMessage(globalMessages.save)}
                    </CapButton>
                  </div>
                </CapTooltip>
                {index !== 0 && (
                  <CapButton
                    onClick={() => deleteButtonHandler(index)}
                    className="rcs-cta-delete-btn"
                    type="secondary"
                  >
                    {formatMessage(globalMessages.delete)}
                  </CapButton>
                )}
              </CapRow>
            )}
          </div>
        );
      } else {
        const ctaIsPhone = type === RCS_BUTTON_TYPES.PHONE_NUMBER;
        const ctaIsReply = type === RCS_BUTTON_TYPES.QUICK_REPLY;
        renderArray.push(
          <CapRow
            key={`cta-saved-${index}`}
            className="cap-rcs-saved-cta margin-t-12"
            align="middle"
            type="flex"
          >
            <CapColumn
              span={1}
              className={`${ctaIsPhone ? 'whatsapp-saved-cta-phone-icon' : ''}`}
            >
              <CapIcon size="s" type={ctaIsPhone ? 'call' : 'launch'} />
            </CapColumn>
            <CapColumn span={6}>
              <CapLabel
                type="label2"
                className="rcs-saved-cta-button-text"
              >
                {text}
              </CapLabel>
            </CapColumn>
            {ctaIsPhone && (
              <CapColumn span={10} align="left">
                <CapLabel className="phone">+{phoneNumber}</CapLabel>
              </CapColumn>
            )}
            {!ctaIsPhone && !ctaIsReply && (
              <>
                <CapColumn span={3}>
                  <CapLabel className="url-type" type="label2">
                    {formatMessage(messages.ctaWebsiteTypeStatic)}
                  </CapLabel>
                </CapColumn>
                <CapTooltip title={url} placement={'top'}>
                  <CapColumn span={7} style={{ marginRight: '0px' }}>
                    <CapLabel className="url">{url}</CapLabel>
                  </CapColumn>
                </CapTooltip>
              </>
            )}
            {(isFullMode && !isEditFlow) && (
              <>
                <CapColumn
                  span={1}
                  className="rcs-saved-cta-edit-icon"
                  onClick={() => editCta(index)}
                >
                  <CapIcon size="s" type="edit" />
                </CapColumn>
                {index !== 0 && (
                  <CapColumn className="rcs-saved-cta-delete-icon" span={1} onClick={() => deleteButtonHandler(index)}>
                    <CapIcon size="s" type="delete" />
                  </CapColumn>
                )}
              </>
            )}
          </CapRow>
        );
      }
    });
    {
      suggestions.length < maxButtons &&
        (isFullMode && !isEditFlow)
        && renderArray.push(
          <CapRow>
            <CapTooltip
              title={
                addBtnDisabled ? formatMessage(messages.ctaAddDisabled) : ''
              }
              placement={'right'}
            >
              <div className="button-disabled-tooltip-wrapper">
                <CapButton
                  type="flat"
                  id="rcs-cta-add-button"
                  disabled={addBtnDisabled}
                  className="margin-t-12 margin-l-24"
                  isAddBtn
                  onClick={addSuggestions}
                >
                  {formatMessage(messages.addButton)}
                </CapButton>
              </div>
            </CapTooltip>
          </CapRow>,
        );
    }
    return renderArray;
  };
  return renderedContent();
};

CapActionButton.propTypes = {
  intl: intlShape.isRequired,
  updateButtonChange: PropTypes.func,
  suggestions: PropTypes.array,
  tags: PropTypes.array,
  injectedTags: PropTypes.object,
  location: PropTypes.object,
  selectedOfferDetails: PropTypes.array,
  onTagSelect: PropTypes.func,
  onContextChange: PropTypes.func,
};

CapActionButton.defaultProps = {
  buttonTextlen: 20,
  type: '',
  updateButtonChange: () => {},
  suggestions: [],
  tags: [],
  injectedTags: {},
  location: {},
  selectedOfferDetails: [],
  onTagSelect: () => {},
  onContextChange: () => {},
};

export default injectIntl(CapActionButton);
