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

import {
  Button,
  Dialog,
  DialogContent,
  DialogActions,
  Box,
  Typography,
} from "@mui/material";

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

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

  const { ethAddress, ethSignature } = useParams();

  const [openModal, setOpenModal] = useState(false);
  const [cosmosSignature, setCosmosSignature] = useState("");

  const location = useLocation();
  const innerMessage = location.state;
  const cosmosAddress = innerMessage.address;

  const displayAttestation = useMemo(() => {
    return canonicalStringify(
      {
        payload: {
          msg: "Onboarding my Azimuth ID onto UrbitChain",
          address: ethAddress,
          payload: innerMessage,
        },
        signatures: [cosmosSignature, ethSignature],
      },
      null,
      2
    );
  }, [ethAddress, cosmosSignature, ethSignature, innerMessage]);

  const message = useMemo(() => {
    return canonicalStringify(
      {
        msg: "Onboarding my Azimuth ID onto UrbitChain",
        address: ethAddress,
        payload: innerMessage,
      },
      null,
      2
    );
  }, [ethAddress, innerMessage]);

  const signCosmos = async () => {
    try {
      if (ethAddress) {
        const signDoc = {
          msgs: [],
          fee: { amount: [], gas: "23" },
          chain_id: "cosmos:cosmoshub-4",
          memo: message,
          account_number: "7",
          sequence: "54",
        };

        const params = { signerAddress: cosmosAddress, signDoc };

        const signedMessage = await signClient!.request<{ signature: string }>({
          topic: session!.topic,
          chainId: "cosmos:cosmoshub-4",
          request: {
            method: "cosmos_signAmino",
            params,
          },
        });
        setOpenModal(true);
        setCosmosSignature(signedMessage.signature);
      }
    } catch (error) {
      console.log("err in signing ", error);
      setOpenModal(false);
      enqueueSnackbar("Error signing message", { variant: "error" });
    }
  };

  return (
    <Box
      style={{
        display: "flex",
        flexDirection: "column",
        marginTop: "100px",
        gap: "10px",
      }}
    >
      <Typography variant="h5">Sign with cosmos key</Typography>
      <Typography variant="body1">Cosmos account: {cosmosAddress}</Typography>
      <Typography variant="body1">
        Message: <br />
      </Typography>
      <Box
        sx={{
          backgroundColor: "lightgray",
          padding: 3,
          wordWrap: "break-word",
        }}
      >
        <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>{message} </pre>
      </Box>

      <Box>
        <Button
          variant="contained"
          onClick={() => {
            signCosmos();
          }}
        >
          Sign with cosmos
        </Button>
      </Box>
      <Dialog
        open={openModal}
        onClose={() => {
          setOpenModal(false);
        }}
        aria-labelledby="alert-dialog-title"
        aria-describedby="alert-dialog-description"
        maxWidth="md"
      >
        <DialogContent>
          Attested message to be broadcasted on chain
          <Box
            sx={{
              backgroundColor: "lightgray",
              padding: 3,
              wordWrap: "break-word",
            }}
          >
            <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>
              {displayAttestation}{" "}
            </pre>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setOpenModal(false)}>Close</Button>
        </DialogActions>
      </Dialog>

      <SnackbarProvider />
    </Box>
  );
};

export default SignWithCosmos;
