import React, { useMemo, useState } from "react";
import { useParams, useLocation, useNavigate } from "react-router-dom";
import { SnackbarProvider, enqueueSnackbar } from "notistack";

import { Box, Typography } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton/LoadingButton";
import {
  MsgOnboardParticipantEncodeObject,
  typeUrlMsgOnboardParticipant,
} from "@cerc-io/registry-sdk";

import { useWalletConnectContext } from "../context/WalletConnectContext";

const SignWithCosmos = () => {
  const { session, signClient } = useWalletConnectContext();

  const { cosmosAddress, ethSignature } = useParams();

  const [isLoading, setIsLoading] = useState(false);

  const navigate = useNavigate();
  const location = useLocation();
  const innerMessage = location.state;
  const ethAddress = innerMessage.address;

  const onboardParticipantMsg: MsgOnboardParticipantEncodeObject =
    useMemo(() => {
      return {
        typeUrl: typeUrlMsgOnboardParticipant,
        value: {
          participant: cosmosAddress,
          ethPayload: innerMessage,
          ethSignature,
        },
      };
    }, [cosmosAddress, innerMessage, ethSignature]);

  const sendTransaction = async (
    transactionMessage: MsgOnboardParticipantEncodeObject
  ) => {
    if (!ethAddress) {
      enqueueSnackbar("Set nitro address");
      return;
    }

    try {
      setIsLoading(true);

      const params = { transactionMessage, signer: cosmosAddress };
      const responseFromWallet = await signClient!.request<{
        code: number;
      }>({
        topic: session!.topic,
        chainId: `cosmos:${process.env.REACT_APP_LACONICD_CHAIN_ID}`,
        request: {
          method: "cosmos_sendTransaction",
          params,
        },
      });
      if (responseFromWallet.code !== 0) {
        enqueueSnackbar("Transaction not sent", { variant: "error" });
      } else {
        navigate(`/onboarding-success/${cosmosAddress}`);
      }
    } catch (error) {
      console.error(error);
      enqueueSnackbar("Error in sending transaction", { variant: "error" });
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Box
      sx={{
        display: "flex",
        flexDirection: "column",
        marginTop: "100px",
        gap: "10px",
      }}
    >
      <Typography variant="h5">Send transaction to chain</Typography>
      <Typography variant="body1">Cosmos account: {cosmosAddress}</Typography>
      <Typography variant="body1">
        Onboarding message: <br />
      </Typography>
      <Box
        sx={{
          backgroundColor: "lightgray",
          padding: 3,
          wordWrap: "break-word",
        }}
      >
        <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>
          {JSON.stringify(onboardParticipantMsg, null, 2)}{" "}
        </pre>
      </Box>

      <Box>
        <LoadingButton
          variant="contained"
          onClick={async () => {
            await sendTransaction(onboardParticipantMsg);
          }}
          loading={isLoading}
        >
          Send transaction
        </LoadingButton>
      </Box>
      <SnackbarProvider />
    </Box>
  );
};

export default SignWithCosmos;
