import React, { useState } from "react";
import { injectIntl } from "react-intl";
import "react-phone-input-2/lib/style.css";
import cloneDeep from "lodash/cloneDeep";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapColumn from "@capillarytech/cap-ui-library/CapColumn";
import CapInput from "@capillarytech/cap-ui-library/CapInput";
import CapButton from "@capillarytech/cap-ui-library/CapButton";
import CapRow from "@capillarytech/cap-ui-library/CapRow";
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 CapSelect from "@capillarytech/cap-ui-library/CapSelect";
import CapTag from '@capillarytech/cap-ui-library/CapTag';
import { CAP_SPACE_04 } from "@capillarytech/cap-ui-library/styled/variables";
import globalMessages from "../../v2Containers/Cap/messages";
import inAppMsg from "../../v2Containers/InApp/messages";
import messages from "./messages";
import './index.scss';
import {
  isUrl,
  isValidText,
} from "../../v2Containers/Line/Container/Wrapper/utils";
import {
  BTN_MAX_LENGTH,
  DEEP_LINK,
  EXTERNAL_URL,
  CTA_OPTIONS,
  URL_MAX_LENGTH,
} from "./constants";
import CapTagListWithInput from "../CapTagListWithInput";

export const CapInAppCTA = (props) => {
  const {
    intl,
    ctaData = [],
    updateHandler,
    deleteHandler,
    deepLink,
    onContextChange,
    location,
    tags,
    injectedTags,
    selectedOfferDetails,
  } = props;
  const { formatMessage } = intl;

  const [urlError, setUrlError] = useState(false);
  const [buttonError, setButtonError] = useState(false);
  const [ctaDeepLinkValue, setCtaDeepLinkValue] = useState(ctaData[0]?.url || "");
  const selectedDeepLink = deepLink?.find(link => link?.value === ctaData[0]?.url);

  const updateHelper = (type, value, index) => {
    let clonedCta = cloneDeep(ctaData[index]);
    clonedCta = {
      ...clonedCta,
      [type]: value,
    };
    updateHandler(clonedCta, index);
  };

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


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

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

  const onUrlChange = ({ target }) => {
    const { value} = target;
    let errorMessage = false;
    if (!isUrl(value)) {
      errorMessage = formatMessage(messages.ctaWebsiteUrlErrorMessage);
    }
    setUrlError(errorMessage);
    updateHelper('url', value, 0); // 0 is an index
  };

  const onDeepLinkSelect = (value) => {
    setCtaDeepLinkValue(value);
    let errorMessage = false;
    if (!isUrl(value)) {
      errorMessage = formatMessage(messages.ctaWebsiteUrlErrorMessage);
    }
    setUrlError(errorMessage);
    updateHelper('url', value, 0); // 0 is an index
  };

  const ctaSaveDisabled = (index) => {
    const { urlType, text, url } = ctaData[index] || {};
    if (text === "" || buttonError) {
      return true;
    } else if (urlType === DEEP_LINK && (ctaDeepLinkValue === "" || urlError)) {
      return true;
    } else if (urlType === EXTERNAL_URL && (url === "" || urlError)) {
      return true;
    }
  };

  const isSavedCta = (index, saved) => {
    updateHelper("isSaved", saved, index);
  };

  const renderedContent = () => {
    const renderArray = [];
    ctaData?.forEach((cta) => {
      const { index, text, url, urlType, isSaved } = cta || {};

      const onButtonTagSelect = (data) => {
        const newUrl = `${url}{{${data}}}`;
        updateHelper('url', newUrl, index);
      };

      //this is to display buttons after they are saved, in both create and edit mode.
      if (isSaved) {
        renderArray.push(
          <CapRow
            className="cap-inapp-saved-cta"
            align="middle"
            type="flex"
          >
            <CapRow className="inapp-cta-row">
              <CapColumn>
                <CapIcon size="s" type={'launch'} className="btn-icon" />
              </CapColumn>
              <CapColumn className="btn-text">
                <CapLabel type="label2" className="inapp-saved-cta-button-text">
                  {text}
                </CapLabel>
              </CapColumn>
            </CapRow>
            <CapColumn >
              {urlType === DEEP_LINK ?
                <CapTag className="cta-type-label">{formatMessage(messages.urlDeepLink)}</CapTag>
                : <CapTag className="cta-type-label">{formatMessage(messages.urlExternalLink)}</CapTag>}
            </CapColumn>
            <CapColumn>
              {urlType === DEEP_LINK ? selectedDeepLink?.label : ''}
            </CapColumn>
            {(
              <CapRow className="cta-action-grp">
                <CapColumn
                  className="inapp-saved-cta-edit-icon"
                  onClick={() => isSavedCta(index, false)}
                >
                  <CapIcon size="s" type="edit" className="cta-action" />
                </CapColumn>
                <CapColumn onClick={() => deleteHandler(index)} className="cta-del-icon">
                  <CapIcon size="s" type="delete" className="cta-action" ariaLabel="delete-cta-icon" />
                </CapColumn>
              </CapRow>
            )}
          </CapRow>
        );
      } else {
        //this is to display buttons before they are saved, only in create mode.
        renderArray.push(
          <CapRow
            className="cap-inapp-cta"
            id={`cap-inapp-cta-${index}`}
          >
            <CapRow className="inapp-cta-buttons">
              <CapColumn span={12} >
                {/* Type of link */}
                <CapHeading type="h4" className="cta-label">
                  {formatMessage(messages.ctaType)}
                </CapHeading>
                <CapSelect
                  id="inapp-cta-type"
                  options={CTA_OPTIONS || []}
                  onChange={(value) => onUrlTypeChange(value, index)}
                  value={urlType}
                />
              </CapColumn>
              <CapColumn span={12}>
                {/* 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="inapp-cta-button-text"
                  onChange={onButtonTextChange}
                  placeholder={formatMessage(messages.ctaButtonTextPlaceholder)}
                  value={text}
                  maxLength={BTN_MAX_LENGTH}
                  errorMessage={buttonError}
                />
                {renderLength(text.length, BTN_MAX_LENGTH)}
              </CapColumn>
            </CapRow>
            {urlType === DEEP_LINK && (
              <>
                <CapHeading type="h4">
                  {formatMessage(messages.urlDeepLink)}
                </CapHeading>
                <CapSelect
                  id="inapp-deep-link-type"
                  placeholder={formatMessage(messages.ctaDeepLinkOptionsPlaceholder)}
                  options={deepLink || []}
                  onChange={onDeepLinkSelect}
                  value={ctaDeepLinkValue}
                />
              </>

            )}
            {urlType === EXTERNAL_URL && (
              <>
                <CapTagListWithInput
                  inputId="inapp-cta-external-link"
                  inputValue={url}
                  inputOnChange={onUrlChange}
                  inputPlaceholder={formatMessage(messages.ctaExternalLinkPlaceholder)}
                  inputSize="large"
                  inputMaxLength={URL_MAX_LENGTH}
                  inputErrorMessage={urlError}
                  headingText={formatMessage(messages.urlExternalLink)}
                  headingStyle={{ marginTop: '3%',marginRight: '65%'}}
                  moduleFilterEnabled={location?.query?.type !== "embedded"}
                  onTagSelect={onButtonTagSelect}
                  onContextChange={onContextChange}
                  location={location}
                  tags={tags || []}
                  injectedTags={injectedTags || {}}
                  selectedOfferDetails={selectedOfferDetails}
                />
              </>
            )}
            <CapRow className="inapp-cta-save-delete-btn">
              <CapTooltip
                title={
                  ctaSaveDisabled(index)
                    ? formatMessage(messages.ctaSaveDisabled)
                    : ""
                }
                placement={"bottom"}
              >
                <div className="button-disabled-tooltip-wrapper">
                  <CapButton
                    onClick={() => isSavedCta(index, true)}
                    disabled={ctaSaveDisabled(index)}
                    className="inapp-cta-save-btn"
                  >
                    {formatMessage(globalMessages.save)}
                  </CapButton>
                </div>
              </CapTooltip>
              <CapButton
                onClick={() => deleteHandler(index)}
                className="inapp-cta-delete-btn"
                type="secondary"
              >
                {formatMessage(globalMessages.delete)}
              </CapButton>
            </CapRow>
          </CapRow>
        );
      }
    });
    return renderArray;
  };

  return renderedContent();
};

export default injectIntl(CapInAppCTA);
