import {
  useCallback, useEffect, useRef,
} 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 {
  WidgetApi, EventDirection, WidgetEventCapability,
} from 'matrix-widget-api';

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

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

  const widgetApi = useRef();

  useEffect(() => {
    const { searchParams } = new URL(window.location.href);
    const widgetId = searchParams.get('widgetId');

    widgetApi.current = widgetApi.current ?? new WidgetApi(widgetId, '*');

    widgetApi.current.on('ready', () => {
      const sendMessageCapability = WidgetEventCapability.forRoomEvent(
        EventDirection.Send,
        'm.room.message',
      );
      const sendRegisterIdentityCapability = WidgetEventCapability.forRoomEvent(
        EventDirection.Send,
        'io.dgov.identity.register',
      );
      widgetApi.current.requestCapability(sendMessageCapability.raw);
      widgetApi.current.requestCapability(sendRegisterIdentityCapability.raw);
      widgetApi.current.updateRequestedCapabilities();
    });

    widgetApi.current.start();
  }, []);

  /* -------------------------------------------------------------------------------- */
  /* --------------------------- BEGIN UI ACTIONS ----------------------------------- */
  /* -------------------------------------------------------------------------------- */

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

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

  // Sign and send a message
  const registerMatrixIdentity = useCallback(async () => {
    const message = new Date().toISOString();

    const signature = await provider.request({
      method: 'personal_sign',
      params: [message, account],
    });

    await widgetApi.current.sendRoomEvent('io.dgov.identity.register', {
      message,
      signature,
    });
  }, [provider, account]);

  /* -------------------------------------------------------------------------------- */
  /* --------------------------- END UI ACTIONS ------------------------------------- */
  /* -------------------------------------------------------------------------------- */

  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>
                    <Button onClick={() => registerMatrixIdentity()}>
                      Register Matrix Identity
                    </Button>
                  </div>
                </Stack>
              </Col>
            </Row>
          </Container>

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

export default Widget;
