import { useQuery, useMutation, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { gql } from "graphql-request";
import { useEffect, useState } from "@saasquatch/universal-hooks";
import { isEmpty } from "../../utilities";
const GET_USER = gql `
  query {
    viewer {
      ... on User {
        id
        accountId
        firstName
        lastName
        email
        countryCode
      }
    }
  }
`;
const UPSERT_USER = gql `
  mutation (
    $id: String!
    $accountId: String!
    $firstName: String!
    $lastName: String!
  ) {
    upsertUser(
      userInput: {
        id: $id
        accountId: $accountId
        firstName: $firstName
        lastName: $lastName
      }
    ) {
      firstName
      lastName
    }
  }
`;
// view doesn't tolerate undefined, even when we're loading
const defaultFormState = {
  country: "",
  email: "",
  firstName: "",
  lastName: "",
  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 = () => {
    setSuccess(false);
    if (formState.firstName && formState.lastName) {
      upsertUser({
        id: userIdent === null || userIdent === void 0 ? void 0 : userIdent.id,
        accountId: userIdent === null || userIdent === void 0 ? void 0 : userIdent.accountId,
        firstName: formState.firstName,
        lastName: formState.lastName,
      });
      setFormState((s) => ({ ...s, errors: {}, error: "" }));
      return;
    }
    const errors = {};
    if (!formState.firstName) {
      errors["firstName"] = { message: props.fieldEmptyText };
    }
    if (!formState.lastName) {
      errors["lastName"] = { message: props.fieldEmptyText };
    }
    if (!isEmpty(errors)) {
      setFormState((e) => ({
        ...e,
        error: props.formErrorText,
      }));
    }
    setFormState((e) => ({ ...e, errors }));
  };
  return {
    states: {
      success,
      loading: (userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.loading) || upsertUserResponse.loading,
      submitDisabled: false,
      showCountry: !props.hideCountry,
      formState,
      user: userData,
      text: {
        firstnametext: props.firstnametext,
        lastnametext: props.lastnametext,
        countrytext: props.countrytext,
        emailtext: props.emailtext,
        editProfileHeader: props.editProfileHeader,
        editProfileSubHeader: props.editProfileSubHeader,
        submitChangeButtonText: props.submitChangeButtonText,
      },
    },
    callbacks: {
      onSubmit,
      onChange: (e) => {
        const { name, value } = e.target;
        setFormState((data) => ({ ...data, [name]: value }));
      },
    },
  };
}
