import { MOLART_ERRORS } from '@/constants/errors';
import { useAppDispatch } from '@/redux/hooks/useAppDispatch';
import { useAppSelector } from '@/redux/hooks/useAppSelector';
import { currentSelectedBioEntityIdSelector } from '@/redux/modal/modal.selector';
import { closeModal } from '@/redux/modal/modal.slice';
import { showToast } from '@/utils/showToast';
import * as MolArt from 'molart';
import * as React from 'react';
import { useEffect } from 'react';

const containerId = 'molart-container';

export const MolArtModal: React.FC = () => {
  const uniprot = useAppSelector(currentSelectedBioEntityIdSelector);
  const dispatch = useAppDispatch();

  useEffect(() => {
    let molart: typeof MolArt;

    try {
      molart = new MolArt({
        uniprotId: uniprot,
        containerId,
        customDataSources: [],
      });
    } catch (e) {
      // eslint-disable-next-line no-console
      console.error(e);
      dispatch(closeModal());
      showToast({
        type: 'error',
        message: MOLART_ERRORS.UNEXPECTED_MOLART_ERROR,
      });
    }

    return () => {
      try {
        molart.destroy();
      } catch (e) {
        // molart.destroy errors are ignored as there's a conflict between react rerenders and molart initialization
        // eslint-disable-next-line no-console
        console.error(e);
      }
    };
  }, [uniprot, dispatch]);

  return (
    <div className="flex h-full w-full items-center justify-center bg-white" id={containerId} />
  );
};