import React, { useEffect, useState } from "react";
import { useForm, useWatch } from "react-hook-form";
import { Button } from "@arcteryx/components-button";
import { useTranslation } from "react-i18next";
import FsSections from "./components/FsSections";
import styled from "styled-components";
import ReCAPTCHA from "react-google-recaptcha";

export const FormWrapper = styled.form`
  max-width: 650px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  a {
    color: var(--colour-black);
  }
  .grecaptcha-badge {
    visibility: hidden !important;
  }
`;

/**
 * Formstack Component
 * @param {object} formData - data from Formstack API
 * @param {string} submitButtonText - change the name of the submit button, defaults to "Submit"
 * @param {string} country - passed from the consuming app
 * @param {boolean} isSubmitting - state of the form when submitting
 * @param {function} onSubmit - provides access to the useForm handleSubmit
 * @param {boolean} hideFormBanner - provides option to hide formstack banner
 * @returns {react} form rendered with fields from the Formstack API
 */
const Formstack = ({
  formData,
  submitButtonText,
  country = "CA",
  language = "en",
  market = "outdoor",
  isSubmitting = false,
  formName,
  onEmailSubscriptionCheckedAnalytics,
  countryList,
  formatFormData,
  recaptchaSiteKey,
  recaptchaRef,
  hideFormBanner = false,
  onSubmit = () => {
    // default
  },
  onErrors = () => {
    //default
  },
}) => {
  const { t } = useTranslation("components-formstack");
  const [provinceId, setProvinceId] = useState(null);
  const [countryId, setCountryId] = useState(null);
  const {
    register,
    formState: { errors },
    handleSubmit,
    watch,
    setFocus,
    setValue,
    getValues,
    control,
  } = useForm({ mode: "onBlur" });

  useEffect(() => {
    formData.fields.forEach(({ id, name }) => {
      if (name.includes("country")) {
        setCountryId(id);
      }
      if (name.includes("province") || name.includes("state")) {
        setProvinceId(id);
      }
    });
  }, [formData]);

  const currentCountry = useWatch({ control, name: countryId });
  const FsSectionsProps = {
    fields: formData?.fields,
    register,
    watch,
    setValue,
    setFocus,
    getValues,
    errors,
    country,
    language,
    provinceId,
    countryId,
    currentCountry,
    formName,
    countryList,
    market,
    hideFormBanner,
  };

  const emailSubscriptionChecked = (formValues) => {
    if ("marketing_emails" in formValues && formValues.marketing_emails === true) {
      onEmailSubscriptionCheckedAnalytics();
    }
  };

  const formOnSubmit = (data) => {
    emailSubscriptionChecked(FsSectionsProps.getValues());
    onSubmit(formatFormData(data, formData.fields));
  };

  const onError = () => {
    const errorFormKeys = Object.keys(errors);
    const errorFormFields = errorFormKeys.map((key) => ({
      formFieldName: key || errors[key].ref.title || "Picture Upload", // the value of the current key.
      formFieldError: errors[key].message, // the value of the current key.
    }));
    const errorFormData = {
      formName,
      formField: errorFormFields,
    };

    //Call function in parent to pass data back up
    onErrors(errorFormData);
  };

  return (
    formData && (
      <FormWrapper
        id={`FsForm${formData?.id}`}
        data-testid={`FsForm${formData?.id}`}
        onSubmit={handleSubmit(formOnSubmit, onError)}
      >
        <FsSections {...FsSectionsProps} />
        {recaptchaSiteKey && recaptchaRef ? (
          <ReCAPTCHA ref={recaptchaRef} size="invisible" sitekey={recaptchaSiteKey} />
        ) : null}
        <Button context="Submit" type="submit" isWaiting={isSubmitting}>
          {submitButtonText || t("Submit")}
        </Button>
      </FormWrapper>
    )
  );
};

export default Formstack;
