import { useSwapContext, useTxUIWrapper } from "@src/context";
import { ADDRESSES } from "@src/contracts";
import { TxStatus } from "@src/models";
import { getTxStatus } from "@src/services";
import { useEffect, useRef } from "react";

export const Tx4Shift = () => {
  const containerRef = useRef<HTMLDivElement | null>(null);

  const { setTxStatus } = useTxUIWrapper();
  const { srcValueUsd, route, srcChain } = useSwapContext();

  useEffect(() => {
    if (!containerRef.current || !route || !srcChain) {
      return;
    }
    containerRef.current.innerHTML = "";

    // Initialize the Shift4 Crypto SDK after the component mounts
    const formConfiguration = {
      apiKey: srcChain.shift4Pk,
      cryptoCurrencyCode: "ETH",
      fiatCurrencyCode: "USD",
      fiatAmount: srcValueUsd,
      lockedAmount: true,
      walletAddress: ADDRESSES[srcChain.chainId]?.SwapperRouter,
      showWalletAddressForm: false,
      themeMode: "light",
      externalOrderId: route.id,
    };

    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    (
      window as unknown as Window & { Shift4CryptoSDK: any }
    )?.Shift4CryptoSDK.createForm(formConfiguration)
      .on("ORDER_COMPLETED", async () => {
        setTxStatus(TxStatus.CONFIRMING_TX);

        // eslint-disable-next-line no-constant-condition
        while (true) {
          await new Promise((r) => setTimeout(r, 1_000));

          try {
            const response = await getTxStatus({ routeHash: route.id });

            // Todo add better error handling
            if (response.status === "DONE") {
              setTxStatus(TxStatus.COMPLETED);
            }
            if (response.status === "REVERTED") {
              setTxStatus(TxStatus.COMPLETED);
            }
          } catch (err) {
            console.error(err);
          }
        }
      })
      .append(containerRef.current);
  }, [route, setTxStatus, srcChain, srcValueUsd]);

  return (
    <div ref={containerRef} style={{ width: "320px", height: "480px" }}></div>
  );
};
