import { FC, useCallback, useEffect, useState } from 'react';
import Freighter from './components/freighter/Freighter';
import Pax from './components/pax/Pax';
import {
  COHERENT_COMM_BUS_WASM_CALL,
  COMM_BUS_LIVE_DATA_EVENT,
  TFDI_SIMBRIEF_USERNAME_CALL,
  TFDI_SIMBRIEF_USERNAME_EVENT,
} from './constants';
import { WASMDataF, WASMDataPax } from './types/WASMData';

const App: FC = () => {
  const [SBUsername, setSBUsername] = useState<string>();
  const [WASMData, setWASMData] = useState<WASMDataPax | WASMDataF>();
  const [isReady, setIsReady] = useState(false);

  // CommBus
  const usernameCallback = useCallback((username: string) => {
    setSBUsername(username);
    setIsReady(true);
  }, []);
  const wasmCallback = useCallback((data: string) => {
    setWASMData(JSON.parse(data));
  }, []);
  useEffect(() => {
    console.log('Initializing CommBus');

    const commBus = RegisterViewListener('JS_LISTENER_COMM_BUS');

    commBus.on(TFDI_SIMBRIEF_USERNAME_EVENT, usernameCallback);
    commBus.on(COMM_BUS_LIVE_DATA_EVENT, wasmCallback);

    Coherent.call(COHERENT_COMM_BUS_WASM_CALL, TFDI_SIMBRIEF_USERNAME_CALL, 'null');

    return () => {
      console.log('De-Initializing CommBus');

      commBus.off(TFDI_SIMBRIEF_USERNAME_EVENT, usernameCallback);
      commBus.off(COMM_BUS_LIVE_DATA_EVENT, wasmCallback);

      commBus.unregister();
    };
  }, []);

  return (
    <div className="flex w-full justify-center py-5 bg-zinc-900">
      <div className="flex w-3/4 flex-col items-center">
        {isReady && WASMData ? (
          WASMData.userData.isCargo ? (
            <Freighter WASMData={WASMData as WASMDataF} username={SBUsername} />
          ) : (
            <Pax WASMData={WASMData as WASMDataPax} username={SBUsername} />
          )
        ) : (
          <h1 className="text-sm font-medium">LOADING</h1>
        )}
      </div>
    </div>
  );
};

export default App;
