import React, { memo, useState } from "react";
import PropTypes from "prop-types";
import { FormattedMessage } from "react-intl";
import CapRow from "@capillarytech/cap-ui-library/CapRow";
import CapButton from "@capillarytech/cap-ui-library/CapButton";
import CapIcon from "@capillarytech/cap-ui-library/CapIcon";
import CapHeading from "@capillarytech/cap-ui-library/CapHeading";
import CapTooltip from "@capillarytech/cap-ui-library/CapTooltip";
import CapMpushCTA from "../../../v2Components/CapMpushCTA";
import { PRIMARY, SECONDARY, DEEP_LINK } from "../constants";
import messages from "../messages";

const CtaButtons = ({
  primaryButton,
  secondaryButton,
  setPrimaryButton,
  setSecondaryButton,
  ctaData,
  updateHandler,
  deleteHandler,
  deepLink,
  location,
  tags,
  injectedTags,
  selectedOfferDetails,
  handleOnTagsContextChange,
}) => {
  // Local state to control CTA form visibility
  const [showPrimaryCTA, setShowPrimaryCTA] = useState(false);
  const [showSecondaryCTA, setShowSecondaryCTA] = useState(false);

  const handleAddPrimary = () => {
    // Prevent multiple clicks if primary button is already being added or form is already showing
    if (primaryButton && showPrimaryCTA) {
      return;
    }

    // If ctaData is empty or doesn't have a primary button, initialize it
    if (ctaData?.length === 0 || !ctaData?.find((cta) => cta?.index === 0)) {
      const newPrimaryButton = {
        index: 0,
        ctaType: PRIMARY,
        text: "",
        urlType: DEEP_LINK,
        url: "",
        deepLinkKeys: "",
        isSaved: false,
      };
      updateHandler(newPrimaryButton, 0);
    }

    setPrimaryButton(true);
    setShowPrimaryCTA(true);
  };

  const handleAddSecondary = () => {
    // Prevent multiple clicks if secondary button is already being added or form is already showing
    //cooment until supported from BE & Hydra
    // if (secondaryButton && showSecondaryCTA) {
    //   return;
    // }

    // if (shouldShowSecondaryCTA) {
    //   return;
    // }

    // If ctaData doesn't have a secondary button, initialize it
    if (ctaData?.length < 2 || !ctaData?.find((cta) => cta?.index === 1)) {
      const newSecondaryButton = {
        index: 1,
        ctaType: SECONDARY,
        text: "",
        urlType: DEEP_LINK,
        url: "",
        deepLinkKeys: "",
        isSaved: false,
      };
      updateHandler(newSecondaryButton, 1);
    }

    // setSecondaryButton(true);
    // setShowSecondaryCTA(true);
  };

  // Check if primary button exists (saved or being edited)
  const primaryButtonExists = ctaData?.length > 0 && ctaData[0]?.text;
  const isPrimaryButtonSaved = primaryButtonExists && ctaData[0]?.isSaved;

  // Check if secondary button exists (saved or being edited)
  const secondaryButtonExists = ctaData?.length > 1 && ctaData[1]?.text;
  const isSecondaryButtonSaved = secondaryButtonExists && ctaData[1]?.isSaved;

  // Show primary CTA if button is active and (form is showing OR button exists)
  const shouldShowPrimaryCTA = primaryButton && (showPrimaryCTA || primaryButtonExists);

  // Show secondary CTA if button is active and (form is showing OR button exists)
  const shouldShowSecondaryCTA = secondaryButton && (showSecondaryCTA || secondaryButtonExists);

  // Enhanced delete handler to hide forms when buttons are deleted
  const handleDelete = (index) => {
    if (index === 0) {
      setShowPrimaryCTA(false);
      setPrimaryButton(false);
    } else if (index === 1) {
      //cooment until supported from BE & Hydra
      // setShowSecondaryCTA(false);
      // setSecondaryButton(false);
    }
    deleteHandler(index);
  };

  return (
    <>
      <CapRow className="mpush-cta-buttons">
        <CapHeading type="h3">
          <FormattedMessage {...messages.buttons} />
        </CapHeading>
        {!isPrimaryButtonSaved && !shouldShowPrimaryCTA && (
          <CapButton
            type="flat"
            id="add-primary-button"
            onClick={handleAddPrimary}
          >
            <CapIcon type="plus" />
            <CapHeading type="h5" id="add-primary-btn-heading">
              <FormattedMessage {...messages.addPrimaryButton} />
            </CapHeading>
          </CapButton>
        )}
      </CapRow>
      {shouldShowPrimaryCTA && (
        <CapMpushCTA
          ctaData={ctaData}
          updateHandler={updateHandler}
          deleteHandler={handleDelete}
          deepLink={deepLink}
          buttonType={PRIMARY}
          location={location}
          tags={tags}
          injectedTags={injectedTags}
          selectedOfferDetails={selectedOfferDetails}
          handleOnTagsContextChange={handleOnTagsContextChange}
        />
      )}
      {isPrimaryButtonSaved && !isSecondaryButtonSaved && !shouldShowSecondaryCTA && (
        <CapTooltip
          overlay={<FormattedMessage {...messages.secondaryButtonTooltip} />}
          placement="top"
        >
          <div style={{ display: 'inline-block' }}>
            <CapButton
              type="flat"
              id="add-secondary-button"
              onClick={handleAddSecondary}
              disabled
            >
              <CapIcon type="plus" />
              <CapHeading type="h5" id="add-secondary-btn-heading">
                <FormattedMessage {...messages.addSecondaryButton} />
              </CapHeading>
            </CapButton>
          </div>
        </CapTooltip>
      )}
      {shouldShowSecondaryCTA && (
        <CapMpushCTA
          ctaData={ctaData}
          updateHandler={updateHandler}
          deleteHandler={handleDelete}
          deepLink={deepLink}
          buttonType={SECONDARY}
        />
      )}
    </>
  );
};

CtaButtons.propTypes = {
  primaryButton: PropTypes.bool.isRequired,
  secondaryButton: PropTypes.bool.isRequired,
  setPrimaryButton: PropTypes.func.isRequired,
  setSecondaryButton: PropTypes.func.isRequired,
  ctaData: PropTypes.array.isRequired,
  updateHandler: PropTypes.func.isRequired,
  deleteHandler: PropTypes.func.isRequired,
  deepLink: PropTypes.array,
  handleOnTagsContextChange: PropTypes.func,
  location: PropTypes.object,
  tags: PropTypes.array,
  injectedTags: PropTypes.object,
  selectedOfferDetails: PropTypes.array,
};

CtaButtons.defaultProps = {
  deepLink: [],
  handleOnTagsContextChange: () => {},
  location: {},
  tags: [],
  injectedTags: {},
  selectedOfferDetails: [],
};

export default memo(CtaButtons);
