import { getEnvironmentSDK, useQuery } from "@saasquatch/component-boilerplate";
import { useEffect, useState } from "@saasquatch/stencil-hooks";
import { gql } from "graphql-request";
import { TAX_FORM_UPDATED_EVENT_KEY } from "../eventKeys";
import { useVeriffApp, VERIFF_COMPLETE_EVENT_KEY } from "../useVeriffApp";
const GET_USER_STATUS = gql `
  query getUserStatus {
    user: viewer {
      ... on User {
        id
        impactConnection {
          connected
          publisher {
            id
            payoutsAccount {
              hold
              holdReasons
            }
          }
        }
        rewards(limit: 1000) {
          data {
            statuses
            partnerFundsTransfer {
              id
              status
              dateScheduled
              dateCreated
              dateTransferred
            }
          }
        }
      }
    }
  }
`;
const GET_TAX_SETTING = gql `
  query getTenantSettings {
    tenantSettings {
      enforceUsTaxCompliance
    }
  }
`;
export function getStatus(data) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
  const account = (_b = (_a = data.user.impactConnection) === null || _a === void 0 ? void 0 : _a.publisher) === null || _b === void 0 ? void 0 : _b.payoutsAccount;
  const hasTransferredReward = (_e = (_d = (_c = data === null || data === void 0 ? void 0 : data.user) === null || _c === void 0 ? void 0 : _c.rewards) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.find((reward) => {
    var _a;
    return reward.statuses.includes("REDEEMED") &&
      ((_a = reward.partnerFundsTransfer) === null || _a === void 0 ? void 0 : _a.status) === "TRANSFERRED";
  });
  if (!((_g = (_f = data.user) === null || _f === void 0 ? void 0 : _f.impactConnection) === null || _g === void 0 ? void 0 : _g.connected) || !account)
    return "INFORMATION_REQUIRED";
  const currentTaxDocument = (_j = (_h = data.user.impactConnection) === null || _h === void 0 ? void 0 : _h.publisher) === null || _j === void 0 ? void 0 : _j.currentTaxDocument;
  if (((_k = account.holdReasons) === null || _k === void 0 ? void 0 : _k.includes("NO_W9_DOCUMENT")) && !currentTaxDocument)
    return "OVER_W9_THRESHOLD";
  if ((_l = account.holdReasons) === null || _l === void 0 ? void 0 : _l.includes("IDV_CHECK_REQUIRED"))
    return "VERIFICATION:REQUIRED";
  if ((_m = account.holdReasons) === null || _m === void 0 ? void 0 : _m.includes("IDV_CHECK_REQUIRED_INTERNAL"))
    return "VERIFICATION:INTERNAL";
  if ((_o = account.holdReasons) === null || _o === void 0 ? void 0 : _o.includes("IDV_CHECK_REVIEW_INTERNAL"))
    return "VERIFICATION:REVIEW";
  if ((_p = account.holdReasons) === null || _p === void 0 ? void 0 : _p.includes("IDV_CHECK_FAILED_INTERNAL"))
    return "VERIFICATION:FAILED";
  // only show banner for NEW_PAYEE_REVIEW if a PFT was created
  if (((_q = account.holdReasons) === null || _q === void 0 ? void 0 : _q.includes("NEW_PAYEE_REVIEW")) && hasTransferredReward)
    return "NEW_PAYEE_REVIEW";
  if ((_r = account.holdReasons) === null || _r === void 0 ? void 0 : _r.includes("NEW_PAYEE_REVIEW"))
    return "DONE";
  if ((_s = account.holdReasons) === null || _s === void 0 ? void 0 : _s.includes("PAYMENT_HOLD_ON_CHANGE"))
    return "PAYMENT_HOLD_ON_CHANGE";
  if ((_t = account.holdReasons) === null || _t === void 0 ? void 0 : _t.includes("BENEFICIARY_NAME_INVALID"))
    return "BENEFICIARY_NAME_INVALID";
  if ((_u = account.holdReasons) === null || _u === void 0 ? void 0 : _u.includes("BENEFICIARY_NAME_MISMATCH"))
    return "BENEFICIARY_NAME_MISMATCH";
  if ((_v = account.holdReasons) === null || _v === void 0 ? void 0 : _v.includes("BANK_TAX_NAME_MISMATCH"))
    return "BANK_TAX_NAME_MISMATCH";
  if ((_w = account.holdReasons) === null || _w === void 0 ? void 0 : _w.includes("WITHDRAWAL_SETTINGS_INVALID"))
    return "WITHDRAWAL_SETTINGS_INVALID";
  if ((_x = account.holdReasons) === null || _x === void 0 ? void 0 : _x.includes("PAYMENT_RETURNED"))
    return "PAYMENT_RETURNED";
  if (account.hold)
    return "HOLD";
  return "DONE";
}
export function usePayoutStatus(props) {
  var _a;
  const { type } = getEnvironmentSDK();
  const { loading, data, errors, refetch } = useQuery(GET_USER_STATUS, {});
  const { data: taxSettingRes } = useQuery(GET_TAX_SETTING, {});
  const { render, loading: veriffLoading, errors: veriffErrors, } = useVeriffApp();
  const [status, setStatus] = useState(undefined);
  const enforceUsTaxComplianceOption = (_a = taxSettingRes === null || taxSettingRes === void 0 ? void 0 : taxSettingRes.tenantSettings) === null || _a === void 0 ? void 0 : _a.enforceUsTaxCompliance;
  useEffect(() => {
    if (!data)
      return;
    const s = getStatus(data);
    setStatus(s);
  }, [data]);
  useEffect(() => {
    const cb = () => refetch();
    window.addEventListener(TAX_FORM_UPDATED_EVENT_KEY, cb);
    window.addEventListener(VERIFF_COMPLETE_EVENT_KEY, cb);
    return () => {
      window.removeEventListener(TAX_FORM_UPDATED_EVENT_KEY, cb);
      window.removeEventListener(VERIFF_COMPLETE_EVENT_KEY, cb);
    };
  }, []);
  const onTermsClick = () => {
    let url = props.cashPayoutsPageUrl;
    if (url.includes("#"))
      url = url.split("#")[0];
    if (status === "INFORMATION_REQUIRED")
      url += "#1";
    else if (status === "OVER_W9_THRESHOLD" &&
      enforceUsTaxComplianceOption === "CASH_ONLY_DEFER_W9")
      url += "#3";
    window.history.pushState(null, "", url);
  };
  const onPaymentInfoClick = () => {
    let url = props.cashPayoutsPageUrl;
    url += "#4";
    window.history.pushState(null, "", url);
  };
  const onNewFormClick = () => {
    let url = props.cashPayoutsPageUrl;
    url += "#3";
    window.history.pushState(null, "", url);
  };
  return {
    states: {
      loading,
      veriffLoading,
      status,
      error: !!errors,
      enforceUsTaxComplianceOption,
    },
    data: { type },
    text: props.getTextProps(),
    callbacks: {
      onTermsClick,
      onClick: render,
      onPaymentInfoClick,
      onNewFormClick,
    },
  };
}
