import { useState } from "@saasquatch/universal-hooks";
import jsonpointer from "jsonpointer";
import { jwtDecode } from "jwt-decode";
import { useRegistrationForm } from "../sqm-portal-registration-form/useRegistrationFormState";
export function usePortalGoogleRegistrationForm(props) {
  const [registrationFormState, setRegistrationFormState] = useRegistrationForm();
  const [showRegistrationForm, setShowRegistrationForm] = useState({
    mode: "base",
  });
  const handleEmailSubmit = async (event) => {
    const formControls = event.target.getFormControls();
    let formData = {};
    let validationErrors = {};
    formControls.forEach((control) => {
      if (!control.name)
        return;
      const key = control.name;
      const value = control.value;
      jsonpointer.set(formData, key, value);
      if (control.required && !value) {
        jsonpointer.set(validationErrors, key, props.requiredFieldErrorMessage);
      }
      if (typeof control.validationError === "function") {
        const validate = control.validationError;
        const validationError = validate({
          control,
          key,
          value,
        });
        if (validationError)
          jsonpointer.set(validationErrors, key, validationError);
      }
    });
    if (Object.keys(validationErrors).length) {
      // early return for validation errors
      setRegistrationFormState({
        ...registrationFormState,
        loading: false,
        error: "",
        validationErrors,
      });
      return;
    }
    setRegistrationFormState({
      ...registrationFormState,
      validationErrors: {},
      initialData: {
        ...registrationFormState === null || registrationFormState === void 0 ? void 0 : registrationFormState.initialData,
        ...formData,
      },
    });
    setShowRegistrationForm({ mode: "manual" });
  };
  const handleGoogleInit = (event) => {
    var _a;
    if (!((_a = event.detail) === null || _a === void 0 ? void 0 : _a.credential))
      return;
    try {
      const res = jwtDecode(event.detail.credential);
      setRegistrationFormState({
        ...registrationFormState,
        _googleOAuthIdToken: event.detail.credential,
        initialData: {
          email: res.email,
          firstName: res.given_name,
          lastName: res.family_name,
        },
      });
      setShowRegistrationForm({ mode: "google" });
    }
    catch (e) {
      console.error("Failed to decode Google Sign In credential JWT:", e);
    }
  };
  return {
    registrationFormState,
    showRegistrationForm,
    validationErrors: registrationFormState.validationErrors,
    handleGoogleInit,
    handleEmailSubmit,
  };
}
