import React, { useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
// import { bindActionCreators } from 'redux';
import { createStructuredSelector } from 'reselect';
import CapRow from '@capillarytech/cap-ui-library/CapRow';
import { UserIsAuthenticated } from '../../utils/authWrapper';
import TagList from '../TagList';
import {
  ANDROID, BEE_LAYOUT_OPTIONS, MOBILE, UNSUBSCRIBE,
} from './constants';
import emptyAndroidSvg from '../../assets/Android.png';
import emptyIosSvg from '../../assets/iOS.png';
import './_beePopupEditor.scss';
function BeePopupEditor(props) {
  const {
    uid,
    id,
    tokenData,
    saveBeeInstance,
    saveBeeData,
    saveBeeHtmlValue,
    beeJson,
    templateLayoutType,
    moduleFilterEnabled,
    label,
    location,
    injectedTags,
    className,
    userLocale,
    selectedOfferDetails,
    tags,
    onContextChange,
    device,
  } = props;

  let beePluginInstance = null;
  let intervalTimer;
  const savedCallback = useRef();
  const beeInstanceRef = useRef(null);
  const isInitializedRef = useRef(false);
  const beeJsonRef = useRef(beeJson);

  useEffect(() => {
    beeJsonRef.current = beeJson;
  }, [beeJson]);

  const [visibleTaglist, setVisibleTaglist] = useState(false);
  const [selectedTag, setSelectedTag] = useState({});
  const filteredTags = (tags || []).filter((obj) => obj.definition.value !== UNSUBSCRIBE);

  useEffect(() => {
    // Only recreate BEE editor when layout type changes, not when content (beeJson) changes
    // If beeJson is in dependencies, editor reloads on every keystroke!
    const beeConfig = {
      uid,
      trackChanges: true,
      container: 'bee-plugin-container',
      workspace: {
        popup: {
          backgroundImageMobile: device === ANDROID ? emptyAndroidSvg : emptyIosSvg,
          layout: BEE_LAYOUT_OPTIONS[templateLayoutType],
          customStyles: {
            container: {
              width: "90%",
              margin: "1.5rem",
            },
          },
        },
        stage: MOBILE,
        hideStageToggle: true,
      },
      contentDialog: {
        mergeTags: {
          label: 'Add Label',
          handler: async (resolve, reject) => {
            // this will open tag modal
            await setVisibleTaglist(true);
            // until tag modal will not open promise will not execute
            // once tag modal is opened it will start 2 sec interval to wait use has selected any tag or cancel the tag selection
            const promise = new Promise((resolveP) => {
              intervalTimer = setInterval(() => {
                // this will execute, if user cancel the tag selection
                if ((savedCallback.current || {}).close === true) {
                  reject();
                  clearInterval(intervalTimer);
                  return;
                }
                // this block is checking use has selected any tag or not
                if (Object.keys(savedCallback.current || {}).length > 0) {
                  resolveP(savedCallback.current);
                  setSelectedTag({});
                  clearInterval(intervalTimer);
                }
              }, 2000);
            });
            // once prmise will resolve , pass the resolve data to handler to show tags in bee edior
            const result = await promise;
            resolve(result);
          },
        },
      },
      onChange: (jsonFile, htmlFile) => {
        saveBeeData(jsonFile, htmlFile, device);
      },
      onSave: (jsonFile, htmlFile) => {
        // onSave provides the actual HTML value, use it to update beeHtml.value
        if (saveBeeHtmlValue && htmlFile) {
          saveBeeHtmlValue(htmlFile, device);
        }
        // Also call saveBeeData to update JSON
        saveBeeData(jsonFile, htmlFile, device);
      },
    };
    window.BeePlugin.create(tokenData, beeConfig, (instance) => {
      beePluginInstance = instance;
      beeInstanceRef.current = instance;
      // Use ref to get the latest beeJson — the closure captures the value at effect time,
      // but beeJsonRef.current is always up-to-date (e.g. when template data loads async)
      const latestBeeJson = beeJsonRef.current;
      const parseJson = typeof latestBeeJson === 'string' ? JSON.parse(latestBeeJson) : latestBeeJson;
      beePluginInstance.start(parseJson);
      saveBeeInstance(beePluginInstance, device);
      isInitializedRef.current = true;
    });
    return () => {
      clearInterval(intervalTimer);
      // Reset initialization flag when component unmounts or layout changes
      isInitializedRef.current = false;
    };
    // IMPORTANT: Only include templateLayoutType, NOT beeJson
    // beeJson changes on every keystroke and would cause editor to reload constantly
  }, [templateLayoutType]);

  useEffect(() => {
    savedCallback.current = Object?.keys(selectedTag)?.length > 0 && selectedTag;
  }, [selectedTag]);

  const onTagSelect = (result) => {
    const msg = {
      name: result,
      value: `{{${result}}}`,
    };
    setSelectedTag(msg);
    setVisibleTaglist(false);
  };

  const onCancelTagList = () => {
    setVisibleTaglist(false);
    setSelectedTag({ close: true });
  };

  return (
    <CapRow useLegacy>
      <div id="bee-plugin-container" className="bee-popup-editor__container"></div>
      <TagList
        moduleFilterEnabled={moduleFilterEnabled}
        label={label}
        onTagSelect={onTagSelect}
        location={location}
        tags={filteredTags}
        injectedTags={injectedTags}
        className={className}
        id={id}
        userLocale={userLocale}
        selectedOfferDetails={selectedOfferDetails}
        visibleTaglist={visibleTaglist}
        hidePopover
        modalProps={{
          onCancel: onCancelTagList,
          className: "bee-editor-tag-list bee-editor-tag-list--positioned",
        }}
        onContextChange={onContextChange}
      />
    </CapRow>
  );
}
BeePopupEditor.propTypes = {
  saveBeeData: PropTypes.func.isRequired,
  saveBeeInstance: PropTypes.func.isRequired,
  beeJson: PropTypes.object.isRequired,
  tokenData: PropTypes.object.isRequired,
  uid: PropTypes.string.isRequired,
  templateLayoutType: PropTypes.string.isRequired,
  id: PropTypes.string.isRequired,
  moduleFilterEnabled: PropTypes.bool.isRequired,
  label: PropTypes.string.isRequired,
  location: PropTypes.object.isRequired,
  injectedTags: PropTypes.array.isRequired,
  className: PropTypes.string.isRequired,
  userLocale: PropTypes.string.isRequired,
  selectedOfferDetails: PropTypes.object.isRequired,
  tags: PropTypes.array.isRequired,
  onContextChange: PropTypes.func.isRequired,
  device: PropTypes.string.isRequired,
};
const mapStateToProps = () => createStructuredSelector({});

function mapDispatchToProps() { }
export default UserIsAuthenticated(connect(mapStateToProps, mapDispatchToProps)(injectIntl(BeePopupEditor)));
