import { useUserIdentity, useQuery, useMutation, useRefreshDispatcher, } from "@saasquatch/component-boilerplate";
import { gql } from "graphql-request";
import { useEffect, useReducer, useRef, useState, } from "@saasquatch/universal-hooks";
import confetti from "canvas-confetti";
const GET_EXCHANGE_LIST = gql `
  query getExchangeList {
    viewer {
      ... on User {
        visibleRewardExchangeItems(limit: 20, offset: 0) {
          data {
            key
            name
            description
            imageUrl
            available
            unavailableReasonCode
            ruleType
            sourceUnit
            sourceValue
            prettySourceValue
            sourceMinValue
            prettySourceMinValue
            sourceMaxValue
            prettySourceMaxValue
            destinationMinValue
            prettyDestinationMinValue
            destinationMaxValue
            prettyDestinationMaxValue
            globalRewardKey
            destinationUnit
            steps {
              sourceValue
              prettySourceValue
              destinationValue
              prettyDestinationValue
              available
              globalRewardKey
              unavailableReasonCode
              rewardInput
            }
          }
          totalCount
        }
      }
    }
  }
`;
const EXCHANGE = gql `
  mutation exchange($exchangeRewardInput: ExchangeRewardInput!) {
    exchangeReward(exchangeRewardInput: $exchangeRewardInput) {
      reward {
        id
        fuelTankCode
      }
    }
  }
`;
export function useRewardExchangeList(props) {
  var _a, _b, _c, _d, _e;
  const [exchangeState, setExchangeState] = useReducer((state, next) => ({
    ...state,
    ...next,
  }), {
    selectedItem: undefined,
    selectedStep: undefined,
    redeemStage: "chooseReward",
    amount: 0,
    exchangeError: false,
  });
  const [open, setOpen] = useState(false);
  const { selectedItem, selectedStep, redeemStage, amount, exchangeError } = exchangeState;
  const user = useUserIdentity();
  const [exchange, { data: exchangeResponse, loading: exchangeLoading, errors },] = useMutation(EXCHANGE);
  const { data, loading, refetch, errors: queryError, } = useQuery(GET_EXCHANGE_LIST, {}, !(user === null || user === void 0 ? void 0 : user.jwt));
  useEffect(() => {
    var _a, _b;
    if ((_b = (_a = exchangeResponse === null || exchangeResponse === void 0 ? void 0 : exchangeResponse.exchangeReward) === null || _a === void 0 ? void 0 : _a.reward) === null || _b === void 0 ? void 0 : _b.id) {
      setExchangeState({ redeemStage: "success", exchangeError: false });
    }
    if (!!errors) {
      setExchangeState({ exchangeError: true });
    }
  }, [exchangeResponse, errors]);
  const canvasRef = useRef();
  useEffect(() => {
    if (!canvasRef.current)
      return;
    const canvas = canvasRef.current;
    canvas.confetti =
      canvas.confetti || confetti.create(canvas, { resize: true });
    canvas.confetti();
  }, [canvasRef.current]);
  const { refresh } = useRefreshDispatcher();
  async function exchangeReward() {
    if (!selectedItem)
      return;
    let exchangeVariables = {
      accountId: user === null || user === void 0 ? void 0 : user.accountId,
      userId: user.id,
    };
    switch (selectedItem.ruleType) {
      case "FIXED_GLOBAL_REWARD":
        exchangeVariables = {
          ...exchangeVariables,
          redeemCreditInput: {
            amount: selectedItem.sourceValue,
            unit: selectedItem.sourceUnit,
          },
          globalRewardKey: selectedItem.globalRewardKey,
        };
        break;
      case "STEPPED_FIXED_GLOBAL_REWARD":
        exchangeVariables = {
          ...exchangeVariables,
          redeemCreditInput: {
            amount: selectedStep.sourceValue,
            unit: selectedItem.sourceUnit,
          },
          globalRewardKey: selectedStep.globalRewardKey,
        };
        break;
      case "VARIABLE_GLOBAL_REWARD":
        exchangeVariables = {
          ...exchangeVariables,
          redeemCreditInput: {
            amount: amount,
            unit: selectedItem.sourceUnit,
          },
          globalRewardKey: selectedItem.globalRewardKey,
          rewardInput: selectedStep.rewardInput,
        };
        break;
      case "VARIABLE_CREDIT_REWARD":
        exchangeVariables = {
          ...exchangeVariables,
          redeemCreditInput: {
            amount: amount,
            unit: selectedItem.sourceUnit,
          },
          rewardInput: {
            type: "CREDIT",
            unit: selectedItem.destinationUnit,
            assignedCredit: selectedStep.destinationValue,
          },
        };
        break;
      default:
        exchangeVariables = {
          ...exchangeVariables,
          ...selectedStep.rewardInput,
        };
    }
    await exchange({ exchangeRewardInput: exchangeVariables });
    refresh();
  }
  const resetState = (refresh) => {
    refresh && refetch();
    setExchangeState({
      amount: 0,
      selectedStep: undefined,
      selectedItem: undefined,
      exchangeError: false,
      redeemStage: "chooseReward",
    });
  };
  function setStage(stage) {
    setExchangeState({ redeemStage: stage });
  }
  function copyFuelTankCode() {
    var _a, _b;
    navigator.clipboard.writeText((_b = (_a = exchangeResponse === null || exchangeResponse === void 0 ? void 0 : exchangeResponse.exchangeReward) === null || _a === void 0 ? void 0 : _a.reward) === null || _b === void 0 ? void 0 : _b.fuelTankCode);
    setOpen(true);
    setTimeout(() => setOpen(false), 1000);
  }
  return {
    states: {
      content: {
        text: props,
      },
      selectedItem,
      redeemStage,
      amount,
      selectedStep,
      exchangeError,
      queryError: !!queryError,
      loading: loading || exchangeLoading,
      open,
      noExchangeOptions: ((_a = data === null || data === void 0 ? void 0 : data.viewer) === null || _a === void 0 ? void 0 : _a.visibleRewardExchangeItems.totalCount) === 0,
    },
    data: {
      exchangeList: (_c = (_b = data === null || data === void 0 ? void 0 : data.viewer) === null || _b === void 0 ? void 0 : _b.visibleRewardExchangeItems) === null || _c === void 0 ? void 0 : _c.data,
      fuelTankCode: (_e = (_d = exchangeResponse === null || exchangeResponse === void 0 ? void 0 : exchangeResponse.exchangeReward) === null || _d === void 0 ? void 0 : _d.reward) === null || _e === void 0 ? void 0 : _e.fuelTankCode,
    },
    callbacks: {
      exchangeReward,
      setExchangeState,
      setStage,
      resetState,
      copyFuelTankCode,
    },
    refs: {
      canvasRef,
    },
  };
}
