/* eslint-disable camelcase */
/* eslint-disable react/prop-types */
import React, { useState } from 'react';
import { injectIntl } 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 CapSelect from '@capillarytech/cap-ui-library/CapSelect';
import CapInput from '@capillarytech/cap-ui-library/CapInput';
import CapButton from '@capillarytech/cap-ui-library/CapButton';
import CapLabel from '@capillarytech/cap-ui-library/CapLabel';
import CapIcon from '@capillarytech/cap-ui-library/CapIcon';
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 whatsappMsg from '../../v2Containers/Whatsapp/messages';
import messages from './messages';
import './index.scss';
import { isUrl, isValidWhatsappCtaText } from '../../v2Containers/Line/Container/Wrapper/utils';
import TagList from '../../v2Containers/TagList';
import {
  CTA_OPTIONS,
  BTN_MAX_LENGTH,
  PHONE_NUMBER_MAX_LENGTH,
  TWILIO_URL_OPTIONS,
  KARIX_GUPSHUP_URL_OPTIONS,
  URL_MAX_LENGTH,
  PHONE_NUMBER,
  WEBSITE,
  DYNAMIC_URL,
  STATIC_URL,
  DYNAMIC_URL_SUFFIX,
} from './constants';
import {
  INITIAL_CTA_DATA,
  HOST_TWILIO,
} from '../../v2Containers/Whatsapp/constants';

export const CapWhatsappCTA = (props) => {
  const {
    intl,
    ctaData = [],
    updateHandler,
    deleteHandler,
    isEditFlow,
    hostName,
    tags = [],
    injectedTags = {},
    selectedOfferDetails = [],
    eventContextTags = [],
    waitEventContextTags = {},
  } = props;
  const { formatMessage } = intl;
  const invalidVarRegex = /{{(.*?)}}/g;

  const [urlError, setUrlError] = useState(false);
  const [buttonError, setButtonError] = useState(false);

  const updateHelper = (type, value, index) => {
    let clonedCta = cloneDeep(ctaData[index]);
    clonedCta = {
      ...clonedCta,
      [type]: value,
    };
    if (type === 'urlType') {
      clonedCta.url = '';
      setUrlError(false);
    }
    updateHandler(clonedCta, index);
  };

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

  const onTagSelect = (data, index, url) => {
    updateHelper('url', url.replace('{{1}}', `{{${data}}}`), index);
  };

  const revertTagSelect = (index, url) => {
    updateHelper('url', url.replace(invalidVarRegex, `{{1}}`), index);
  };

  const onCtaTypeChange = (value, index) => {
    let clonedCta = cloneDeep(ctaData[index]);
    clonedCta = {
      ...clonedCta,
      ctaType: value,
      text: '',
      phone_number: '',
      url: '',
    };
    setUrlError(false);
    updateHandler(clonedCta, index);
  };

  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 ctaOptions = CTA_OPTIONS.map((option) => {
    const { value, label, tooltipLabel } = option;
    //only disable PHONE_NUMBER if first button is also PHONE_NUMBER
    const isDisabled = ctaData.length === 2 && ctaData[0].ctaType === PHONE_NUMBER && value === PHONE_NUMBER;
    return {
      value,
      label: renderCtaOptions(label, tooltipLabel, isDisabled),
      disabled: isDisabled,
    };
  });

  const addCta = () => {
    const clonedCta = cloneDeep(ctaData);
    clonedCta.push(cloneDeep(INITIAL_CTA_DATA[0]));
    if (clonedCta.length === 2) {
      clonedCta[1].index = 1;
      clonedCta[1].ctaType = clonedCta[0].ctaType === PHONE_NUMBER ? WEBSITE : PHONE_NUMBER;
    }
    updateHandler(clonedCta, null, true);
  };

  const onButtonTextChange = ({ target }) => {
    const { value, id } = target;
    let errorMessage = '';
    if (!isValidWhatsappCtaText(value)) {
      errorMessage = formatMessage(messages.ctaButtonErrorMessage);
    }
    setButtonError(errorMessage);
    updateHelper('text', value, id);
  };

  const onPhoneNoChange = (value, index) => {
    updateHelper('phone_number', value, index);
  };

  const onUrlTypeChange = (value, index) => {
    updateHelper('urlType', value, index);
  };

  const onUrlChange = ({ target }, urlType) => {
    let { value, id } = target;
    if (urlType === DYNAMIC_URL) {
      value = value.replace(invalidVarRegex, '');
    }
    let errorMessage = false;
    if (!isUrl(value)) {
      errorMessage = formatMessage(messages.ctaWebsiteUrlErrorMessage);
    } else if (
      urlType === STATIC_URL
      && value.match(invalidVarRegex)?.length > 0
    ) {
      errorMessage = formatMessage(messages.staticUrlWithVarErrorMessage);
    }
    setUrlError(errorMessage);
    updateHelper('url', value, id);
  };

  const ctaSaveDisabled = (index) => {
    const {
      ctaType, text, phone_number, url,
    } = ctaData[index] || {};
    if (text === '' || buttonError) {
      return true;
    } else if (ctaType === PHONE_NUMBER && phone_number.length < 5) {
      return true;
    } else if (ctaType === WEBSITE && (url === '' || urlError)) {
      return true;
    }
    return false;
  };

  const saveCta = (index) => {
    const clonedIndexCta = cloneDeep(ctaData[index]);
    // If this is a website CTA with dynamic URL type, ensure {{1}} is added at the end
    if (clonedIndexCta?.ctaType === WEBSITE && clonedIndexCta?.urlType === DYNAMIC_URL) {
      if (!clonedIndexCta?.url?.includes(DYNAMIC_URL_SUFFIX)) {
        clonedIndexCta.url += DYNAMIC_URL_SUFFIX;
        ctaData[index] = clonedIndexCta;
      }
    }
    updateHelper('isSaved', true, index);
  };
  const editCta = (index) => {
    updateHelper('isSaved', false, index);
  };

  const renderedContent = () => {
    const renderArray = [];
    const addBtnDisabled = ctaData.length === 1 && !ctaData[0].isSaved;
    ctaData.forEach((cta) => {
      const {
        index, ctaType, text, phone_number, urlType, url, isSaved,
      } = cta || {};
      //this is to display buttons after they are saved, in both create and edit mode.
      if (isSaved) {
        const ctaIsPhone = ctaType === PHONE_NUMBER;
        const urlTypeIsDynamic = urlType === DYNAMIC_URL;
        renderArray.push(
          <CapRow
            className="cap-whatsapp-saved-cta margin-t-12"
            align="middle"
            type="flex"
            style={{ marginLeft: isEditFlow ? 0 : '' }}
          >
            <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="whatsapp-saved-cta-button-text"
              >
                {text}
              </CapLabel>
            </CapColumn>
            {ctaIsPhone && (
              <CapColumn span={10} align="left">
                <CapLabel className="phone">+{phone_number}</CapLabel>
              </CapColumn>
            )}
            {!ctaIsPhone && (
              <>
                <CapColumn span={3}>
                  <CapLabel className="url-type" type="label2">
                    {urlType === STATIC_URL
                      ? formatMessage(messages.ctaWebsiteTypeStatic)
                      : formatMessage(messages.ctaWebsiteTypeDynamic)}
                  </CapLabel>
                </CapColumn>
                <CapTooltip title={url} placement="top">
                  <CapRow type='flex' fullWidth style={{ marginRight: '0px', maxWidth: '11.2rem' }}>
                    <CapLabel className="url">{url}</CapLabel>
                  </CapRow>
                </CapTooltip>
              </>
            )}
            {!isEditFlow && (
              <>
                <CapColumn
                  span={1}
                  className="whatsapp-saved-cta-edit-icon"
                  onClick={() => editCta(index)}
                >
                  <CapIcon size="s" type="edit" />
                </CapColumn>
                <CapColumn span={1} onClick={() => deleteHandler(index)}>
                  <CapIcon size="s" type="delete" />
                </CapColumn>
              </>
            )}
            {isEditFlow && urlTypeIsDynamic && url.includes('{{1}}') && (
              <CapColumn>
                <TagList
                  className="whatsapp-cta-taglist"
                  label={formatMessage(messages.whatsappCtaTagListLabel)}
                  onTagSelect={(data) => onTagSelect(data, index, url)}
                  tags={tags}
                  injectedTags={injectedTags}
                  selectedOfferDetails={selectedOfferDetails}
                  eventContextTags={eventContextTags}
                  waitEventContextTags={waitEventContextTags}
                />
              </CapColumn>
            )}
            {isEditFlow && urlTypeIsDynamic && !url.includes('{{1}}') && (
              <CapColumn
                span={1}
                onClick={() => revertTagSelect(index, url)}
                className="whatsapp-cta-tag-revert"
              >
                <CapTooltip
                  title={formatMessage(messages.whatsappCtaTagListRevert)}
                  placement="top"
                >
                  <CapIcon size="s" type="return" />
                </CapTooltip>
              </CapColumn>
            )}
          </CapRow>,
        );
      } else {
        //this is to display buttons before they are saved, only in create mode.
        renderArray.push(
          <CapRow
            useLegacy
            className="cap-whatsapp-cta margin-t-16"
            id={`cap-whatsapp-cta-${index}`}
          >
            <CapColumn>
              <CapRow type='flex' justify='space-between' className='actions-container'>
                <CapColumn span={11}>
                  {/* Type of action */}
                  <CapHeading type="h4" className="cta-label">
                    {formatMessage(messages.ctaType)}
                  </CapHeading>
                  <CapSelect
                    id="whatsapp-cta-type"
                    options={ctaOptions || []}
                    onChange={(value) => onCtaTypeChange(value, index)}
                    value={ctaType}
                  />
                </CapColumn>
                <CapColumn span={11}>
                  {/* Button text */}
                  <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="whatsapp-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>
              {ctaType === 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={phone_number}
                      onChange={(value) => onPhoneNoChange(value, index)}
                      country="in"
                      className="cta-phone-number"
                    />
                    {renderLength(phone_number.length, PHONE_NUMBER_MAX_LENGTH)}
                  </CapColumn>
                </CapRow>
              )}
              {ctaType === WEBSITE && (
                <CapRow type="flex" justify="space-between">
                  <CapColumn span={11}>
                    {/* URL Type */}
                    <CapHeading type="h4" className="cta-label">
                      {formatMessage(messages.ctaWebsiteType)}
                    </CapHeading>
                    <CapSelect
                      id="whatsapp-cta-url-type"
                      options={
                        hostName === HOST_TWILIO
                          ? TWILIO_URL_OPTIONS
                          : KARIX_GUPSHUP_URL_OPTIONS
                      }
                      onChange={(value) => onUrlTypeChange(value, index)}
                      value={urlType}
                    />
                  </CapColumn>
                  <CapColumn span={11}>
                    {/* cta url */}
                    <CapHeading type="h4" className="cta-label">
                      {formatMessage(messages.ctaWebsiteUrl)}
                      {urlType === DYNAMIC_URL && (
                        <CapTooltipWithInfo
                          infoIconProps={{
                            style: { marginLeft: CAP_SPACE_04 },
                          }}
                          autoAdjustOverflow
                          placement="right"
                          title={formatMessage(messages.dynamicUrlTooltip, { one: '{{1}}' })}
                        />
                      )}
                    </CapHeading>
                    <CapInput
                      id={index}
                      addonAfter={urlType === DYNAMIC_URL && !url.includes(DYNAMIC_URL_SUFFIX) && DYNAMIC_URL_SUFFIX}
                      className="whatsapp-cta-url"
                      onChange={(event) => onUrlChange(event, urlType)}
                      placeholder={
                        urlType === DYNAMIC_URL
                          ? formatMessage(messages.ctaDynamicPlaceholder)
                          : formatMessage(messages.ctaStaticPlaceholder)
                      }
                      value={url}
                      size="large"
                      maxLength={URL_MAX_LENGTH}
                      errorMessage={urlError}
                    />
                    {renderLength(url.length, URL_MAX_LENGTH)}
                  </CapColumn>
                </CapRow>
              )}
            </CapColumn>
            <CapColumn>
              <CapRow useLegacy className="whatsapp-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="whatsapp-cta-save-btn"
                    >
                      {formatMessage(globalMessages.save)}
                    </CapButton>
                  </div>
                </CapTooltip>
                <CapButton
                  onClick={() => deleteHandler(index)}
                  className="whatsapp-cta-delete-btn"
                  type="secondary"
                >
                  {formatMessage(globalMessages.delete)}
                </CapButton>
              </CapRow>
            </CapColumn>
          </CapRow>,
        );
      }
    });
    // eslint-disable-next-line no-lone-blocks
    {
      // when first button is not saved, add button is disabled with tooltip
      // eslint-disable-next-line no-unused-expressions
      ctaData.length < 2
        && !isEditFlow
        && renderArray.push(
          <CapRow useLegacy>
            <CapTooltip
              title={
                addBtnDisabled ? formatMessage(messages.ctaAddDisabled) : ''
              }
              placement="right"
            >
              <div className="button-disabled-tooltip-wrapper">
                <CapButton
                  type="flat"
                  id="whatsapp-cta-add-button"
                  disabled={addBtnDisabled}
                  className="margin-t-12 margin-l-24"
                  isAddBtn
                  onClick={addCta}
                >
                  {formatMessage(messages.addButton)}
                </CapButton>
              </div>
            </CapTooltip>
          </CapRow>,
        );
    }
    return renderArray;
  };

  return renderedContent();
};

export default injectIntl(CapWhatsappCTA);
