import React from "react";
import PropTypes from 'prop-types';
import { injectIntl, intlShape } from "react-intl";
import cloneDeep from "lodash/cloneDeep";
import CapRow from "@capillarytech/cap-ui-library/CapRow";
import CapHeader from "@capillarytech/cap-ui-library/CapHeader";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapTooltipWithInfo from "@capillarytech/cap-ui-library/CapTooltipWithInfo";
import CapInput from "@capillarytech/cap-ui-library/CapInput";
import CapError from "@capillarytech/cap-ui-library/CapError";
import CapTooltip from "@capillarytech/cap-ui-library/CapTooltip";
import CapButton from "@capillarytech/cap-ui-library/CapButton";
import CapColumn from "@capillarytech/cap-ui-library/CapColumn";
import CapIcon from "@capillarytech/cap-ui-library/CapIcon";
import CapLabel from "@capillarytech/cap-ui-library/CapLabel";
import CapInfoNote from "@capillarytech/cap-ui-library/CapInfoNote";
import messages from "./messages";
import "./index.scss";
import globalMessages from "../../v2Containers/Cap/messages";
import { BUTTON_TEXT, INITIAL_QUICK_REPLY_DATA } from "../../v2Containers/Whatsapp/constants";
import ctaMessages from "../CapWhatsappCTA/messages";

export const CapWhatsappQuickReply = (props) => {
  const { quickReplyData = [], renderMessageLength, setQuickReplyData, isEditFlow, intl,authenticationFlow } = props;
  const { TextArea } = CapInput;
  const { formatMessage } = intl;
  const quickReplyDataLength = quickReplyData?.length;
  //this function is used for handle text field value change
  const handleTextChange = ({target: {value = ''} = {}}, index) => {
    let error = false;
    if (value?.length > 20) {
      error = formatMessage(messages.templateButtonTextLengthError);
    }
    //this check is for same repeated value is not allowed in another text field of quick reply
    const checkIsValueAvailable = quickReplyData?.find((reply) => reply?.text === value);
    if (checkIsValueAvailable) {
      error = formatMessage(messages.templateButtonTextSameValue);
    }
    setQuickReplyData(
      quickReplyData?.map((quickReply) => {
        if (quickReply?.index === index) {
          return {
            ...quickReply,
            text: value,
            error,
          };
        }
        return quickReply;
      })
    );
  };

  //this function is used for save the quick reply text field data and same edit the data
  const handleSaveAndEditBtn = (index, value) => {
    setQuickReplyData(
      quickReplyData.map((quickReply) => {
        if (quickReply?.index === index) {
          return {
            ...quickReply,
            isSaved: value,
          };
        }
        return quickReply;
      })
    );
  };

  //This function is used for delete the quick reply data for a row
  const handleDelete = (index) => {
    setQuickReplyData((prevState) => {
      const clonedQuickReplyData = cloneDeep(prevState);
      const filteredQuickReplyData = clonedQuickReplyData.filter(
        (i) => i?.index !== index
      );
      return filteredQuickReplyData.map((quickReply, i) => ({
        ...quickReply,
        index: i,
      }));
    });
  };
  const quickReplyConfiguredBtn = ({ text, index, authenticationFlow = false }) => (
    <CapRow className={`cap-whatsapp-quick-reply ${authenticationFlow && 'whatsapp-autofill-container'}`}>
      <CapRow type="flex" className="whatsapp-quick-reply-save-container">
        {!authenticationFlow && <CapIcon type="six-dots" />}
        <CapColumn className="text-container">{text}</CapColumn>
        <CapColumn className={`quick-reply-icon ${authenticationFlow && 'whatsapp-quick-reply-disabled-icons'}`}>
          <CapIcon
            onClick={() => handleSaveAndEditBtn(index, false)}
            type="edit"
            aria-label="quick-reply-edit"
          />
          <CapIcon
            onClick={() => handleDelete(index)}
            type="delete"
            aria-label="quick-reply-delete"
          />
        </CapColumn>
      </CapRow>
    </CapRow>
  )
  const addQuickReply = () => {
    const cloneInitialQuickReplyData = cloneDeep(INITIAL_QUICK_REPLY_DATA);
    cloneInitialQuickReplyData[0].index = quickReplyDataLength || 0;
    const clonedQuickReplyData = [
      ...quickReplyData,
      ...cloneInitialQuickReplyData,
    ];
    setQuickReplyData(clonedQuickReplyData);
  };

  const isQuickReplyDisable =
    quickReplyDataLength === 1 && !quickReplyData?.[0]?.isSaved;
  return (
    <>
      {authenticationFlow ? 
        <>
          {quickReplyConfiguredBtn({ text: formatMessage(globalMessages.autofill), index: '0', authenticationFlow: true })}
          <CapInfoNote className="margin-l-26" message={formatMessage(messages.autofillInfo)}/>
        </> :
        <>
      {quickReplyDataLength > 0 && !isEditFlow && (
        <CapRow useLegacy>
          {quickReplyData?.map(({ index, isSaved, text, error }) => {
            if (!isSaved) {
              //this section is render textfield when its not saved or in edit condition
              return (
                <CapRow useLegacy className="cap-whatsapp-quick-reply">
                  <CapRow useLegacy
                    className="whatsapp-button-text-container"
                    key={index}
                  >
                    <CapHeader
                      title={
                        <CapHeading
                          type="h4"
                          className="whatsapp-button-text-heading"
                        >
                          {formatMessage(messages.buttonText)}
                            <CapTooltipWithInfo
                              placement="right"
                              className="whatsapp-button-text-tooltip"
                              autoAdjustOverflow
                              title={formatMessage(messages.buttonTextTooltip)}
                          />
                        </CapHeading>
                      }
                    />
                      <CapRow useLegacy className="whatsapp-button-text-input">
                        <TextArea
                          autosize={{ minRows: 1, maxRows: 5 }}
                          placeholder={formatMessage(
                          messages.buttonTextPlaceholder
                        )}
                          onChange={(e) => handleTextChange(e, index)}
                          errorMessage={
                          error && (
                            <CapError className="whatsapp-template-message-error">
                              {error}
                            </CapError>
                          )
                        }
                          value={text || ""}
                      />
                      </CapRow>
                    {renderMessageLength(BUTTON_TEXT, text?.length || 0)}
                    {/* it render save and delete button */}
                      <CapRow useLegacy className="whatsapp-cta-save-delete-btn">
                        <CapTooltip
                          title={
                          (text === "" || error)
                            && formatMessage(ctaMessages.ctaSaveDisabled)
                        }
                          placement={"bottom"}
                      >
                        <div className="button-disabled-tooltip-wrapper">
                          <CapButton
                            onClick={() => {
                              handleSaveAndEditBtn(index, true);
                            }}
                            disabled={text === "" || error}
                            className="whatsapp-cta-save-btn"
                          >
                            {formatMessage(globalMessages.save)}
                          </CapButton>
                        </div>
                        </CapTooltip>
                          <CapButton
                            onClick={() => {
                              handleDelete(index);
                            }}
                            className="whatsapp-cta-delete-btn whatsapp-quick-reply-delete-button"
                            type="secondary"
                      >
                            {formatMessage(globalMessages.delete)}
                          </CapButton>
                      </CapRow>
                  </CapRow>
                </CapRow>
              );
            }
            return (
                //this section render when data is saved and user can edit it
                quickReplyConfiguredBtn({text,index})
              );
          })}
        </CapRow>
      )}
      {/* this section render in edit mode from campaign side */}
      {quickReplyDataLength > 0 && isEditFlow &&
        quickReplyData.map(({text, index}) => (
          <CapRow className="cap-whatsapp-quick-reply whatsapp-quick-reply-edit-container" key={index}>
            <CapLabel type="label16">{text}</CapLabel>
          </CapRow>
        ))
      }
      {/* this section render add button section with condition */}
      {quickReplyDataLength < 3 && !isEditFlow && (
        <CapRow useLegacy>
          <CapTooltip
            title={
              isQuickReplyDisable ? formatMessage(ctaMessages.ctaAddDisabled) : ""
            }
            placement={"right"}
          >
            <div className="button-disabled-tooltip-wrapper">
              <CapButton
                type="flat"
                id="whatsapp-quick-reply-add-button"
                disabled={isQuickReplyDisable}
                className="margin-t-12 margin-l-24"
                isAddBtn
                onClick={addQuickReply}
              >
                {formatMessage(ctaMessages.addButton)}
              </CapButton>
            </div>
          </CapTooltip>
        </CapRow>
      )}</>}
    </>
  );
};

CapWhatsappQuickReply.propTypes = {
  quickReplyData: PropTypes.array,
  renderMessageLength: PropTypes.func,
  setQuickReplyData: PropTypes.func,
  isEditFlow: PropTypes.func,
  intl: intlShape.isRequired,
  authenticationFlow : PropTypes.bool,
};

export default injectIntl(CapWhatsappQuickReply);
