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';

interface IAppProps {
  commBus: ViewListener.ViewListener;
}

const App: FC<IAppProps> = ({ commBus }) => {
  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');

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

    setTimeout(() => {
      Coherent.call(COHERENT_COMM_BUS_WASM_CALL, TFDI_SIMBRIEF_USERNAME_CALL, 'null');
    }, 1000);

    return () => {
      commBus.off(TFDI_SIMBRIEF_USERNAME_EVENT, usernameCallback);
      commBus.off(COMM_BUS_LIVE_DATA_EVENT, wasmCallback);
    };
  }, []);

  return (
    <div className="flex w-full justify-center pt-2 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;
