import React from "react";
import { Outlet, useLocation, useNavigate } from "react-router-dom";

import { Avatar, Button, Stack, Typography } from "@mui/material";

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

const SignPageLayout = () => {
  const { disconnect, session } = useWalletConnectContext();
  const navigate = useNavigate();
  const location = useLocation();

  const disconnectHandler = async () => {
    const { pathname } = location;
    const redirectTo = pathname ? pathname.substring(1) : "";

    await disconnect();
    navigate(`/connect-wallet?redirectTo=${redirectTo}`);
  };

  return (
    <Stack justifyContent="center" alignItems="center">
      <Container
        boxProps={{
          sx: {
            display: "flex",
            flexDirection: "row",
            justifyContent: "space-between",
            mb: 4,
          },
        }}
      >
        {session && (
          <Stack spacing={0.5}>
            <div
              style={{
                display: "flex",
                flexDirection: "row",
                alignItems: "flex-end",
              }}
            >
              <Typography variant="body2">
                <b>Connected to:</b> {session.peer.metadata.name}
              </Typography>
              <Avatar
                variant="square"
                alt="Peer logo"
                src={session.peer.metadata.icons[0]}
                sx={{
                  width: 20,
                  height: 20,
                  marginLeft: 1,
                  paddingBottom: 0.5,
                }}
              />
            </div>
            <Typography variant="body2">
              <b>Session ID:</b> {session.topic}
            </Typography>
          </Stack>
        )}
        <Button
          variant="outlined"
          color="error"
          onClick={disconnectHandler}
          sx={{ color: "text.primary" }}
        >
          Disconnect
        </Button>
      </Container>
      <Outlet />
    </Stack>
  );
};

export default SignPageLayout;
