import React, { useCallback } from "react";
import PropTypes from "prop-types";
import { injectIntl, intlShape } from "react-intl";
import cloneDeep from "lodash/cloneDeep";
import isEmpty from "lodash/isEmpty";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapHeader from "@capillarytech/cap-ui-library/CapHeader";
import CapInput from "@capillarytech/cap-ui-library/CapInput";
import CapRadioGroup from "@capillarytech/cap-ui-library/CapRadioGroup";
import CapRow from "@capillarytech/cap-ui-library/CapRow";
import CapColumn from "@capillarytech/cap-ui-library/CapColumn";
import CapLabel from "@capillarytech/cap-ui-library/CapLabel";
import CapLink from "@capillarytech/cap-ui-library/CapLink";
import CapError from "@capillarytech/cap-ui-library/CapError";
import CapCheckbox from "@capillarytech/cap-ui-library/CapCheckbox";
import CapSelect from "@capillarytech/cap-ui-library/CapSelect";
import CapAskAira from "@capillarytech/cap-ui-library/CapAskAira";
import TagList from "../../v2Containers/TagList";
import messages from "./messages";
import {
  ANDROID,
  INAPP_MEDIA_TYPES,
  INAPP_BUTTON_TYPES,
  ALLOWED_IMAGE_EXTENSIONS_REGEX,
  INAPP_IMG_SIZE,
  INITIAL_CTA_DATA,
  MEDIA_RADIO_OPTIONS,
  BUTTON_RADIO_OPTIONS,
} from "../../v2Containers/InApp/constants";
import { INAPP } from "../../v2Containers/CreativesContainer/constants";
import CapImageUpload from "../CapImageUpload";
import CapInAppCTA from "../CapInAppCTA";
import './index.scss';

const CapDeviceContent = (props) => {
  const {
    intl,
    location,
    injectedTags,
    selectedOfferDetails,
    panes,
    actions,
    editData,
    isFullMode,
    inAppImageSrc,
    setInAppImageSrc,
    isEditFlow,
    ctaData,
    setCtaData,
    buttonType,
    setButtonType,
    templateMediaType,
    setTemplateMediaType,
    title,
    setTitle,
    templateMessageError,
    templateMessage,
    setTemplateMessage,
    setTemplateMessageError,
    addActionLink,
    setAddActionLink,
    deepLink,
    deepLinkValue,
    setDeepLinkValue,
    onCopyTitleAndContent,
    isOtherDeviceSupported,
    tags,
    onTagSelect,
    handleOnTagsContextChange,
    templateDescErrorHandler,
    templateTitleError,
    setTemplateTitleError,
    isAiContentBotDisabled,
  } = props || {};
  const { TextArea } = CapInput;
  const { formatMessage } = intl;

  const isAndroid = panes === ANDROID;
  const isMediaTypeImage = INAPP_MEDIA_TYPES.IMAGE === templateMediaType;
  const isBtnTypeCta = buttonType === INAPP_BUTTON_TYPES.CTA;
  const onTemplateMessageChange = ({ target: { value } }) => {
    let error = templateDescErrorHandler(value);
    if (value === '') {
      error = formatMessage(messages.emptyTemplateMessageErrorMessage);
    }
    setTemplateMessage(value);
    setTemplateMessageError(error);
  };

  const setUpdateInAppImageSrc = useCallback(
    (filePath) => {
      const templateType = 0;
      setInAppImageSrc(filePath);
      actions.clearInAppAsset(templateType);
    },
    [inAppImageSrc]
  );
  const updateOnInAppImageReUpload = useCallback(() => {
    setInAppImageSrc("");
  }, [inAppImageSrc]);

  const updateHandler = (ctaDataParam, index) => {
    setCtaData((prevState) => {
      const clonedCta = cloneDeep(prevState);
      clonedCta[index] = ctaDataParam;
      return clonedCta;
    });
  };

  // function to delete CTA button
  const deleteHandler = (index) => {
    setCtaData((prevState) => {
      const clonedCta = cloneDeep(prevState);
      const filteredCta = clonedCta.filter((cta) => cta.index !== index);
      if (filteredCta.length === 1) {
        // updates the index of the cta buttons present in case there's a cta button deleted
        filteredCta[0].index = 0;
      }
      if (isEmpty(filteredCta)) {
        onChangeButtonType({target: { value: INAPP_BUTTON_TYPES.NONE } });
      }
      return filteredCta;
    });
  };

  const onTitleChange = ({ target: { value } }) => {
    let error = templateDescErrorHandler(value);
    if (value === '') {
      error = formatMessage(messages.emptyTemplateMessageErrorMessage);
    }
    setTitle(value);
    setTemplateTitleError(error);
  };

  const onTemplateMediaTypeChange = ({ target: { value } }) => {
    setTemplateMediaType(value);
  };

  const onChangeButtonType = ({ target: { value } }) => {
    setButtonType(value);
    setCtaData(INITIAL_CTA_DATA);
  };

  const onActionLinkCheckBoxChange = () => {
    setAddActionLink(!addActionLink);
    setDeepLinkValue('');
  };

  const uploadInAppAsset = (file, type, fileParams) => {
    actions.uploadInAppAsset(file, type, fileParams, 0);
  };

  const getTagList = (index) => (
    <TagList
      moduleFilterEnabled={
        location && location?.query && location?.query?.type !== "embedded"
      }
      label={formatMessage(messages.addLabel)}
      onTagSelect={(value) => onTagSelect(value, index)}
      onContextChange={handleOnTagsContextChange}
      location={location}
      tags={tags || []}
      injectedTags={injectedTags || {}}
      selectedOfferDetails={selectedOfferDetails}
    />
  );

  return (
    <>
      <CapRow className="creatives-device-content">
        {isOtherDeviceSupported && (
          <CapLink
            title={isAndroid
              ? formatMessage(messages.copyContentFromIOS)
              : formatMessage(messages.copyCotentFromAndroid)}
            className="inapp-copy-content"
            onClick={onCopyTitleAndContent}
          />
        )}
        <CapRow className="creatives-inapp-title">
          <CapColumn
            className="inapp-content-main"
          >
            <CapHeading type="h5" className="inapp-title">
              {formatMessage(messages.title)}
            </CapHeading>
            {getTagList(0)}
            {/* here 0 signifies the tags for template title */}
          </CapColumn>
          <CapInput
            id="inapp-title-name-input"
            onChange={onTitleChange}
            placeholder={formatMessage(messages.titlePlaceholder)}
            value={title}
            size="default"
            isRequired
            errorMessage={templateTitleError && (
              <CapError className="inapp-template-message-error">
                {templateTitleError}
              </CapError>
            )}
          />
        </CapRow>
        <CapRow className="creatives-inapp-media">
          <CapRow className="inapp-content-media">
            <CapHeading type="h5" className="inapp-media-header">
              {formatMessage(messages.mediaLabel)}
            </CapHeading>
            <CapRadioGroup
              id="inapp-media-radio"
              options={MEDIA_RADIO_OPTIONS}
              value={templateMediaType}
              onChange={onTemplateMediaTypeChange}
              className="inapp-media-radio"
            />
          </CapRow>
        </CapRow>
        <CapRow className={`creatives-inapp-message ${!isMediaTypeImage && "message-bottom-margin"}`}>
          <CapColumn
            className="inapp-message-header"
          >
            <CapHeading type="h5" className="inapp-message-header-style">
              {formatMessage(messages.message)}
            </CapHeading>
            {getTagList(1)}
            {/* here 1 signifies the tags for template message */}
          </CapColumn>
          <div className="inapp-create-template-message-input-wrapper">
            <TextArea
              id="inapp-create-template-message-input"
              className="inapp-create-template-message-input"
              placeholder={formatMessage(messages.textAreaInputPlaceholder)}
              onChange={onTemplateMessageChange}
              value={templateMessage || ""}
              autosize={{ minRows: 5, maxRows: 5 }}
              errorMessage={
                templateMessageError && (
                  <CapError className="inapp-template-message-error">
                    {templateMessageError}
                  </CapError>
                )
              }
            />
            {!isAiContentBotDisabled && (
              <CapAskAira.ContentGenerationBot
                text={templateMessage || ""}
                setText={(text) => {
                  onTemplateMessageChange({ target: { value: text } });
                }}
                iconPlacement="float-br"
                iconSize="1.6rem"
                rootStyle={{
                  bottom: "0.2rem",
                  right: "0.2rem",
                  left: "auto",
                  position: "absolute",
                }}
              />
            )}
          </div>
          {isMediaTypeImage && (
            <>
              <CapHeading type="h4" className="cover-img">
                {formatMessage(messages.coverImage)}
              </CapHeading>
              <CapImageUpload
                allowedExtensionsRegex={ALLOWED_IMAGE_EXTENSIONS_REGEX}
                imgSize={INAPP_IMG_SIZE}
                uploadAsset={uploadInAppAsset}
                isFullMode={isFullMode}
                imageSrc={inAppImageSrc}
                updateImageSrc={setUpdateInAppImageSrc}
                updateOnReUpload={updateOnInAppImageReUpload}
                index={0}
                className="cap-custom-image-upload"
                key="inapp-uploaded-image"
                imageData={editData}
                channel={INAPP}
                channelSpecificStyle={!isFullMode}
              />
            </>
          )}
        </CapRow>
      </CapRow>
      <CapRow className="inapp-action-link">
        <CapCheckbox onChange={onActionLinkCheckBoxChange} checked={addActionLink} />
        <CapRow className="inapp-render-heading">
          <CapHeader
            title={(
              <CapRow type="flex">
                <CapHeading type="h4">
                  {formatMessage(messages.addActionLink)}
                </CapHeading>
              </CapRow>
            )}
            description={<CapLabel type="label3">{formatMessage(messages.addActionLinkDesc)}</CapLabel>}
          />
          {addActionLink && (
            <CapRow className="inapp-action-deep-link">
              <CapHeading type="h4">
                {formatMessage(messages.actionDeepLink)}
              </CapHeading>
              <CapSelect
                id="inapp-add-action-link-type"
                placeholder={formatMessage(messages.deepLinkOptionsPlaceholder)}
                options={deepLink || []}
                value={deepLinkValue}
                onChange={(value) => {
                  setDeepLinkValue(value);
                }}
              />
            </CapRow>
          )}
        </CapRow>
      </CapRow>
      <CapRow className="inapp-cta-button">
        <CapHeader
          className="inapp-render-heading-cta-button"
          title={(
            <CapRow type="flex">
              <CapHeading type="h4">
                {formatMessage(messages.btnLabel)}
              </CapHeading>
              <CapHeading
                type="h6"
                className="inapp-optional-label"
              >
                {formatMessage(messages.optional)}
              </CapHeading>
            </CapRow>
          )}
          description={<CapLabel type="label3">{formatMessage(messages.btnDesc)}</CapLabel>}
        />
        <CapRadioGroup
          options={BUTTON_RADIO_OPTIONS}
          value={buttonType}
          onChange={onChangeButtonType}
          disabled={!isAndroid}
          className="inapp-btn-radio-group"
        />
        {isBtnTypeCta && (
          <CapInAppCTA
            ctaData={ctaData}
            updateHandler={updateHandler}
            deleteHandler={deleteHandler}
            isEditFlow={isEditFlow}
            deepLink={deepLink}
            onContextChange={handleOnTagsContextChange}
            location={location}
            tags={tags}
            injectedTags={injectedTags}
            selectedOfferDetails={selectedOfferDetails}
          />
        )}
      </CapRow>
    </>
  );
};

CapDeviceContent.propTypes = {
  intl: intlShape.isRequierd,
  location: PropTypes.string,
  injectedTags: PropTypes.object,
  selectedOfferDetails: PropTypes.array,
  panes: PropTypes.string,
};

export default injectIntl(CapDeviceContent);
