import { useQuery, useMutation, useUserIdentity, } from "@saasquatch/component-boilerplate";
import { gql } from "graphql-request";
import { useEffect, useState } from "@saasquatch/universal-hooks";
import { intl } from "../../global/global";
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 = {
  currentRegion: "",
  firstName: "",
  lastName: "",
  errors: {},
  error: "",
};
export function useEditProfile(props) {
  const userIdent = useUserIdentity();
  const [showEdit, setShowEdit] = useState(false);
  const [error, setError] = useState("");
  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) || !showEdit)
      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,
        });
      });
      setShowEdit(false);
    }
  }, [upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.loading]);
  useEffect(() => {
    setUserData((data) => { var _a; return ({ ...data, ...(_a = userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.data) === null || _a === void 0 ? void 0 : _a.viewer }); });
  }, [userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.data]);
  useEffect(() => {
    var _a;
    if ((_a = upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.errors) === null || _a === void 0 ? void 0 : _a.message) {
      setFormState((state) => ({ ...state, error: props.networkErrorMessage }));
    }
  }, [upsertUserResponse === null || upsertUserResponse === void 0 ? void 0 : upsertUserResponse.errors]);
  return {
    states: {
      loading: (userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.loading) || upsertUserResponse.loading,
      submitDisabled: false,
      formState,
      user: userData,
      showEdit,
      text: {
        editprofileheader: props.editprofileheader,
        editprofiletext: props.editprofiletext,
        firstnametext: props.firstnametext,
        lastnametext: props.lastnametext,
        canceltext: props.canceltext,
        updatetext: props.updatetext,
        currentregiontext: props.currentregiontext,
        showregion: props.showregion,
        fieldEmptyText: props.fieldEmptyText,
      },
    },
    callbacks: {
      onSubmit: () => {
        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: {} }));
          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 }));
      },
      resetForm: () => {
        var _a, _b, _c, _d, _e, _f;
        const currentRegion = ((_b = (_a = userDataResponse === null || userDataResponse === void 0 ? void 0 : userDataResponse.data) === null || _a === void 0 ? void 0 : _a.viewer) === null || _b === void 0 ? void 0 : _b.countryCode) ? intl.formatDisplayName(userDataResponse.data.viewer.countryCode, {
          type: "region",
        })
          : "";
        setUserData({
          ...(_c = userDataResponse.data) === null || _c === void 0 ? void 0 : _c.viewer,
          ...(_d = upsertUserResponse.data) === null || _d === void 0 ? void 0 : _d.upsertUser,
        });
        setFormState({
          ...defaultFormState,
          ...(_e = userDataResponse.data) === null || _e === void 0 ? void 0 : _e.viewer,
          ...(_f = upsertUserResponse.data) === null || _f === void 0 ? void 0 : _f.upsertUser,
          currentRegion,
        });
      },
      onChange: (e) => {
        const { name, value } = e.target;
        setFormState((data) => ({ ...data, [name]: value }));
      },
      setShowEdit,
    },
  };
}
