import { useCallback } from 'react';
import Button from 'react-bootstrap/Button';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Stack from 'react-bootstrap/Stack';

import MainTabs from './components/tabs';
import useMainContext from './contexts/useMainContext';

function WebApp() {
  const {
    sdk, connected, chainId, account, reputation, totalReputation, balanceEther,
  } = useMainContext();

  const connect = useCallback(async () => {
    try {
      await sdk?.connect();
      console.log('connected');
      console.log('connected', connected);
    } catch (err) {
      console.warn('failed to connect..', err);
    }
  }, [sdk, connected]);

  const disconnect = useCallback(async () => {
    try {
      sdk?.terminate();
    } catch (err) {
      console.warn('failed to disconnect..', err);
    }
  }, [sdk]);

  return (
    <>
      {!connected && <Button onClick={() => connect()}>Connect</Button>}

      {connected && (
        <>
          <Container>
            <Row>
              <Col>
                {chainId !== '0xaa36a7' && (
                <div>
                  Please switch MetaMask to Sepolia testnet!
                </div>

                )}
              </Col>
            </Row>
            <Row>
              <Col>
                <Stack>
                  <div>
                    {chainId && `Chain ID: ${chainId}`}
                  </div>
                  <div>
                    {`Account: ${account}`}
                  </div>
                  <div>
                    {`Balance: ${balanceEther} ETH`}
                  </div>
                </Stack>
              </Col>
              <Col>
                <Stack>
                  <div>
                    {`Your REP: ${reputation?.toString()}`}
                  </div>
                  <div>
                    {`Total REP: ${totalReputation?.toString()}`}
                  </div>
                  <div>
                    <Button onClick={() => disconnect()}>Disconnect</Button>
                  </div>
                </Stack>
              </Col>
            </Row>
          </Container>

          <MainTabs />
        </>
      )}
    </>
  );
}

export default WebApp;
