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 } from './constants';
import { WASMDataF, WASMDataPax } from './types/WASMData';
import { CommBusCall, CommBusEvent } from './types/general';

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

  // CommBus
  const usernameCallback = useCallback((username: string) => {
    setSBUsername(username);
  }, []);
  const wasmCallback = useCallback((data: string) => {
    setWASMData(JSON.parse(data));
  }, []);
  useEffect(() => {
    console.log(
      '[KHOFMANN TFDi MD-11 Load Manager] JS Version [VI]{version}[/VI]: process.env.NODE_ENV [VI]{date}[/VI]'
    );

    console.log('[KHOFMANN TFDi MD-11 Load Manager] Initialising CommBus');

    const commBus = RegisterViewListener('JS_LISTENER_COMM_BUS');

    commBus.on(CommBusEvent.TFDI_SIMBRIEF_USERNAME, usernameCallback);
    commBus.on(CommBusEvent.LIVE_DATA, wasmCallback);

    Coherent.call(COHERENT_COMM_BUS_WASM_CALL, CommBusCall.TFDI_SIMBRIEF_USERNAME, 'null');

    return () => {
      console.log('[KHOFMANN TFDi MD-11 Load Manager] De-Initialising CommBus');

      commBus.off(CommBusEvent.TFDI_SIMBRIEF_USERNAME, usernameCallback);
      commBus.off(CommBusEvent.LIVE_DATA, 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">
        {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;
