import React, { useEffect, useState } from "react";
import OneSchemaImporter from "@oneschema/react";
import {
  LoadingOverlay,
  Modal,
  useConfirmationModal,
} from "@komi-app/components";
import { OneSchemaLaunchStatus, OneSchemaSuccessEvent } from "../Types";
import notification from "utils/notification";
import { services } from "services";
import "./ContactsImport.scss";
import config from "config";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
type OneSchemaContactImporterProps = {
  setIsImporterOpen: (isImporterOpen: boolean) => void;
  setIsContactImportButtonDisabled: (inProgress: boolean) => void;
};

export const OneSchemaContactImporter: React.FC<
  OneSchemaContactImporterProps
> = ({ setIsImporterOpen, setIsContactImportButtonDisabled }) => {
  /**
   * State to check if the importer is ready to be rendered.
   * This is used to show the loader till the importer is ready.
   */
  const [isImporterReadyToRender, setIsImporterReadyToRender] = useState(false);

  /**
   * OneSchema token is generated on the server and passed to the client.
   * This token is used to authenticate the user on OneSchema.
   */
  const [oneSchemaToken, setOneSchemaToken] = useState<string>(""); //Generated on komi-server

  const isOneSchemaDevModeFixOn = useFeatureIsOn(
    FLAGS.FEAT_CRM_1092_ONESCHEMA_DEV_MODE
  )

  /**
   * Configuration for the OneSchema importer.
   * Todo: Move to a proper config file
   */
  const oneSchemaConfig = {
    isOpen: true, //Set to true to open the importer
    clientId: config.OneSchema.clientId,
    userJwt: oneSchemaToken,
    templateKey: "fan_contacts",
    devMode: isOneSchemaDevModeFixOn ? config.service.env !== 'production' : false,
    className: "oneschema-importer",
    customizationOverrides: {
      hideLogo: true,
    },
  };

  //Confirmation modal to show when the user successfully uploads contacts
  const confirmationModal = useConfirmationModal();

  /**
   * Get the OneSchema JWT from the server on component mount.
   */
  useEffect(() => {
    getOneSchemaToken();
  }, []); // Empty dependency array ensures this effect runs once after the initial render

  /**
   * This function is called when the OneSchema importer is ready to be rendered.
   */
  const onLaunch = (message: OneSchemaLaunchStatus) => {
    if (message.success) {
      setIsImporterReadyToRender(true);
    } else {
      handleImportError();
    }
  };

  /**
   * Called when the user closes the importer.
   */
  const onCancel = () => {
    setIsImporterOpen(false);
    setIsContactImportButtonDisabled(false);
  };

  /**
   * Called when the user successfully uploads contacts.
   * @param event
   */
  const onImportSuccess = async (event: OneSchemaSuccessEvent) => {
    //Start the fan import on the server
    await services.fans().startFanImport(event);

    //Hide the importer
    setIsImporterOpen(false);
    setIsContactImportButtonDisabled(true);

    //Imform the user the import has started
    confirmationModal.open({
      maxWidth: "520px",
      className: "contact-upload__confirmation-modal",
      title: "You have successfully uploaded your contacts",
      description:
        "We’re processing your contacts. They will become visible as soon as the import is complete.",
      buttons: [
        {
          label: "Done",
          variant: "primary",
          action: "confirm",
        },
      ],
      onConfirm: async () => {},
      fullWidthButtons: false,
    });
  };

  /**
   * Generic error handler for the importer.
   */
  const handleImportError = () => {
    setIsImporterOpen(false);
    notification.error({
      message: "Something went wrong with the upload. Please try again.",
    });
  };

  /**
   * Get the Oneschema JWT from the server.
   * Once received, initialize OneSchema
   */
  const getOneSchemaToken = async () => {
    const { ok, response } = await services.fans().getOneSchemaToken();
    if (ok) {
      setOneSchemaToken(response);
    } else {
      handleImportError();
    }
  };

  /**
   * Returns the OneSchema importer.
   * To be called only when the JWT is
   * fetched from the server and successfully received
   * @returns JSX.Element
   */
  const getOneSchemaImporter = () => {
    return (
      <OneSchemaImporter
        {...oneSchemaConfig}
        onRequestClose={() => setIsImporterOpen(false)}
        importConfig={{ type: "local", metadataOnly: true }}
        onLaunched={onLaunch}
        onCancel={onCancel}
        onSuccess={onImportSuccess}
      />
    );
  };

  return (
    <>
      {/* Loader to wait till Importer is ready */}
      {!isImporterReadyToRender && (
        <LoadingOverlay
          loading={!isImporterReadyToRender}
          variant="dark"
          children={""}
        />
      )}

      {/* Once oneSchema Token is receive, begin rendering the Importer.  */}
      {oneSchemaToken && getOneSchemaImporter()}
    </>
  );
};
