import { useLocale, useParentQueryValue, useQuery, useSetParent, } from "@saasquatch/component-boilerplate";
import { useEffect, useState } from "@saasquatch/universal-hooks";
import { DateTime } from "luxon";
import { vatLabels } from "../countries";
import { getStatus, } from "../sqm-payout-status-alert/usePayoutStatus";
import { TAX_CONTEXT_NAMESPACE, TAX_FORM_CONTEXT_NAMESPACE, USER_QUERY_NAMESPACE, } from "../data";
import { INDIRECT_TAX_PROVINCES, INDIRECT_TAX_SPAIN_REGIONS, } from "../subregions";
import { useVeriffApp, VERIFF_COMPLETE_EVENT_KEY } from "../useVeriffApp";
import { taxTypeToName } from "../utils";
import { gql } from "graphql-request";
const GET_TAX_SETTING = gql `
  query getTenantSettings {
    tenantSettings {
      enforceUsTaxCompliance
    }
  }
`;
function getCountryName(countryCode, locale) {
  if (!countryCode)
    return undefined;
  // @ts-ignore: DisplayNames exists on Intl
  return new Intl.DisplayNames([(locale === null || locale === void 0 ? void 0 : locale.replace("_", "-")) || "en-US"], {
    type: "region",
  }).of([countryCode]);
}
function getSubRegionName(regionCode) {
  var _a;
  if (!regionCode)
    return "";
  // Impact adds an underscore to some regions
  const standardCode = regionCode.replace("_", "");
  const regions = [...INDIRECT_TAX_PROVINCES, ...INDIRECT_TAX_SPAIN_REGIONS];
  return (_a = regions.find((r) => r.regionCode === standardCode)) === null || _a === void 0 ? void 0 : _a.displayName;
}
function getIndirectTaxType(taxInformation) {
  var _a;
  const regions = [...INDIRECT_TAX_PROVINCES, ...INDIRECT_TAX_SPAIN_REGIONS];
  if (taxInformation === null || taxInformation === void 0 ? void 0 : taxInformation.indirectTaxRegion) {
    const standardRegion = taxInformation.indirectTaxRegion.replace("_", "");
    const taxType = (_a = regions.find((r) => r.regionCode === standardRegion)) === null || _a === void 0 ? void 0 : _a.taxType;
    if (taxType)
      return taxType;
  }
  // Spain regions only have VAT type
  if (taxInformation === null || taxInformation === void 0 ? void 0 : taxInformation.withholdingTaxCountryCode)
    return "VAT";
  if (taxInformation === null || taxInformation === void 0 ? void 0 : taxInformation.indirectTaxCountryCode) {
    return vatLabels[taxInformation.indirectTaxCountryCode] || "Indirect Tax";
  }
  return "Indirect Tax";
}
export const useTaxAndCashDashboard = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
  const setStep = useSetParent(TAX_CONTEXT_NAMESPACE);
  const setContext = useSetParent(TAX_FORM_CONTEXT_NAMESPACE);
  const [showDialog, setShowDialog] = useState(false);
  const { render, loading: veriffLoading, errors: veriffErrors, } = useVeriffApp();
  const { data: taxSettingRes } = useQuery(GET_TAX_SETTING, {});
  const locale = useLocale();
  useEffect(() => {
    // Clear override context once on submitted
    setContext({});
    if (window.location.hash) {
      setContext({
        overrideNextStep: "/dashboard",
        overrideBackStep: "/dashboard",
        hideSteps: true,
      });
      setStep(`/${window.location.hash.replace("#", "")}`);
    }
  }, []);
  const { data, loading, errors: userError, refetch, } = useParentQueryValue(USER_QUERY_NAMESPACE);
  const publisher = (_b = (_a = data === null || data === void 0 ? void 0 : data.user) === null || _a === void 0 ? void 0 : _a.impactConnection) === null || _b === void 0 ? void 0 : _b.publisher;
  const documentType = publisher === null || publisher === void 0 ? void 0 : publisher.requiredTaxDocumentType;
  const submissionDate = (_c = publisher === null || publisher === void 0 ? void 0 : publisher.currentTaxDocument) === null || _c === void 0 ? void 0 : _c.dateCreated;
  const dateSubmitted = submissionDate
    ? DateTime.fromMillis(submissionDate).toFormat("LLL dd, yyyy")
    : undefined;
  const onEditPayoutInfo = () => {
    setContext({
      overrideNextStep: "/dashboard",
      overrideBackStep: "/dashboard",
      hideSteps: true,
    });
    setStep("/4");
  };
  const onNewFormClick = () => {
    setShowDialog(false);
    setContext({
      overrideNextStep: "/dashboard",
      overrideBackStep: "/dashboard",
      hideSteps: true,
    });
    setStep("/3");
  };
  const provinceName = (_d = INDIRECT_TAX_PROVINCES.find((p) => { var _a; return p.regionCode === ((_a = publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation) === null || _a === void 0 ? void 0 : _a.indirectTaxRegion); })) === null || _d === void 0 ? void 0 : _d.displayName;
  const payoutStatus = data ? getStatus(data) : null;
  useEffect(() => {
    const cb = () => refetch();
    window.addEventListener(VERIFF_COMPLETE_EVENT_KEY, cb);
    return () => {
      window.removeEventListener(VERIFF_COMPLETE_EVENT_KEY, cb);
    };
  }, []);
  const enforceUsTaxComplianceOption = (_e = taxSettingRes === null || taxSettingRes === void 0 ? void 0 : taxSettingRes.tenantSettings) === null || _e === void 0 ? void 0 : _e.enforceUsTaxCompliance;
  return {
    states: {
      dateSubmitted,
      documentType,
      canEditPayoutInfo: publisher === null || publisher === void 0 ? void 0 : publisher.brandedSignup,
      documentTypeString: taxTypeToName(documentType),
      status: (_f = publisher === null || publisher === void 0 ? void 0 : publisher.currentTaxDocument) === null || _f === void 0 ? void 0 : _f.status,
      subRegion: getSubRegionName((_g = publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation) === null || _g === void 0 ? void 0 : _g.indirectTaxRegion),
      subRegionTaxNumber: (_h = publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation) === null || _h === void 0 ? void 0 : _h.withholdingTaxId,
      qstNumber: (_j = publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation) === null || _j === void 0 ? void 0 : _j.additionalTaxId,
      indirectTaxType: getIndirectTaxType(publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation),
      indirectTaxNumber: (_k = publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation) === null || _k === void 0 ? void 0 : _k.indirectTaxId,
      isBusinessEntity: (publisher === null || publisher === void 0 ? void 0 : publisher.requiredTaxDocumentType) === "W8BENE",
      province: provinceName,
      country: getCountryName((_l = publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation) === null || _l === void 0 ? void 0 : _l.indirectTaxCountryCode, locale),
      notRegistered: !((_m = publisher === null || publisher === void 0 ? void 0 : publisher.taxInformation) === null || _m === void 0 ? void 0 : _m.indirectTaxId),
      noFormNeeded: !documentType,
      disabled: loading,
      loading,
      loadingError: !!(userError === null || userError === void 0 ? void 0 : userError.message),
      showNewFormDialog: showDialog,
      hasHold: !!((_o = publisher === null || publisher === void 0 ? void 0 : publisher.payoutsAccount) === null || _o === void 0 ? void 0 : _o.hold),
      payoutStatus,
      veriffLoading,
      enforceUsTaxComplianceOption,
    },
    callbacks: {
      onClick: () => setShowDialog(true),
      onVerifyClick: () => render(),
      onEditPayoutInfo,
      onNewFormCancel: () => setShowDialog(false),
      onNewFormClick,
    },
    text: props.getTextProps(),
  };
};
