import { createRoot } from 'react-dom/client';
import GenerateImgTabView from './generateImgTabView';
import { __ } from '@wordpress/i18n';
import { getSettings } from '@/settings';

declare const wp: any;

(async () => {
  const MediaFrame = wp?.media?.view?.MediaFrame?.Select;

  if (!MediaFrame) {
    return;
  }

  const settings = await getSettings();

  if (!settings?.generate_image_enabled) {
    wp.media.view.MediaFrame.Select = MediaFrame.extend({
      initialize: function () {
        MediaFrame.prototype.initialize.apply(this, arguments);

        this.on('content:render:generateImg', this.renderGenerateImg, this);
      },
      renderGenerateImg: function () {
        this.content.mode('browse');
      },
    });

    return;
  }

  wp.media.view.MediaFrame.Select = MediaFrame.extend({
    initialize: function () {
      MediaFrame.prototype.initialize.apply(this, arguments);

      const State = wp.media.controller.State.extend({
        insert: function () {
          this.MediaFrame.close();
        },
      });

      this.states.add([
        new State({
          id: 'generateImg',
          title: __('Generate AI Image', 'filter-ai'),
          search: false,
        }),
      ]);

      this.on('content:render:generateImg', this.renderGenerateImg, this);
    },
    browseRouter: function (routerView: any) {
      routerView.set({
        upload: {
          text: wp.media.view.l10n.uploadFilesTitle,
          priority: 20,
        },
        generateImg: {
          text: __('Generate AI Image', 'filter-ai'),
          priority: 30,
        },
        browse: {
          text: wp.media.view.l10n.mediaLibraryTitle,
          priority: 40,
        },
      });
    },

    renderGenerateImg: function () {
      const parent = this.$el;
      const isToolbarHidden = parent.hasClass('hide-toolbar');

      const container = document.createElement('div');
      container.className = 'generateImg-content';

      const callback = () => this.content.mode('browse');

      const View = wp.Backbone.View.extend({
        className: 'generateImg-wrapper',
        render: function () {
          this.$el.append(container);

          try {
            renderGenerateImgReact(container, callback);

            if (!isToolbarHidden) {
              parent.addClass('hide-toolbar');
            }
          } catch (err) {
            console.error('[GenerateImgTab] React render error:', err);
          }

          return this;
        },

        remove: function () {
          unmountGenerateImgReact();
          wp.Backbone.View.prototype.remove.call(this);

          if (!isToolbarHidden) {
            parent.removeClass('hide-toolbar');
          }
        },
      });

      const view = new View();
      this.content.set(view);
    },
  });
})();

let root: any = null;

function renderGenerateImgReact(container: HTMLElement, callback: () => void) {
  root = createRoot(container);
  root.render(<GenerateImgTabView callback={callback} />);
}

function unmountGenerateImgReact() {
  if (root) {
    root.unmount();
    root = null;
  }
}
