import { useState, useEffect } from "react";
import ReactLoading from "react-loading";
import Formsy from "formsy-react";
import { API } from "aws-amplify";
import OCVForm from "./OCVForm";

const axios = require("axios");

export const FormWrapper = ({
  viewData,
  classes,
  formID,
  link,
  headerText,
  submissionText,
  anchorID,
}) => {
  const [activePage, setActivePage] = useState(0);
  const [state, setState] = useState({});
  const [formData, setFormData] = useState(null);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [isSubmitted, setIsSubmitted] = useState(false);

  const disableButton = () => {
    //setCanSubmit(false);
    setState({ ...state, canSubmit: false });
  };
  const enableButton = () => {
    //setCanSubmit(true);
    setState({ ...state, canSubmit: true });
  };

  const submit = (model) => {
    setIsSubmitting(true);
    API.post("ocvapps", "/form/submission", {
      body: {
        appID: formData.appID,
        data: {
          formID: formID,
          formData: model,
        },
      },
      headers: {
        "x-api-key": "AJgsD4mQAY95dQiaJecac3WBvEFlqnvn3vAxI93f",
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        if (response?.response?.statusCode === 200) {
          setIsSubmitting(false);
          setIsSubmitted(true);
        } else {
          setIsSubmitting(false);
          setIsSubmitted(false);
          alert(
            "There has been a problem with your form submission. Contact the Web Administrator for help."
          );
        }
      })
      .catch((error) => {
        setIsSubmitting(false);
        setIsSubmitted(false);
        alert(error);
      });
  };

  // retrieve formData
  useEffect(() => {
    async function getFormData() {
      try {
        const response = await axios.get(link);
        setFormData(response?.data?.data);
      } catch (error) {
        console.error(error);
      }
    }

    getFormData();
  }, [link]);

  if (formData === null) {
    return (
      <div className="OCVFormDiv">
        <ReactLoading
          className="loading-centered"
          type={"spinningBubbles"}
          color={"#105c9c"}
          height={"10%"}
          width={"10%"}
        />
      </div>
    );
  } else {
    return (
      <Formsy
        onValidSubmit={submit}
        onValid={enableButton}
        onInvalid={disableButton}
      >
        <OCVForm
          isSubmitted={isSubmitted}
          isSubmitting={isSubmitting}
          disableButton={disableButton}
          enableButton={enableButton}
          formData={formData}
          formID={formID}
          headerText={headerText}
          submissionText={submissionText}
          anchorID={anchorID}
          classes={classes}
          viewData={viewData}
          state={state}
          setState={setState}
          activePage={activePage}
          setActivePage={setActivePage}
        />
      </Formsy>
    );
  }
};