import React, { useCallback } from "react";
import PropTypes from "prop-types";
import { FormattedMessage } from "react-intl";
import CapRow from "@capillarytech/cap-ui-library/CapRow";
import CapInput from "@capillarytech/cap-ui-library/CapInput";
import CapColumn from "@capillarytech/cap-ui-library/CapColumn";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapError from "@capillarytech/cap-ui-library/CapError";
import CapDivider from "@capillarytech/cap-ui-library/CapDivider";
import CapSelect from "@capillarytech/cap-ui-library/CapSelect";
import CapCheckbox from "@capillarytech/cap-ui-library/CapCheckbox";
import CapLabel from "@capillarytech/cap-ui-library/CapLabel";
import CapInfoNote from "@capillarytech/cap-ui-library/CapInfoNote";
import TagList from "../../TagList";
import {
  ANDROID,
  IOS,
  MEDIA_TYPES_OPTIONS,
  LINK_TYPE_OPTIONS,
  DEEP_LINK,
  EXTERNAL_LINK,
  CAROUSEL,
} from "../constants";
import messages from "../messages";
import MediaUploaders from "./MediaUploaders";
import CtaButtons from "./CtaButtons";
import { hasPersonalizationTags } from "../../../utils/commonUtils";

const PlatformContentFields = ({
  deviceType,
  content,
  errors,
  handlers,
  tagListProps,
  mediaUploaderProps,
  ctaButtonProps,
  linkProps,
  sameContent,
  formatMessage,
  location,
  tags,
  injectedTags,
  selectedOfferDetails,
  // new prop to disable personalization features for anonymous users
  restrictPersonalization = false,
}) => {
  const { title: titleError, message: messageError } = errors;

  const titleErrorToShow = titleError || (restrictPersonalization && hasPersonalizationTags(content.title)
    ? formatMessage(messages.personalizationTagsErrorMessage)
    : "");
  const messageErrorToShow = messageError || (restrictPersonalization && hasPersonalizationTags(content.message)
    ? formatMessage(messages.personalizationTagsErrorMessage)
    : "");
  const {
    handleTitleChange,
    handleMessageChange,
    handleMediaTypeChange,
    handleActionOnClickChange,
    handleLinkTypeChange,
    handleDeepLinkChange,
    handleDeepLinkKeysChange,
    handleExternalLinkChange,
    onTagSelect,
    handleOnTagsContextChange,
  } = handlers;

  const {
    deepLink,
    deepLinkValue,
    deepLinkKeysValue,
    externalLinkValue,
  } = linkProps;

  // Get the selected deep link object to extract keys
  // Try exact match first, then try match without query parameters
  let selectedDeepLink = deepLink?.find((link) => link?.value === deepLinkValue);

  // If no exact match, try to find match without query parameters
  if (!selectedDeepLink && deepLinkValue?.includes('?')) {
    const baseDeepLinkValue = deepLinkValue.split('?')[0];
    selectedDeepLink = deepLink?.find((link) => link?.value === baseDeepLinkValue);
  }

  const deepLinkKeysFromSelection = selectedDeepLink?.keys;

  // Handle deep link keys value - could be array or string
  let deepLinkKeysArray = [];
  if (Array.isArray(deepLinkKeysValue)) {
    deepLinkKeysArray = deepLinkKeysValue;
  } else if (deepLinkKeysValue) {
    deepLinkKeysArray = [deepLinkKeysValue];
  }

  let deepLinkKeysFromSelectionArray = [];
  if (Array.isArray(deepLinkKeysFromSelection)) {
    deepLinkKeysFromSelectionArray = deepLinkKeysFromSelection;
  } else if (deepLinkKeysFromSelection) {
    deepLinkKeysFromSelectionArray = [deepLinkKeysFromSelection];
  }

  const onTitleChange = useCallback(
    ({ target: { value } }) => {
      handleTitleChange(deviceType, value);
    },
    [handleTitleChange, deviceType]
  );

  const onMessageChange = useCallback(
    ({ target: { value } }) => {
      handleMessageChange(deviceType, value);
    },
    [handleMessageChange, deviceType]
  );

  const onMediaTypeChange = useCallback(
    (value) => {
      handleMediaTypeChange(deviceType, value);
    },
    [handleMediaTypeChange, deviceType]
  );

  const onActionOnClickChange = useCallback(
    (e) => handleActionOnClickChange(deviceType, e.target.checked),
    [handleActionOnClickChange, deviceType]
  );

  const onLinkTypeChange = useCallback(
    (value) => handleLinkTypeChange(deviceType, value),
    [handleLinkTypeChange, deviceType]
  );

  const onDeepLinkChange = useCallback((value) => handleDeepLinkChange(value), [
    handleDeepLinkChange,
  ]);

  const onDeepLinkKeysChange = useCallback(
    ({ target: { value } }) => {
      // Parse comma-separated values into array
      const keysArray = value?.split(',')?.map((key) => key?.trim())?.filter((key) => key?.length > 0);
      handleDeepLinkKeysChange(keysArray);
    },
    [handleDeepLinkKeysChange]
  );

  const onExternalLinkChange = useCallback(
    (e) => handleExternalLinkChange(e.target.value),
    [handleExternalLinkChange]
  );

  const getTagList = useCallback(
    (index) => {
      const disableMsg = restrictPersonalization ? formatMessage(messages.personalizationNotSupportedAnonymous) : undefined;
      return (
        <TagList
          {...tagListProps}
          disabled={restrictPersonalization}
          disableTooltipMsg={disableMsg}
          onTagSelect={(value) => onTagSelect(value, index)}
          onContextChange={handleOnTagsContextChange}
        />
      );
    },
    [tagListProps, onTagSelect, handleOnTagsContextChange, restrictPersonalization, formatMessage]
  );

  const onButtonTagSelect = useCallback(
    (value) => {
      const newUrl = `${externalLinkValue}{{${value}}}`;
      handleExternalLinkChange(newUrl);
    },
    [handleExternalLinkChange, externalLinkValue]
  );

  return (
    <>
      {sameContent && (
        <CapInfoNote message={formatMessage(messages.sameContentNote)} />
      )}
      <CapRow className="content-fields">
        <CapRow className="creatives-mpush-title">
          <CapColumn className="mpush-title-main">
            <CapHeading type="h3" className="mpush-title">
              <FormattedMessage {...messages.title} />
            </CapHeading>
            {getTagList(0)}
          </CapColumn>
          <CapInput
            id={`mobile-push-title-name-input-${deviceType}`}
            onChange={onTitleChange}
            placeholder={formatMessage(messages.titlePlaceholder)}
            value={content.title}
            size="default"
            isRequired
            errorMessage={
              titleErrorToShow && (
                <CapError className="mobile-push-template-title-error">
                  {titleErrorToShow}
                </CapError>
              )
            }
          />
        </CapRow>

        <CapRow className="creatives-mpush-message">
          <CapColumn className="mpush-message-main">
            <CapHeading type="h3" className="mpush-message">
              <FormattedMessage {...messages.message} />
            </CapHeading>
            {getTagList(1)}
          </CapColumn>
          <CapInput.TextArea
            id={`mobile-push-message-name-input-${deviceType}`}
            onChange={onMessageChange}
            placeholder={formatMessage(messages.messagePlaceholder)}
            value={content.message}
            size="default"
            isRequired
            errorMessage={
              messageErrorToShow && (
                <CapError className="mobile-push-template-message-error">
                  {messageErrorToShow}
                </CapError>
              )
            }
            autosize={{ minRows: 3, maxRows: 5 }}
          />
        </CapRow>
        <CapDivider />
        <CapRow className="creatives-mpush-media">
          <CapHeading type="h3" className="mpush-media-type">
            <FormattedMessage {...messages.mediaType} />
          </CapHeading>
          <CapSelect.CapCustomSelect
            width="100%"
            className="margin-t-4"
            options={MEDIA_TYPES_OPTIONS}
            value={content.mediaType}
            onChange={onMediaTypeChange}
          />
          <MediaUploaders
            mediaType={content.mediaType}
            {...mediaUploaderProps}
            formatMessage={formatMessage}
            location={location}
            tags={tags}
            injectedTags={injectedTags}
            selectedOfferDetails={selectedOfferDetails}
            handleOnTagsContextChange={handleOnTagsContextChange}
          />
        </CapRow>
        {content?.mediaType !== CAROUSEL && (
          <>
            <CapDivider />
            <CapRow className="creatives-mpush-actions">
              <CapRow className="mpush-actions-main">
                <CapHeading type="h3" className="mpush-actions">
                  <FormattedMessage {...messages.buttonsAndLinks} />
                </CapHeading>
                <CapLabel className="optional-text">
                  <FormattedMessage {...messages.optionalText} />
                </CapLabel>
              </CapRow>
              <CapCheckbox
                checked={content.actionOnClick}
                onChange={onActionOnClickChange}
                className="action-on-click-checkbox"
              >
                <FormattedMessage {...messages.actionOnClickBody} />
              </CapCheckbox>
              <CapRow>
                <CapLabel className="action-description">
                  <FormattedMessage {...messages.actionDescription} />
                </CapLabel>
              </CapRow>
              {content.actionOnClick && (
                <CapRow style={{ display: "flex", justifyContent: "space-around" }}>
                  <CapColumn span={6}>
                    <CapHeading type="h4" className="buttons-heading">
                      <FormattedMessage {...messages.linkType} />
                    </CapHeading>
                    <CapSelect.CapCustomSelect
                      options={LINK_TYPE_OPTIONS}
                      value={content.linkType}
                      onChange={onLinkTypeChange}
                      key="mobile-push-link-type"
                      selectPlaceholder={formatMessage(messages.selectDeepLink)}
                    />
                  </CapColumn>
                  {content.linkType === DEEP_LINK && (
                    <CapColumn span={14}>
                      <CapHeading type="h4" className="buttons-heading">
                        {formatMessage(messages.deepLink)}
                      </CapHeading>
                      <CapSelect.CapCustomSelect
                        options={(() => {
                          const options = [...(deepLink || [])];
                          // If the current value is not in the options, add it
                          if (deepLinkValue && !options.find((opt) => opt.value === deepLinkValue)) {
                            options.push({
                              value: deepLinkValue,
                              label: deepLinkValue,
                            });
                          }
                          return options;
                        })()}
                        value={deepLinkValue}
                        onChange={onDeepLinkChange}
                        key="mobile-push-deep-link-type"
                        placeholder={formatMessage(messages.selectDeepLink)}
                        style={{ marginTop: "10px" }}
                      />
                    </CapColumn>
                  )}
                  {content.linkType === EXTERNAL_LINK && (
                    <CapColumn span={14}>
                      <CapRow style={{ display: "flex" }}>
                        <CapHeading type="h4" className="buttons-heading">
                          {formatMessage(messages.externalLink)}
                        </CapHeading>
                        <TagList
                          moduleFilterEnabled={
                            location?.query?.type !== "embedded"
                          }
                          label={formatMessage(messages.addLabels)}
                          onTagSelect={onButtonTagSelect}
                          onContextChange={handleOnTagsContextChange}
                          location={location}
                          tags={tags}
                          injectedTags={injectedTags}
                          selectedOfferDetails={selectedOfferDetails}
                          disabled={restrictPersonalization}
                          disableTooltipMsg={
                            restrictPersonalization ? formatMessage(messages.personalizationNotSupportedAnonymous) : undefined
                          }
                        />
                      </CapRow>
                      <CapInput
                        id="mobile-push-external-link-input"
                        onChange={onExternalLinkChange}
                        placeholder={formatMessage(messages.enterExternalLink)}
                        value={externalLinkValue}
                        size="default"
                        isRequired
                        errorMessage={
                          errors.externalLink && (
                            <CapError className="mobile-push-external-link-error">
                              {errors.externalLink}
                            </CapError>
                          )
                        }
                      />
                    </CapColumn>
                  )}
                </CapRow>
              )}
              {content?.actionOnClick && content?.linkType === DEEP_LINK && deepLinkValue && (deepLinkKeysFromSelectionArray?.length > 0 || deepLinkKeysArray?.length > 0) && (
                <CapRow style={{ marginTop: "10px", left: "6%", width: '115%'}}>
                  <CapColumn span={14}>
                    <CapHeading type="h4" className="deep-link-keys-heading">
                      {formatMessage(messages.deepLinkKeys)}
                    </CapHeading>
                    <CapLabel type="label2" className="deep-link-keys-value">
                      {(() => {
                        if (deepLinkKeysFromSelectionArray?.length > 0) {
                          return deepLinkKeysFromSelectionArray?.join(', ');
                        }
                        if (deepLinkKeysArray?.length > 0) {
                          return deepLinkKeysArray?.join(', ');
                        }
                        return '';
                      })()}
                    </CapLabel>
                    <CapInput
                      id="mobile-push-deep-link-keys-input"
                      onChange={onDeepLinkKeysChange}
                      placeholder={formatMessage(messages.deepLinkKeysPlaceholder, { key: deepLinkKeysFromSelectionArray?.join(', ')})}
                      value={Array.isArray(deepLinkKeysValue) ? deepLinkKeysValue?.join(', ') : (deepLinkKeysValue || "")}
                      size="default"
                      style={{ marginTop: "10px" }}
                      error={errors?.deepLinkKeys}
                    />
                  </CapColumn>
                </CapRow>
              )}
            </CapRow>
            <CtaButtons {...ctaButtonProps} />
          </>
        )}
      </CapRow>
    </>
  );
};

PlatformContentFields.propTypes = {
  deviceType: PropTypes.oneOf([ANDROID, IOS]).isRequired,
  content: PropTypes.object.isRequired,
  errors: PropTypes.shape({
    title: PropTypes.string,
    message: PropTypes.string,
    externalLink: PropTypes.string,
    deepLinkKeys: PropTypes.string,
  }).isRequired,
  handlers: PropTypes.object.isRequired,
  tagListProps: PropTypes.object.isRequired,
  mediaUploaderProps: PropTypes.object.isRequired,
  ctaButtonProps: PropTypes.object.isRequired,
  linkProps: PropTypes.object.isRequired,
  sameContent: PropTypes.bool.isRequired,
  formatMessage: PropTypes.func.isRequired,
  restrictPersonalization: PropTypes.bool,
};

PlatformContentFields.defaultProps = {
  restrictPersonalization: false,
};

export default PlatformContentFields;
