import { FC, useEffect, useState } from 'react';
import { GSX_SERVICE_CALLED, GSX_SERVICE_FINISHED } from '../../constants';
import { WASMDataF } from '../../types/WASMData';
import { LoadingState } from '../../types/general';
import { CoherentCallZFWEntry, inRangeOf, loadAircraft, unloadAircraft } from '../../utils/utils';
import CGSelect from '../CGSelect/CGSelect';
import ActionBar from '../actionbar/ActionBar';

interface ZFWEntryProps {
  WASMData: WASMDataF;
  loadingState: LoadingState;
  setLoadingState: (newState: LoadingState) => void;
}

const ZFWEntryF: FC<ZFWEntryProps> = ({ WASMData, loadingState, setLoadingState }) => {
  const [CGTarget, setCGTarget] = useState(WASMData.targetPayload.CGTarget);
  const [fuel, setFuel] = useState(Math.round(WASMData.livePayload.fuel));
  const [ZFWTarget, setZFWTarget] = useState(Math.round(WASMData.targetPayload.total));
  const [fuelEnabled, setFuelEnabled] = useState(true);

  const ZFW = () => {
    if (loadingState !== 'loaded' && !GSXActive()) return ZFWTarget;

    return Math.round(WASMData.livePayload.total);
  };
  const ZFWValid = () => {
    return ZFW() <= WASMData.limits.maxZFW;
  };
  const GW = () => {
    return fuel + ZFW();
  };
  const GWValid = () => {
    return GW() <= WASMData.limits.maxTOW;
  };

  const GSXActive = () => {
    return (
      (WASMData.GSX.boardingState >= GSX_SERVICE_CALLED || WASMData.GSX.deboardingState >= GSX_SERVICE_CALLED) &&
      WASMData.GSX.deboardingState !== GSX_SERVICE_FINISHED
    );
  };

  const handleInput = (input: string, maxValue: number, setter: (value: number) => void) => {
    if (!input) {
      setter(0);
      return;
    }

    const converted = parseInt(input);
    if (converted) {
      if (converted < 0) setter(0);
      else if (converted > maxValue) setter(maxValue);
      else setter(converted);
    }
  };
  const handleInputZFW = (input: string) => {
    if (!input) return;

    const converted = parseInt(input);
    if (converted) {
      if (converted < 0) setZFWTarget(Math.round(WASMData.targetPayload.empty + WASMData.targetPayload.crew));
      else if (converted > WASMData.limits.maxZFW) setZFWTarget(WASMData.limits.maxZFW);
      else setZFWTarget(converted);
    }
  };
  const handleBlur = (input: string) => {
    const minZFW = Math.round(WASMData.targetPayload.empty + WASMData.targetPayload.crew);

    if (!input) {
      setZFWTarget(minZFW);
      return;
    }

    const converted = parseInt(input);
    if (converted) {
      if (converted < minZFW) setZFWTarget(minZFW);
      else if (converted > WASMData.limits.maxZFW) setZFWTarget(WASMData.limits.maxZFW);
      else setZFWTarget(converted);
    }

    updateData(converted);
  };

  useEffect(
    () =>
      setFuel((prev) => {
        if (prev > WASMData.limits.maxFuel) return WASMData.limits.maxFuel;
        return prev;
      }),
    [WASMData.userData.isER]
  );
  useEffect(() => {
    setFuelEnabled((prev) => (!prev ? inRangeOf(Math.round(WASMData.livePayload.fuel), fuel) : prev));
  }, [WASMData.livePayload.fuel]);

  const updateData = (_ZFWTarget?: number, _CGTarget?: number) => {
    CoherentCallZFWEntry(_ZFWTarget ?? ZFWTarget, _CGTarget ?? CGTarget);
  };

  return (
    <>
      <div className="block flex w-full flex-col opacity-100 transition-opacity duration-150 ease-linear mb-4">
        <div className="relative flex w-full items-center justify-between rounded-md bg-zinc-600 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>Fuel ({WASMData.userData.isImperial ? 'lbs' : 'kg'})</label>
            <input
              type="text"
              placeholder=""
              className={`w-1/2 rounded-lg border border-white bg-zinc-700 px-3 py-2 text-right`}
              value={fuel}
              onChange={(e) => handleInput(e.target.value, WASMData.limits.maxFuel, setFuel)}
              disabled={loadingState !== 'preview' || GSXActive()}
            />
            <button
              className="middle none center rounded-lg bg-green-600 px-6 py-3 font-sans text-xs font-bold uppercase text-white shadow-md shadow-green-500/20 transition-all hover:shadow-lg hover:shadow-green-500/40 focus:opacity-[0.85] focus:shadow-none active:opacity-[0.85] active:shadow-none disabled:pointer-events-none disabled:opacity-50 disabled:shadow-none"
              data-ripple-light="true"
              onClick={() => {
                SimVar.SetSimVarValue(
                  'L:MD11_EFB_PAYLOAD_FUEL',
                  'lbs',
                  WASMData.userData.isImperial ? fuel : fuel * 2.20462262185
                );
                SimVar.SetSimVarValue('L:MD11_EFB_READ_READY', 'bool', true);
                setFuelEnabled(WASMData.livePayload.fuel === fuel);
              }}
              disabled={loadingState !== 'preview' || !fuelEnabled || GSXActive()}
            >
              Load Fuel
            </button>
          </div>
        </div>
      </div>

      <div className="block flex w-full flex-col opacity-100 transition-opacity duration-150 ease-linear mb-4">
        <div className="relative flex w-full items-center justify-between rounded-t-md bg-zinc-600 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>Target ZFW ({WASMData.userData.isImperial ? 'lbs' : 'kg'})</label>
            <input
              type="text"
              placeholder=""
              className="w-1/2 rounded-lg border border-white bg-zinc-700 px-3 py-2 text-right focus:border-blue-600 focus:ring-blue-600"
              value={ZFWTarget}
              onChange={(e) => handleInputZFW(e.target.value)}
              onBlur={(e) => handleBlur(e.target.value)}
              disabled={loadingState !== 'preview' || GSXActive()}
            />
          </div>
        </div>
        <div className="relative flex w-full items-center justify-between rounded-b-md bg-zinc-700 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>
              Target ZFWCG ({WASMData.limits.minCG} - {WASMData.limits.maxCG})
            </label>
            <CGSelect
              minCG={WASMData.limits.minCG}
              maxCG={WASMData.limits.maxCG}
              value={CGTarget}
              disabled={loadingState !== 'preview' || GSXActive()}
              increase={() =>
                setCGTarget((prev) => {
                  const _new = prev + 0.1;
                  updateData(undefined, _new);
                  return _new;
                })
              }
              decrease={() =>
                setCGTarget((prev) => {
                  const _new = prev - 0.1;
                  updateData(undefined, _new);
                  return _new;
                })
              }
            />
          </div>
        </div>
      </div>

      <div className="block flex w-full flex-col opacity-100 transition-opacity duration-150 ease-linear mb-4">
        <div className="relative flex w-full items-center justify-between rounded-t-md bg-zinc-600 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>
              {loadingState !== 'loaded' && !GSXActive() ? 'Expected' : 'Actual'} ZFW (
              {WASMData.userData.isImperial ? 'lbs' : 'kg'})
            </label>
            <input
              type="text"
              placeholder=""
              className={`w-1/2 rounded-lg border ${ZFWValid() ? 'border-white' : 'border-red-500 text-red-500'} bg-zinc-700 px-3 py-2 text-right`}
              disabled
              value={ZFW()}
            />
          </div>
        </div>
        <div className="relative flex w-full items-center justify-between rounded-b-md bg-zinc-700 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>
              {loadingState !== 'loaded' && !GSXActive() ? 'Expected' : 'Actual'} GW (
              {WASMData.userData.isImperial ? 'lbs' : 'kg'})
            </label>
            <input
              type="text"
              placeholder=""
              className={`w-1/2 rounded-lg border ${GWValid() ? 'border-white' : 'border-red-500 text-red-500'} bg-zinc-700 px-3 py-2 text-right`}
              disabled
              value={GW()}
            />
          </div>
        </div>
      </div>

      <ActionBar
        loadingState={loadingState}
        loadDisabled={!GWValid()}
        GSXSync={WASMData.options.GSXSync}
        load={() => {
          setLoadingState('loaded');

          loadAircraft();
        }}
        unload={() => {
          setLoadingState('preview');

          unloadAircraft();
        }}
      />
    </>
  );
};

export default ZFWEntryF;
