import React, { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { ethers } from "ethers";

import { Box, Typography } from '@mui/material';
import SumsubWebSdk from '@sumsub/websdk-react';
import { MessageHandler } from '@sumsub/websdk';
import { EventPayload } from '@sumsub/websdk/types/types';

import { config, fetchAccessToken, getAccessTokenExpirationHandler, options } from '../utils/sumsub';

const UserVerification = () => {
  const [kycId, setKycId] = useState<string>('unknown');
  const [applicationSubmitted, setApplicationSubmitted] = useState<boolean>(false);
  const [token, setToken] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(true);

  const location = useLocation();
  const navigate = useNavigate();

  const {message, cosmosAddress, receivedEthSig} = location.state as {
    message?: string;
    cosmosAddress?: string;
    receivedEthSig?: string;
  };

  const userId = cosmosAddress;

  useEffect(() => {
    const getToken = async (userId: string) => {
      const newToken = await fetchAccessToken(userId);

      setToken(newToken);
      setLoading(false);
    };

    if (userId) {
      getToken(userId).catch(error => {
        console.error(error);
        alert("Failed to fetch token");
      });
    }
  }, [userId]);

  useEffect(() => {
    if (applicationSubmitted && kycId !== '') {
      const kycIdHash = ethers.utils.sha256(ethers.utils.toUtf8Bytes(kycId));
      navigate("/sign-with-cosmos", {
        state: {
          message,
          cosmosAddress,
          receivedEthSig,
          subscriberIdHash: kycIdHash,
        }})
    }
  }, [applicationSubmitted, kycId, navigate, cosmosAddress, message, receivedEthSig]);

  const messageHandler: MessageHandler = (event, payload) => {
    console.log('sumsubEvent:', event, payload);

    if (event === 'idCheck.onApplicantLoaded') {
      setKycId((payload as EventPayload<'idCheck.onApplicantLoaded'>).applicantId);
    }

    if (event === 'idCheck.onApplicantSubmitted') {
      setApplicationSubmitted(true);
    }

    if (event === 'idCheck.onApplicantStatusChanged') {
      const applicantStatus = (payload as EventPayload<'idCheck.onApplicantStatusChanged'>).reviewStatus;

      if (applicantStatus === 'pending' || applicantStatus === 'completed') {
        setApplicationSubmitted(true);
      }
    }
  };

  return (
    <>
      <Box
        sx={{
          display: "flex",
          flexDirection: "column",
          marginTop: 12,
          gap: 1,
        }}
      >
        <Typography variant="h5">User verification</Typography>
        <div id="sumsub-websdk-container"></div>
      </Box>
      {!loading && token && userId && (
        <SumsubWebSdk
          accessToken={token}
          expirationHandler={getAccessTokenExpirationHandler(userId)}
          config={config}
          options={options}
          onMessage={messageHandler}
        />
      )}
    </>
  );
};

export default UserVerification;
