import { FC, StrictMode, useCallback, useEffect, useState } from 'react';
import Pax from './components/pax/Pax';
import { COHERENT_COMBUS_WASM_CALL, COMM_BUS_LIVE_DATA_EVENT, TFDI_SIMBRIEF_USERNAME_EVENT } from './constants';
import { WASMDataPax } from './types/WASMData';

interface IAppProps {
  commBus: ViewListener.ViewListener;
}

const App: FC<IAppProps> = ({ commBus }) => {
  const [SBUsername, setSBUsername] = useState<string>();
  //FIXME: TS Type
  const [WASMData, setWASMData] = useState<WASMDataPax>();
  const [isReady, setIsReady] = useState(false);

  // Main Loop for Live Payload
  // 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(COMM_BUS_LIVE_DATA_EVENT, usernameCallback);
    commBus.on(COMM_BUS_LIVE_DATA_EVENT, wasmCallback);

    setTimeout(() => {
      Coherent.call(COHERENT_COMBUS_WASM_CALL, TFDI_SIMBRIEF_USERNAME_EVENT, 'null');
    }, 1000);

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

  return (
    <StrictMode>
      <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 ? (
              <>Not yet Implemented</>
            ) : (
              <Pax WASMData={WASMData} username={SBUsername} />
            )
          ) : (
            <h1 className="text-sm font-medium">LOADING</h1>
          )}
        </div>
      </div>
    </StrictMode>
  );
};

export default App;
