import React, { useState, useEffect, useRef } 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 CapSelect from "@capillarytech/cap-ui-library/CapSelect";
import CapTag from '@capillarytech/cap-ui-library/CapTag';
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 { isDeepLink } from "../../v2Containers/MobilePushNew/utils";
import {
    BTN_MAX_LENGTH,
    DEEP_LINK,
    EXTERNAL_URL,
    CTA_OPTIONS,
    URL_MAX_LENGTH,
} from "./constants";
import { PRIMARY } from "../../v2Containers/MobilePushNew/constants";
import { URL } from "../../v2Containers/Whatsapp/constants";
import TagList from "../../v2Containers/TagList";
import CapTagListWithInput from "../CapTagListWithInput";

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

    const [urlError, setUrlError] = useState(false);
    const [buttonError, setButtonError] = useState(false);
    const [deepLinkKeysError, setDeepLinkKeysError] = useState(false);
    const [ctaDeepLinkValue, setCtaDeepLinkValue] = useState(ctaData[0]?.url || "");
    const [ctaDeepLinkKeysValue, setCtaDeepLinkKeysValue] = useState(ctaData[0]?.deepLinkKeys || []);
    const [localUrlValues, setLocalUrlValues] = useState({});
    // Track which URLs have been manually cleared to prevent restoration
    const clearedUrlsRef = useRef(new Set());
    const selectedDeepLink = deepLink?.find((link) => link?.value === ctaData[0]?.url);
    const deepLinkKeysFromSelection = selectedDeepLink?.keys;
    
    // Handle deep link keys value - could be array or string
    let deepLinkKeysArray = [];
    if (Array.isArray(ctaDeepLinkKeysValue)) {
      deepLinkKeysArray = ctaDeepLinkKeysValue;
    } else if (ctaDeepLinkKeysValue) {
      deepLinkKeysArray = [ctaDeepLinkKeysValue];
    }

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

    useEffect(() => {
        const urlValues = {};
        ctaData.forEach((cta) => {
            if (cta && typeof cta.index !== 'undefined') {
                // Don't restore URLs that have been manually cleared
                const wasManuallyCleared = clearedUrlsRef.current.has(cta.index);
                urlValues[cta.index] = wasManuallyCleared ? '' : (cta.url || '');
                

            }
        });
        setLocalUrlValues(urlValues);
    }, [ctaData]);

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

    const renderLength = (len, max) => (
        <CapHeading
            type="label1"
            className="mpush-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) => {
        // Mark this URL as manually cleared to prevent restoration
        clearedUrlsRef.current.add(index);
        
        // Clear the URL field when switching between link types
        updateHelper('url', '', index);
        
        // Immediately clear the local URL state for this button
        setLocalUrlValues(prev => ({
            ...prev,
            [index]: ''
        }));
        
        // Also clear the local deep link state
        setCtaDeepLinkValue('');
        // Clear any URL errors
        setUrlError(false);
        // Update the URL type
        updateHelper('urlType', value, index);
    };

    const onUrlChange = ({ target }) => {
        const { value, dataset } = target;
        const index = parseInt(dataset.index, 10);
        
        // If user is typing a new URL, remove from cleared set
        if (value && value?.trim() !== '') {
            clearedUrlsRef.current.delete(index);
        }
        
        let errorMessage = false;
        if (!isUrl(value)) {
            errorMessage = formatMessage(messages.ctaWebsiteUrlErrorMessage);
        }
        setUrlError(errorMessage);
        
        // Update local state immediately for instant UI feedback
        setLocalUrlValues(prev => ({
            ...prev,
            [index]: value
        }));
        
        updateHelper('url', value, index);
    };

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

    const onDeepLinkKeysChange = ({ target }) => {
        const { value, dataset } = target;
        const index = parseInt(dataset.index, 10);
        // Parse comma-separated values into array
        const keysArray = value?.split(',')?.map((key) => key?.trim())?.filter((key) => key?.length > 0);
        setCtaDeepLinkKeysValue(keysArray);
        setDeepLinkKeysError(keysArray.length === 0);
        updateHelper('deepLinkKeys', keysArray, 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 === DEEP_LINK && ctaDeepLinkValue && deepLinkKeysFromSelectionArray?.length > 0 && (!Array.isArray(ctaDeepLinkKeysValue) || ctaDeepLinkKeysValue?.length === 0 || deepLinkKeysError)) {
            return true;
        } else if (urlType === EXTERNAL_URL && (url === "" || urlError)) {
            return true;
        }
    };

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

    const renderedContent = () => {
        const renderArray = [];
        const filteredCtaData = ctaData?.filter((cta) => {
            if (buttonType === PRIMARY) {
                return cta?.index === 0;
            } else {
                return cta?.index === 1;
            }
        });
        
        filteredCtaData?.forEach((cta) => {
            const { index, text, urlType, isSaved } = cta || {};
            const onButtonTagSelect = (data) => {
                const newUrl = `${localUrlValues[index]}{{${data}}}`;
                updateHelper('url', newUrl, index);
            };
            if (isSaved) {
                renderArray.push(
                    <CapRow
                        className="cap-mpush-saved-cta"
                        align="middle"
                        type="flex"
                    >
                        <CapRow className="mpush-cta-row">
                            <CapColumn>
                                <CapIcon size="s" type={'launch'} />
                            </CapColumn>
                            <CapColumn className="btn-text">
                                <CapLabel type="label2" className="mpush-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>
                        <CapColumn>
                        </CapColumn>
                        {(
                            <CapRow className="cta-action-grp">
                                <CapColumn
                                    className="mpush-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 {
                renderArray.push(
                    <CapRow
                        className="cap-mpush-cta"
                        id={`cap-mpush-cta-${index}`}
                    >
                        <CapColumn>
                            <CapHeading type="h4" className="cta-label">
                                {buttonType === PRIMARY ? formatMessage(messages.ctaButtonText) : formatMessage(messages.ctaButtonTextSecondary)}
                            </CapHeading>
                            <CapInput
                                id={index}
                                onChange={onButtonTextChange}
                                placeholder={formatMessage(messages.ctaButtonTextPlaceholder)}
                                value={text}
                                maxLength={BTN_MAX_LENGTH}
                                errorMessage={buttonError}
                            />
                            {renderLength(text.length, BTN_MAX_LENGTH)}
                        </CapColumn>
                        <CapColumn className="mpush-cta-buttons">
                            <CapRow style={{ width: '30%', marginRight: '10px' }}>
                                <CapHeading type="h4" className="cta-label">
                                    {formatMessage(messages.ctaType)}
                                </CapHeading>
                                <CapSelect.CapCustomSelect
                                    id="mpush-cta-type"
                                    key="mpush-cta-type"
                                    options={CTA_OPTIONS || []}
                                    onChange={(value) => onUrlTypeChange(value, index)}
                                    value={urlType}
                                />
                            </CapRow>
                            {urlType === DEEP_LINK && (
                                <CapRow style={{ width: '70%' }}>
                                    <CapHeading type="h4" className="cta-deep-link-label">
                                        {formatMessage(messages.urlDeepLink)}
                                    </CapHeading>
                                    <CapSelect.CapCustomSelect
                                        id="mpush-deep-link-type"
                                        key="mpush-deep-link-type"
                                        placeholder={formatMessage(messages.ctaDeepLinkOptionsPlaceholder)}
                                        options={deepLink || []}
                                        onChange={(value) => onDeepLinkSelect(value, index)}
                                        value={ctaDeepLinkValue}
                                    />
                                </CapRow>
                            )}
                            {urlType === EXTERNAL_URL && (
                                <CapTagListWithInput
                                    inputId="mpush-cta-external-link"
                                    inputValue={localUrlValues[index] || ''}
                                    inputOnChange={onUrlChange}
                                    inputPlaceholder={formatMessage(messages.ctaExternalLinkPlaceholder)}
                                    inputSize="large"
                                    inputMaxLength={URL_MAX_LENGTH}
                                    inputErrorMessage={urlError}
                                    headingText={formatMessage(messages.urlExternalLink)}
                                    headingStyle={{ marginTop: '3%', marginRight: '50%'}}
                                    containerStyle={{ width: '70%', marginTop: '-0.625rem' }}
                                    moduleFilterEnabled={location?.query?.type !== "embedded"}
                                    onTagSelect={onButtonTagSelect}
                                    onContextChange={handleOnTagsContextChange}
                                    location={location}
                                    tags={tags || []}
                                    injectedTags={injectedTags || {}}
                                    selectedOfferDetails={selectedOfferDetails}
                                    inputProps={{ 'data-index': index }}
                                />
                            )}
                        </CapColumn>
                        {urlType === DEEP_LINK && ctaDeepLinkValue && deepLinkKeysFromSelectionArray.length > 0 && (
                            <CapRow style={{ marginTop: '10px' }}>
                                <CapHeading type="h4">
                                    {formatMessage(messages.deepLinkKeys)}
                                </CapHeading>
                                <CapLabel type="label2" className="cta-deep-link-keys-value">
                                    {(() => {
                                        if (deepLinkKeysFromSelectionArray.length > 0) {
                                            return deepLinkKeysFromSelectionArray.join(', ');
                                        }
                                        if (deepLinkKeysArray.length > 0) {
                                            return deepLinkKeysArray.join(', ');
                                        }
                                    })()}
                                </CapLabel>
                                <CapInput
                                    id="mpush-deep-link-keys"
                                    className="mpush-deep-link-keys"
                                    onChange={onDeepLinkKeysChange}
                                    placeholder={formatMessage(messages.deepLinkKeysPlaceholder, { key: deepLinkKeysFromSelectionArray.join(', ') })}
                                    value={Array.isArray(ctaDeepLinkKeysValue) ? ctaDeepLinkKeysValue.join(', ') : (ctaDeepLinkKeysValue || '')}
                                    size="large"
                                    data-index={index}
                                    errorMessage={deepLinkKeysError ? formatMessage(messages.deepLinkKeysRequired) : ""}
                                />
                            </CapRow>
                        )}
                        <CapRow className="mpush-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="mpush-cta-save-btn"
                                    >
                                        {formatMessage(globalMessages.save)}
                                    </CapButton>
                                </div>
                            </CapTooltip>
                            <CapButton
                                onClick={() => deleteHandler(index)}
                                className="mpush-cta-delete-btn"
                                type="secondary"
                            >
                                {formatMessage(globalMessages.delete)}
                            </CapButton>
                        </CapRow>
                    </CapRow>
                );
            }
        });
        return renderArray;
    };

    return renderedContent();
};

export default injectIntl(CapMpushCTA);
