import { FC, useEffect, useState } from 'react';
import { LoadingState } from '../../types/general';
import { WASMDataPax } from '../../types/WASMData';
import { CoherentCallStationEntryPax, inRangeOf, loadAircraft, unloadAircraft } from '../../utils/utils';
import ActionBar from '../actionbar/ActionBar';
import Input from '../input/Input';

interface StationEntryProps {
  WASMData: WASMDataPax;
  loadingState: LoadingState;
  gsxActive: boolean;
  setLoadingState: (newState: LoadingState) => void;
}

const StationEntryPax: FC<StationEntryProps> = ({ WASMData, loadingState, gsxActive, setLoadingState }) => {
  const [business1, setBusiness1] = useState(WASMData.targetPayload.business1);
  const [business2, setBusiness2] = useState(WASMData.targetPayload.business2);
  const [economy1, setEconomy1] = useState(WASMData.targetPayload.economy1);
  const [economy2, setEconomy2] = useState(WASMData.targetPayload.economy2);
  const [forwardCargo, setForwardCargo] = useState(WASMData.targetPayload.forwardCargo);
  const [rearCargo, setRearCargo] = useState(WASMData.targetPayload.rearCargo);
  const [fuel, setFuel] = useState(Math.round(WASMData.livePayload.fuel));
  const [fuelEnabled, setFuelEnabled] = useState(true);

  const ZFW = () => {
    if (loadingState !== 'loaded' && !gsxActive) return Math.round(WASMData.targetPayload.total);

    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 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 updateData = () => {
    CoherentCallStationEntryPax(business1, business2, economy1, economy2, forwardCargo, rearCargo);
  };

  useEffect(() => updateData(), [business1, business2, economy1, economy2, forwardCargo, rearCargo]);
  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]);

  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={(value) => handleInput(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>Business</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={business1}
              onChange={(value) => handleInput(value, WASMData.limits.business1, setBusiness1)}
              disabled={loadingState !== 'preview' || gsxActive}
            />
          </div>
        </div>
        <div className="relative flex w-full items-center justify-between bg-zinc-700 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>Premium Economy</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={business2}
              onChange={(value) => handleInput(value, WASMData.limits.business2, setBusiness2)}
              disabled={loadingState !== 'preview' || gsxActive}
            />
          </div>
        </div>
        <div className="relative flex w-full items-center justify-between bg-zinc-600 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>Forward Economy</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={economy1}
              onChange={(value) => handleInput(value, WASMData.limits.economy1, setEconomy1)}
              disabled={loadingState !== 'preview' || gsxActive}
            />
          </div>
        </div>
        <div className="relative flex w-full items-center justify-between bg-zinc-700 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>Aft Economy</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={economy2}
              onChange={(value) => handleInput(value, WASMData.limits.economy2, setEconomy2)}
              disabled={loadingState !== 'preview' || gsxActive}
            />
          </div>
        </div>
        <div className="relative flex w-full items-center justify-between bg-zinc-600 p-2 px-4">
          <div className="flex w-full items-center justify-between text-xs">
            <label>Forward Cargo ({WASMData.userData.isImperial ? 'lbs' : 'kg'})</label>
            <Input
              type="text"
              topKeyboard
              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={forwardCargo}
              onChange={(value) => handleInput(value, WASMData.limits.forwardCargo, setForwardCargo)}
              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>Aft Cargo ({WASMData.userData.isImperial ? 'lbs' : 'kg'})</label>
            <Input
              type="text"
              topKeyboard
              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={rearCargo}
              onChange={(value) => handleInput(value, WASMData.limits.rearCargo, setRearCargo)}
              disabled={loadingState !== 'preview' || gsxActive}
            />
          </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={!ZFWValid() || !GWValid()}
        GSXSync={WASMData.options.GSXSync}
        load={() => {
          setLoadingState('loaded');

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

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

export default StationEntryPax;
