import { FC, useEffect, useMemo, useState } from 'react';
import { GSX_SERVICE_CALLED, GSX_SERVICE_FINISHED } from '../../constants';
import { LoadingState } from '../../types/general';
import { WASMDataPax } from '../../types/WASMData';
import OptionsPax from '../options/OptionsPax';
import Profile from '../profile/Profile';
import SBEntryPax from '../SBEntry/SBEntryPax';
import StationEntryPax from '../stationEntry/StationEntryPax';
import Tabbar from '../tabbar/Tabbar';
import ZFWEntryPax from '../zfwEntry/ZFWEntryPax';

interface PaxProps {
  WASMData: WASMDataPax;
  username?: string;
}

const Pax: FC<PaxProps> = ({ WASMData, username }) => {
  const [selectedTab, setSelectedTab] = useState(0);
  const [loadingState, setLoadingState] = useState<LoadingState>('preview');
  const [boardingState, setBoardingState] = useState(1);
  const [deboardingState, setDeboardingState] = useState(1);

  useEffect(() => {
    if (WASMData.GSX.boardingState > 1 &&  WASMData.GSX.boardingState < GSX_SERVICE_CALLED) return;

    setBoardingState(WASMData.GSX.boardingState);
    setDeboardingState(1);
  }, [WASMData.GSX.boardingState]);
  useEffect(() => {
    if (WASMData.GSX.deboardingState > 1 && WASMData.GSX.deboardingState < GSX_SERVICE_CALLED) return;

    setBoardingState(1);
    setDeboardingState(WASMData.GSX.deboardingState);
  }, [WASMData.GSX.deboardingState]);

  const upper1 = (overrideState: LoadingState = loadingState) => {
    if (overrideState !== 'loaded') return WASMData.targetPayload.business1;

    return WASMData.livePayload.business1;
  };
  const upper2 = (overrideState: LoadingState = loadingState) => {
    if (overrideState !== 'loaded') return WASMData.targetPayload.business2;

    return WASMData.livePayload.business2;
  };
  const upper3 = (overrideState: LoadingState = loadingState) => {
    if (overrideState !== 'loaded') return WASMData.targetPayload.economy1;

    return WASMData.livePayload.economy1;
  };
  const upper4 = (overrideState: LoadingState = loadingState) => {
    if (overrideState !== 'loaded') return WASMData.targetPayload.economy2;

    return WASMData.livePayload.economy2;
  };
  const lower1 = () => {
    if (loadingState !== 'loaded' && !GSXActive) return Math.round(WASMData.targetPayload.forwardCargo);

    return Math.round(WASMData.livePayload.forwardCargo);
  };
  const lower2 = () => {
    if (loadingState !== 'loaded' && !GSXActive) return Math.round(WASMData.targetPayload.rearCargo);

    return Math.round(WASMData.livePayload.rearCargo);
  };
  const OEW = () => {
    if (loadingState !== 'loaded' && !GSXActive) return Math.round(WASMData.targetPayload.empty);

    return Math.round(WASMData.livePayload.empty);
  };
  const crew = () => {
    if (loadingState !== 'loaded' && !GSXActive) return Math.round(WASMData.targetPayload.crew);

    return Math.round(WASMData.livePayload.crew);
  };

  const GSXActive = useMemo(() => {
    // Cases when active:
    // BOARDING called, running or done
    // DEBOARDING called, running or done
    // Cases when not active:
    // BOARDING not called, disabled
    // DEBOARDING not called, disabled
    // BOTH done

    console.log(
      'GSXActive',
      (boardingState >= GSX_SERVICE_CALLED || deboardingState >= GSX_SERVICE_CALLED) &&
        deboardingState !== GSX_SERVICE_FINISHED
    );

    return (
      (boardingState >= GSX_SERVICE_CALLED || deboardingState >= GSX_SERVICE_CALLED) &&
      deboardingState !== GSX_SERVICE_FINISHED
    );
  }, [boardingState, deboardingState]);

  const CGs = (): [string, boolean, string, boolean] => {
    if (loadingState !== 'loaded' && !GSXActive) {
      return [
        WASMData.targetPayload.ZFWCG.toFixed(1),
        WASMData.targetPayload.ZFWCG < WASMData.limits.minCG || WASMData.targetPayload.ZFWCG > WASMData.limits.maxCG,
        WASMData.targetPayload.TOCG.toFixed(1),
        WASMData.targetPayload.TOCG < WASMData.limits.minCG || WASMData.targetPayload.TOCG > WASMData.limits.maxCG,
      ];
    }

    if (WASMData.options.GSXSync && GSXActive && boardingState !== GSX_SERVICE_FINISHED) {
      return [
        WASMData.targetPayload.ZFWCG.toFixed(1),
        WASMData.targetPayload.ZFWCG < WASMData.limits.minCG || WASMData.targetPayload.ZFWCG > WASMData.limits.maxCG,
        WASMData.targetPayload.TOCG.toFixed(1),
        WASMData.targetPayload.TOCG < WASMData.limits.minCG || WASMData.targetPayload.TOCG > WASMData.limits.maxCG,
      ];
    }

    return [
      WASMData.livePayload.ZFWCG.toFixed(1),
      WASMData.livePayload.ZFWCG < WASMData.limits.minCG || WASMData.livePayload.ZFWCG > WASMData.limits.maxCG,
      WASMData.livePayload.TOCG.toFixed(1),
      WASMData.livePayload.TOCG < WASMData.limits.minCG || WASMData.livePayload.TOCG > WASMData.limits.maxCG,
    ];
  };

  useEffect(() => {
    setLoadingState(WASMData.loaded ? 'loaded' : 'preview');
  }, [WASMData.loaded]);

  return (
    <>
      <Profile
        type="PAX"
        isER={WASMData.userData.isER}
        upper1={`${upper1(GSXActive ? 'loaded' : loadingState)}`}
        upper1max={loadingState === 'loaded' || GSXActive ? `${upper1('preview')}` : `${WASMData.limits.business1}`}
        upper2={`${upper2(GSXActive ? 'loaded' : loadingState)}`}
        upper2max={loadingState === 'loaded' || GSXActive ? `${upper2('preview')}` : `${WASMData.limits.business2}`}
        upper3={`${upper3(GSXActive ? 'loaded' : loadingState)}`}
        upper3max={loadingState === 'loaded' || GSXActive ? `${upper3('preview')}` : `${WASMData.limits.economy1}`}
        upper4={`${upper4(GSXActive ? 'loaded' : loadingState)}`}
        upper4max={loadingState === 'loaded' || GSXActive ? `${upper4('preview')}` : `${WASMData.limits.economy2}`}
        lower1={`${lower1()}`}
        lower2={`${lower2()}`}
        OEW={`${OEW()}`}
        crew={`${crew()}`}
        unit={WASMData.userData.isImperial ? 'LBS' : 'KG'}
        inPreview={loadingState !== 'loaded' && !GSXActive}
        CGs={CGs()}
        done={
          WASMData.options.GSXSync
            ? boardingState === GSX_SERVICE_FINISHED && deboardingState !== GSX_SERVICE_FINISHED
            : loadingState !== 'preview'
        }
      />
      <Tabbar
        tabs={
          username ? ['Simbrief', 'ZFW', 'Passengers & Cargo', 'Options'] : ['ZFW', 'Passengers & Cargo', 'Options']
        }
        selectedTab={selectedTab}
        setSelectedTab={setSelectedTab}
      />
      {username && selectedTab === 0 && (
        <SBEntryPax
          WASMData={WASMData}
          loadingState={loadingState}
          setLoadingState={setLoadingState}
          gsxActive={GSXActive}
        />
      )}
      {((username && selectedTab === 1) || (!username && selectedTab === 0)) && (
        <ZFWEntryPax
          WASMData={WASMData}
          loadingState={loadingState}
          setLoadingState={setLoadingState}
          gsxActive={GSXActive}
        />
      )}
      {((username && selectedTab === 2) || (!username && selectedTab === 1)) && (
        <StationEntryPax
          WASMData={WASMData}
          loadingState={loadingState}
          setLoadingState={setLoadingState}
          gsxActive={GSXActive}
        />
      )}
      {((username && selectedTab === 3) || (!username && selectedTab === 2)) && (
        <OptionsPax WASMData={WASMData} loadingState={loadingState} gsxActive={GSXActive} />
      )}
    </>
  );
};

export default Pax;
