import React, { useState } from "react";
import { injectIntl } from "react-intl";
import PhoneInput from 'react-phone-input-2';
import { cloneDeep } from "lodash";
import 'react-phone-input-2/lib/style.css';
import CapRow from "@capillarytech/cap-ui-library/CapRow";
import CapRadioGroup from "@capillarytech/cap-ui-library/CapRadioGroup";
import CapLabel from "@capillarytech/cap-ui-library/CapLabel";
import CapColumn from "@capillarytech/cap-ui-library/CapColumn";
import CapInput from "@capillarytech/cap-ui-library/CapInput";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapTooltipWithInfo from "@capillarytech/cap-ui-library/CapTooltipWithInfo";
import CapSelect from "@capillarytech/cap-ui-library/CapSelect";
import CapButton from "@capillarytech/cap-ui-library/CapButton";
import CapTooltip from "@capillarytech/cap-ui-library/CapTooltip";
import CapIcon from "@capillarytech/cap-ui-library/CapIcon";
import { CAP_SPACE_04 } from "@capillarytech/cap-ui-library/styled/variables";
import TagList from "../../v2Containers/TagList";
import {
  carouselButtonOptions,
  INITIAL_CAROUSEL_PHONE_NUMBER_DATA,
  INITIAL_CAROUSEL_QUICK_REPLY_DATA,
  INITIAL_CAROUSEL_URL_DATA,
  PHONE_NUMBER,
  URL,
  BTN_MAX_LENGTH,
  PHONE_NUMBER_MAX_LENGTH,
  URL_MAX_LENGTH,
  QUICK_REPLY,
} from "./constant";
import capWhatsappMsg from '../../v2Containers/Whatsapp/messages';
import capWhatsappCTAMsg from '../CapWhatsappCTA/messages';
import {
  KARIX_GUPSHUP_URL_OPTIONS, TWILIO_URL_OPTIONS, DYNAMIC_URL, STATIC_URL,
} from "../CapWhatsappCTA/constants";
import globalMessages from '../../v2Containers/Cap/messages';
import { isUrl, isValidWhatsappCtaText } from '../../v2Containers/Line/Container/Wrapper/utils';
import { HOST_TWILIO } from "../../v2Containers/Whatsapp/constants";
import "./index.scss";

export const CapWhatsappCarouselButton = (props) => {
  const {
    intl,
    carouselData = [],
    setCarouselData,
    carouselIndex = 0,
    hostName = '',
    isEditFlow = false,
    tags = [],
    injectedTags = {},
    selectedOfferDetails = [],
  } = props;
  const { formatMessage } = intl;
  const buttonData = carouselData[carouselIndex]?.buttons || [];
  const invalidVarRegex = /{{(.*?)}}/g;

  const handleButtonType = ({ target: { value } }, buttonIndex) => {
    const dataMap = {
      [PHONE_NUMBER]: INITIAL_CAROUSEL_PHONE_NUMBER_DATA,
      [URL]: INITIAL_CAROUSEL_URL_DATA,
      [QUICK_REPLY]: INITIAL_CAROUSEL_QUICK_REPLY_DATA,
    };
    const initialData = dataMap[value];
    const newButtonData = initialData ? cloneDeep(initialData) : {};

    setCarouselData(
      carouselData.map((item, index) =>
        index === carouselIndex
          ? {
              ...item,
              buttons: item.buttons.map((btn, i) =>
                i === buttonIndex ? newButtonData : btn
              ),
            }
          : item
      )
    );
  };

  const onValueChange = (buttonIndex, fields = []) => {
    const updatedButtonData = cloneDeep(buttonData);
    fields.forEach((field) => {
      updatedButtonData[buttonIndex][field?.fieldName] = field?.value;
    });
    setCarouselData(
      carouselData.map((item, index) => index === carouselIndex
        ? { ...item, buttons: updatedButtonData }
        : item)
    );
  };

  const onTagSelect = (data, index, url) => {
    onValueChange(index, [{fieldName: 'url', value: url.replace('{{1}}', `{{${data}}}`)}]);
  };

  const revertTagSelect = (index, url) => {
    onValueChange(index, [{fieldName: 'url', value: url.replace(invalidVarRegex, `{{1}}`)}]);
  };

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

  const onUrlChange = ({ target = {} }, urlType, buttonIndex) => {
    let { value = '' } = target;
    if (urlType === DYNAMIC_URL) {
      value = value.replace(invalidVarRegex, '');
      value = `${value}{{1}}`;
    }
    let errorMessage = false;
    if (!isUrl(value)) {
      errorMessage = formatMessage(capWhatsappCTAMsg.ctaWebsiteUrlErrorMessage);
    } else if (
      urlType === STATIC_URL
      && value.match(invalidVarRegex)?.length > 0
    ) {
      errorMessage = formatMessage(capWhatsappCTAMsg.staticUrlWithVarErrorMessage);
    }
    onValueChange(buttonIndex, [{fieldName: 'url', value}, {fieldName: 'urlError', value: errorMessage}]);
  };

  const onButtonTextChange = (value, buttonIndex) => {
    let errorMessage = '';
    if (!isValidWhatsappCtaText(value)) {
      errorMessage = formatMessage(capWhatsappCTAMsg.ctaButtonErrorMessage);
    }
    onValueChange(buttonIndex, [{fieldName: 'text', value}, {fieldName: 'textError', value: errorMessage}]);
  };

  const ctaSaveDisabled = (index) => {
    const {
      buttonType, text, phone_number, url, textError, urlError,
    } = buttonData[index] || {};
    if (text === '' || textError) {
      return true;
    } if (buttonType === PHONE_NUMBER && phone_number.length < 5) {
      return true;
    } if (buttonType === URL && (url === '' || urlError)) {
      return true;
    }
    return false;
  };

  const handleSaveButton = (buttonIndex) => {
    onValueChange(buttonIndex, [{fieldName: 'isSaved', value: true}]);
  };

  const handleEditButton = (buttonIndex) => {
    onValueChange(buttonIndex, [{fieldName: 'isSaved', value: false}]);
  };

  const handleDeleteButton = (buttonIndex) => {
    setCarouselData((prevData) =>
      prevData.map((carousel, index) =>
        index === carouselIndex
          ? {
              ...carousel,
              buttons: carousel.buttons.filter((_, i) => i !== buttonIndex),
            }
          : carousel
      )
    );
  };

  const addCarouselButton = () => {
    setCarouselData(
      carouselData.map((item, index) =>
        index === carouselIndex
          ? {
              ...item,
              buttons: [...buttonData, cloneDeep(INITIAL_CAROUSEL_PHONE_NUMBER_DATA)],
            }
          : item
      )
    );
  };

  const renderButtonContent = (buttonType, buttonIndex) => (
    <>
      <CapRow className="text-box-container">
        <CapColumn span={24}>
          {/* Button text */}
          <CapHeading type="h4" className="cta-label">
            {formatMessage(capWhatsappCTAMsg.ctaButtonText)}
            <CapTooltipWithInfo
              infoIconProps={{
                style: { marginLeft: CAP_SPACE_04 },
              }}
              autoAdjustOverflow
              placement="right"
              title={formatMessage(capWhatsappCTAMsg.ctaButtonTextTooltip)}
            />
          </CapHeading>
          <CapInput
            className="whatsapp-cta-button-text"
            onChange={({ target: { value } }) => onButtonTextChange(value, buttonIndex)}
            placeholder={formatMessage(capWhatsappCTAMsg.ctaButtonTextPlaceholder)}
            value={buttonData[buttonIndex].text}
            size="large"
            maxLength={BTN_MAX_LENGTH}
            errorMessage={buttonData[buttonIndex]?.textError}
          />
          {renderLength(buttonData[buttonIndex]?.text?.length, BTN_MAX_LENGTH)}
        </CapColumn>
      </CapRow>
      {buttonType === PHONE_NUMBER && (
        <CapRow className="text-box-container">
          <CapColumn span={24}>
            {/* phone number */}
            <CapHeading type="h4" className="cta-label">
              {formatMessage(capWhatsappCTAMsg.ctaPhoneNo)}
            </CapHeading>
            <PhoneInput
              placeholder={formatMessage(capWhatsappCTAMsg.ctaPhoneNoPlaceholder)}
              autoFormat={false}
              countryCodeEditable={false}
              value={buttonData[buttonIndex].phone_number}
              onChange={(value) => onValueChange(buttonIndex, [{fieldName: 'phone_number', value}])}
              country="in"
              className="cta-phone-number carousel-button-phone-number"
            />
            {renderLength(buttonData[buttonIndex]?.phone_number.length, PHONE_NUMBER_MAX_LENGTH)}
          </CapColumn>
        </CapRow>
      )}
      {buttonType === URL
      && (
        <CapRow type="flex" align="top" justify="space-between" className="text-box-container">
          <CapColumn span={6}>
            {/* URL Type */}
            <CapHeading type="h4" className="cta-label">
              {formatMessage(capWhatsappCTAMsg.ctaWebsiteType)}
            </CapHeading>
            <CapSelect
              id="whatsapp-carousel-button-url-type"
              options={
                hostName === HOST_TWILIO
                  ? TWILIO_URL_OPTIONS
                  : KARIX_GUPSHUP_URL_OPTIONS
              }
              onChange={(value) => onValueChange(buttonIndex, [{fieldName: 'urlType', value}])}
              value={buttonData[buttonIndex]?.urlType}
            />
          </CapColumn>
          <CapColumn span={16}>
            {/* cta url */}
            <CapHeading type="h4" className="cta-label">
              {formatMessage(capWhatsappCTAMsg.ctaWebsiteUrl)}
              {buttonData[buttonIndex]?.urlType === DYNAMIC_URL && (
                <CapTooltipWithInfo
                  infoIconProps={{
                    style: { marginLeft: CAP_SPACE_04 },
                  }}
                  autoAdjustOverflow
                  placement="right"
                  title={formatMessage(capWhatsappCTAMsg.dynamicUrlTooltip, { one: '{{1}}' })}
                />
              )}
            </CapHeading>
            <CapInput
              className="whatsapp-cta-url"
              onChange={(event) => onUrlChange(event, buttonData[buttonIndex]?.urlType, buttonIndex)}
              placeholder={
              buttonData[buttonIndex]?.urlType === DYNAMIC_URL
                ? formatMessage(capWhatsappCTAMsg.ctaDynamicPlaceholder)
                : formatMessage(capWhatsappCTAMsg.ctaStaticPlaceholder)
              }
              value={buttonData[buttonIndex]?.url}
              size="large"
              maxLength={URL_MAX_LENGTH}
              errorMessage={buttonData[buttonIndex]?.urlError || ''}
            />
            {renderLength(buttonData[buttonIndex]?.url?.length, URL_MAX_LENGTH)}
          </CapColumn>
        </CapRow>
      )
      }
      {/* it render save and delete button */}
      <CapRow useLegacy className="whatsapp-cta-save-delete-btn whatsapp-carousel-save-edit-btn">
        <CapTooltip
          title={
            ctaSaveDisabled(buttonIndex)
              && formatMessage(capWhatsappCTAMsg.ctaSaveDisabled)
          }
          placement="bottom"
        >
          <div className="button-disabled-tooltip-wrapper">
            <CapButton
              onClick={() => {
                handleSaveButton(buttonIndex);
              }}
              disabled={ctaSaveDisabled(buttonIndex)}
              className="whatsapp-cta-save-btn"
            >
              {formatMessage(globalMessages.save)}
            </CapButton>
            {buttonData.length > 1 && buttonIndex > 0 && parseInt(carouselIndex, 10) === 0 && (
              <CapButton
                onClick={() => {
                  handleDeleteButton(buttonIndex);
                }}
                className="whatsapp-cta-delete-btn whatsapp-carousel-delete-button"
                type="secondary"
              >
                {formatMessage(globalMessages.delete)}
              </CapButton>
            )}
          </div>
        </CapTooltip>
      </CapRow>
    </>
  );

  const isCarouselAddButtonDisable = buttonData?.length === 1 && !buttonData?.[0]?.isSaved;

  return (
    <CapRow>
      {buttonData.map((button, index) => {
        const isPhoneNumberType = button?.buttonType === PHONE_NUMBER;
        const isURLtype = button?.buttonType === URL;
        if (button.isSaved || isEditFlow) {
          return (
            <CapRow
              key={`${button.buttonType}_${index}`}
              className={`cap-whatsapp-saved-cta cap-whatsapp-saved-carousel-button margin-t-12 ${isEditFlow ? 'margin-l-0' : ''}`}
              align="middle"
              type="flex"
              noWrap
            >
              <CapColumn
                span={1}
                className={`${isPhoneNumberType ? 'whatsapp-saved-cta-phone-icon' : ''}`}
              >
                <CapIcon size="s" type={isPhoneNumberType ? 'call' : isURLtype ? 'launch' : 'six-dots'} />
              </CapColumn>
              <CapColumn span={6}>
                <CapLabel
                  type="label2"
                  className="whatsapp-saved-cta-button-text"
                >
                  {button?.text}
                </CapLabel>
              </CapColumn>
              {isPhoneNumberType && (
                <CapColumn span={10} align="left">
                  <CapLabel className="phone">
                    {button?.phone_number}
                  </CapLabel>
                </CapColumn>
              )}
              {isURLtype && (
                <CapRow type="flex" align="middle">
                  <CapRow type="flex" align="middle" justify="start">
                    <CapLabel className="url-type" type="label2">
                      {button?.urlType === STATIC_URL
                        ? formatMessage(capWhatsappCTAMsg.ctaWebsiteTypeStatic)
                        : formatMessage(capWhatsappCTAMsg.ctaWebsiteTypeDynamic)}
                    </CapLabel>
                  </CapRow>
                  <CapRow type='flex' className="whatsapp-url-preview-wrapper">
                    <CapTooltip title={button?.url} placement="top">
                      <CapColumn span={16} className="margin-r-0">
                        <CapLabel className="url">{button?.url}</CapLabel>
                      </CapColumn>
                    </CapTooltip>
                  </CapRow>
                </CapRow>
              )}
              {!isEditFlow && (
                <CapRow type='flex' align='middle' justify="end" gap={12} fillSpace>
                  <CapIcon size="s" type="edit" onClick={() => handleEditButton(index)}/>
                  {parseInt(carouselIndex, 10) === 0 && (
                    <CapIcon size="s" type="delete" onClick={() => handleDeleteButton(index)} disabled={buttonData?.length === 1}/>
                  )}
                </CapRow>
              )}
              {isEditFlow && button?.urlType === DYNAMIC_URL && button?.url.includes('{{1}}') && (
                <CapColumn>
                  <TagList
                    className="whatsapp-cta-taglist"
                    label={formatMessage(capWhatsappCTAMsg.whatsappCtaTagListLabel)}
                    onTagSelect={(data) => onTagSelect(data, index, button?.url)}
                    tags={tags}
                    injectedTags={injectedTags}
                    selectedOfferDetails={selectedOfferDetails}
                  />
                </CapColumn>
              )}
              {isEditFlow && button?.urlType === DYNAMIC_URL && !button?.url.includes('{{1}}') && (
                <CapColumn
                  span={1}
                  onClick={() => revertTagSelect(index, button?.url)}
                  className="whatsapp-cta-tag-revert"
                >
                  <CapTooltip
                    title={formatMessage(capWhatsappCTAMsg.whatsappCtaTagListRevert)}
                    placement="top"
                  >
                    <CapIcon size="s" type="return" />
                  </CapTooltip>
                </CapColumn>
              )}
            </CapRow>
          );
        } return (
          <CapRow useLegacy
            key={`${button.buttonType}_${index}`}
            className="cap-whatsapp-carousel-button"
          >
            <CapLabel type="label16" className="button-type-heading">{formatMessage(capWhatsappMsg.buttonType)}</CapLabel>
            <CapRadioGroup
              id="carousel-button-radio"
              options={carouselButtonOptions(carouselIndex)}
              value={button.buttonType}
              onChange={(e) => handleButtonType(e, index)}
              className="whatsapp-media-radio"
            />
            {renderButtonContent(button.buttonType, index)}
          </CapRow>
        );
      })}
      {/* user can add only two button in the first carousel in other carousel user dont allow to add buttons */}
      {buttonData?.length < 2 && !isEditFlow && parseInt(carouselIndex, 10) === 0 && (
        <CapRow useLegacy>
          <CapTooltip
            title={
              isCarouselAddButtonDisable ? formatMessage(capWhatsappCTAMsg.ctaAddDisabled) : ""
            }
            placement="right"
          >
            <div className="button-disabled-tooltip-wrapper">
              <CapButton
                type="flat"
                id="whatsapp-quick-reply-add-button"
                disabled={isCarouselAddButtonDisable}
                className="margin-t-12 margin-l-24"
                isAddBtn
                onClick={addCarouselButton}
              >
                {formatMessage(capWhatsappCTAMsg.addButton)}
              </CapButton>
            </div>
          </CapTooltip>
        </CapRow>
      )}
    </CapRow>
  );
};

export default injectIntl(CapWhatsappCarouselButton);
