import { useMutation, useQuery, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { useEffect, useState } from "@saasquatch/universal-hooks";
import { gql } from "graphql-request";
import jsonpointer from "jsonpointer";
const GET_USER = gql `
  query {
    viewer {
      ... on User {
        id
        accountId
        marketingEmailOptIn
      }
    }
  }
`;
const UPSERT_USER = gql `
  mutation ($userInput: UserInput!) {
    upsertUser(userInput: $userInput) {
      id
      marketingEmailOptIn
    }
  }
`;
// view doesn't tolerate undefined, even when we're loading
const defaultFormState = {
  marketingEmailOptIn: false,
  errors: {},
  error: "",
};
export function usePortalProfile(props) {
  const userIdent = useUserIdentity();
  const [success, setSuccess] = useState(false);
  const [userData, setUserData] = useState(undefined);
  const [formState, setFormState] = useState(defaultFormState);
  const userDataResponse = useQuery(GET_USER, {}, !(userIdent === null || userIdent === void 0 ? void 0 : userIdent.jwt));
  const [upsertUser, upsertUserResponse] = useMutation(UPSERT_USER);
  useEffect(() => {
    if (upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.loading)
      return;
    if (upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.errors) {
      setFormState((state) => {
        var _a, _b, _c;
        return ({
          ...state,
          error: (_c = (_b = (_a = upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.errors) === null || _a === void 0 ? void 0 : _a.response) === null || _b === void 0 ? void 0 : _b.errors) === null || _c === void 0 ? void 0 : _c[0].message,
        });
      });
    }
    else {
      setUserData((state) => {
        var _a;
        return ({
          ...state,
          ...(_a = upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.data) === null || _a === void 0 ? void 0 : _a.upsertUser,
        });
      });
      if (upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.data)
        setSuccess(true);
    }
  }, [upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.loading]);
  useEffect(() => {
    var _a, _b;
    setUserData((data) => { var _a; return ({ ...data, ...(_a = userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.data) === null || _a === void 0 ? void 0 : _a.viewer }); });
    setFormState({
      ...defaultFormState,
      ...(_a = userDataResponse.data) === null || _a === void 0 ? void 0 : _a.viewer,
      ...(_b = upsertUserResponse.data) === null || _b === void 0 ? void 0 : _b.upsertUser,
    });
  }, [userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.data]);
  useEffect(() => {
    var _a, _b;
    if ((_a = upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.errors) === null || _a === void 0 ? void 0 : _a.message) {
      setFormState({
        ...(_b = userDataResponse.data) === null || _b === void 0 ? void 0 : _b.viewer,
        error: props.networkRequestMessage,
      });
    }
  }, [upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.errors]);
  const onSubmit = (event) => {
    var _a;
    setSuccess(false);
    const formData = (_a = event.detail) === null || _a === void 0 ? void 0 : _a.formData;
    formData === null || formData === void 0 ? void 0 : formData.forEach((value, key) => {
      jsonpointer.set(formData, key, value);
    });
    upsertUser({
      userInput: {
        id: userIdent === null || userIdent === void 0 ? void 0 : userIdent.id,
        accountId: userIdent === null || userIdent === void 0 ? void 0 : userIdent.accountId,
        marketingEmailOptIn: Boolean(formData.marketingEmailOptIn),
      },
    });
    setFormState((s) => ({ ...s, errors: {}, error: "" }));
    return;
  };
  return {
    states: {
      success,
      loading: (userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.loading) || upsertUserResponse.loading,
      submitDisabled: false,
      formState,
      user: userData,
      text: {
        emailPreferencesHeader: props.emailPreferencesHeader,
        marketingCheckboxLabel: props.marketingCheckboxLabel,
        submitChangeButtonText: props.submitChangeButtonText,
        successMessage: props.successMessage,
      },
    },
    callbacks: {
      onSubmit,
      setChecked: (value) => setFormState({ ...formState, marketingEmailOptIn: value }),
    },
  };
}
