/**
*
* Ckeditor
*
*/

import PropTypes from 'prop-types';

import React from 'react';
// import styled from 'styled-components';

// import { FormattedMessage } from 'react-intl';
import _ from 'lodash';
import CapSpin from '@capillarytech/cap-ui-library/CapSpin';
import  CapAskAira  from '@capillarytech/cap-ui-library/CapAskAira';
import { request,getAPICallObject } from '../../services/api';
import './style.scss';
// import messages from './messages';
const loadScript = require('load-script');
const hostName = window.location.origin.includes('localhost') ? 'https://nightly.intouch.capillarytech.com' : window.location.origin;
const defaultScriptUrl = `${hostName}/arya/ui/library/ckeditor/ckeditor.js`;

const user = localStorage.getItem('user');
let locale = 'en';
if (user && JSON.parse(user).lang) {
  locale = JSON.parse(user).lang;
}
const CKEditorConfig = {
  skin: 'moono-lisa',
  toolbar: [
    { name: 'document', items: ['Source', '-'] },
    { name: 'clipboard', items: ['Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo'] },
    { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-'] },
    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat'] },
    { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language'] },
    { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
    { name: 'insert', items: ['Image', 'Table', 'HorizontalRule', 'Smiley'] },
    // '/',
    { name: 'styles', items: ['Format', 'Font', 'FontSize'] },
    { name: 'colors', items: ['TextColor', 'BGColor'] },
    { name: 'tools', items: ['Maximize', 'ShowBlocks'] },
  ],
  format_tags: 'p;h1;h2;h3;pre',
  toolbarCanCollapse: true,
  toolbarStartupExpanded: true,
  uiColor: '#e3e3e3',
  width: 'calc(100% - 2px)',
  height: 'calc(100vh - 290px)',
  fullPage: true,
  htmlEncodeOutput: true,
  startupFocus: true,
  // allowedContent: {
  // // Allow all content.
  //   $1: {
  //     // elements: this.editorInstance.dtd,
  //     //elements: window.CKEDITOR.dtd,
  //     attributes: true,
  //     styles: true,
  //     classes: true,
  //   },
  // },
  allowedContent: true, // Allow all content, including attributes and styles
  extraAllowedContent: 'img[width,height]',
  disallowedContent: 'script; *[on*]',
  language: locale,
  toolbar_Basic:
  [
    ['SwitchBar', '-', 'Source', '-', 'Bold', 'Italic', 'Underline'],
    ['NumberedList', 'BulletedList'],
    ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
    ['Link', 'Unlink', 'Anchor'],
    ['Image', 'Table'],
    ['Font', 'FontSize'],
    ['TextColor', 'BGColor'],
  ],
  removePlugins: 'magicline',
};

const weChatCKEditorConfig = {
  skin: 'moono-lisa',
  toolbar: [
    { name: 'clipboard', items: ['Undo', 'Redo', 'Font', 'FontSize', 'Format'] },
    { name: 'colors', items: ['TextColor', 'BGColor'] },
    { name: 'tools', items: ['Maximize', 'ShowBlocks'] },
    { name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'CopyFormatting', 'RemoveFormat'] },
    { name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote', 'CreateDiv', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock', '-', 'BidiLtr', 'BidiRtl', 'Language'] },
    { name: 'insert', items: ['Table', 'HorizontalRule', 'Smiley'] },
    { name: 'editing', items: ['Find', 'Replace', '-', 'SelectAll', '-'] },
    { name: 'links', items: ['Link', 'Unlink', 'Anchor'] },
    { name: 'pasting', items: ['Paste', 'PasteText', 'PasteFromWord'] },
    { name: 'document', items: ['Source'] },
  ],
  format_tags: 'p;h1;h2;h3;pre',
  toolbarCanCollapse: false,
  toolbarStartupExpanded: true,
  // uiColor: '#e3e3e3',
  width: 'calc(100% - 2px)',
  height: 'calc(100vh - 290px)',
  fullPage: true,
  htmlEncodeOutput: true,
  startupFocus: true,
  allowedContent: {
  // Allow all content.
    $1: {
      // elements: this.editorInstance.dtd,
      //elements: window.CKEDITOR.dtd,
      attributes: true,
      styles: true,
      classes: true,
    },
  },
  disallowedContent: 'script; *[on*]',
  language: locale,
  toolbar_Basic:
  [
    ['SwitchBar', '-', 'Source', '-', 'Bold', 'Italic', 'Underline'],
    ['NumberedList', 'BulletedList'],
    ['JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
    ['Link', 'Unlink', 'Anchor'],
    ['Image', 'Table'],
    ['Font', 'FontSize'],
    ['TextColor', 'BGColor'],
  ],
};

class Ckeditor extends React.Component { // eslint-disable-line react/prefer-stateless-function
  constructor(props) {
    super(props);
    let config = CKEditorConfig;
    if (this.props.channel && this.props.channel.toLowerCase() === 'wechat') {
      config = weChatCKEditorConfig;
      config.startupFocus = false;
      config.height = 'calc(100vh - 450px)';
    }
    const { accessibleFeatures = [] } = this.props.currentOrgDetails || {};
    const isAiImageGenerationEnabled = accessibleFeatures?.includes("ENABLE_AI_SUGGESTIONS");
    //State initialization
    this.state = {
      config,
      isAiImageGenerationEnabled,
      events: {
        blur: this.onBlur,
        afterPaste: this.afterPaste,
        change: this.onChange,
      },
      content: "",
      editorInstance: undefined,
      setInitData: false,
      isLoading: true,
      scriptLoaded: false,
    };

    this.delayTimer = 0;
    //Bindings
    this.onLoad = this.onLoad.bind(this);
  }

  componentWillMount() {
    let content = '';
    this.id = this.props.id;
    if (this.props.content !== '') {
      content = this.props.content;
      content = content.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\\&quot;/g, "\"");
    }
    this.setState({content}, () => {
      if (this.editorInstance) {
        this.editorInstance.setData(content);
      }
    });
  }

  //load ckeditor script as soon as component mounts if not already loaded
  componentDidMount() {
    loadScript(defaultScriptUrl, this.onLoad);
  }

  componentWillReceiveProps(nextProps) {
    this.id = this.props.id;
    if (this.editorInstance && this.editorInstance.status === "ready") {
      // setTimeout(() => {
      //   this.editorInstance.name = this.id;
      // }, 5000);

    }
  }

  componentWillUnmount() {
    this.unmounting = true;
    if (this.editorInstance) {
      this.editorInstance.destroy();
      if (window.CKEDITOR && !_.isEmpty(window.CKEDITOR.instances)) {
        window.CKEDITOR.instances = {};
      }
    }
  }

  componentDidUpdate(prevProps) {
    if (this.props.content !== prevProps.content) {
      let content = '';
      this.id = this.props.id;
      if (this.props.content !== '') {
        content = this.props.content;
        content = content.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/\\&quot;/g, "\"");
      }
      this.setState({ content }, () => {
        if (this.editorInstance) {
          //Check if the current editor content is different from the new content
          const currentEditorData = this.editorInstance?.getData();
          if (!_.isEqual(currentEditorData, content)) {
            this.editorInstance?.setData(content);
          }
        }
      });
    }
  }

  onLoad = () => {
    this.setState({ scriptLoaded: true }, () => {
      this.initializeEditor();
    });
  };

  initializeEditor = () => {
    if (this.unmounting) return;

    if (!window.CKEDITOR) {
      console.error("CKEditor not found");
      return;
    }

    let html = this.props.content;
    html = html.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, "\"");

    this.editorInstance = window.CKEDITOR.appendTo(
      this.node,
      this.state.config,
      html
    );


    if (this.props.getEditorInstanse) {
      this.props.getEditorInstanse(this.editorInstance, this.props.id);
    }
    //this.editorInstance.name = this.id;

    //Register listener for custom events if any
    // this.editorInstance.on('change', this.handleContentChange);

    // mode event is fired whenever mode is toggled from normal to source mode or vice versa
    // change event works only in wysiwyg(non-source) mode, key event works in both source & wysiwyg(non-source) mode but,
    // key event doesn't get fired up while setting text to bold,italic etc..
    this.editorInstance.on('mode', () => {
      if (this.editorInstance.mode === "source") {
        this.editorInstance.on('key', this.handleContentChange);
      } else {
        if (this.editorInstance.hasListeners("key")) {
          /*Removing the 'key' listener is necessary. If not removed and the mode is switched in the following manner :
          source mode -> Non-source mode -> source mode,
          then under this scenario both 'key' and 'change' listener will get fired on entering text. Except that 'key' listener will not get fired when setting text to 'bold', 'italic' etc.
          */
          this.editorInstance.removeListener("key", this.handleContentChange);
        }
        this.editorInstance.on('change', this.handleContentChange);
      }
    });

    _.forEach(this.props.events, (event, index) => {
      this.editorInstance.on(index, event);
    });
    const channel = _.get(this.props, 'channel', '');
    if (channel && channel.toLowerCase() === 'wechat') {
      this.editorInstance.on('blur', this.onFocusOut);
      _.forEach(this.props.events, (event, index) => {
        this.editorInstance.on(index, event);
      });
      this.editorInstance.on('focus', this.onFocusIn);
      _.forEach(this.props.events, (event, index) => {
        this.editorInstance.on(index, event);
      });
    }
    this.setState({ isLoading: false });
  }

  onFocusOut = () => {
    this.props.onFocusOut();
  }

  onFocusIn = () => {
    this.props.onFocusIn();
  }

  delay(callback, ms) {
    clearTimeout(this.delayTimer);
    this.delayTimer = setTimeout(callback, ms);
  }

  handleContentChange = (evt) => {
    // this.setState({content: this.editorInstance.getData()}, () => {
    //   this.props.handleContentChange(evt);
    //   // evt.setData(this.editorInstance.getData());
    // });
    this.delay(() => {
      this.setState({content: this.editorInstance.getData()}, () => {
        this.props.handleContentChange(evt);
      });
    }, 1000);
  };

  render() {
    const { isAiImageGenerationEnabled } = this.state;
    return (
      <>
        <CapSpin spinning={this.state.isLoading}>
          <div
            id={this.props.id}
            style={{ borderRight: "1px solid #000 !important" }}
          >
            <div
              className={this.props.activeClass}
              ref={(node) => (this.node = node)}
            />
          </div>
        </CapSpin>
        {isAiImageGenerationEnabled && (
          <CapAskAira.CapAiMediaGeneration
            request={request}
            getAPICallObject={getAPICallObject}
            iconPlacement="fixed-br-beamer"
          />
        )}
      </>
    );
  }
}

Ckeditor.defaultProps = {
  id: 'ckeditor',
  content: "<html><body></body></html>",
  config: {},
  activeClass: "",
  events: {},
};

Ckeditor.propTypes = {
  id: PropTypes.string,
  content: PropTypes.any,
  activeClass: PropTypes.string,
  events: PropTypes.object,
  getEditorInstanse: PropTypes.func,
  handleContentChange: PropTypes.func,
  channel: PropTypes.string,
  onFocusOut: PropTypes.func,
  onFocusIn: PropTypes.func,
};

export default Ckeditor;
