import { Row } from "reactstrap";
import ValidationField from "../../../Components/ValidationField/ValidationField";
import { useFormikContext } from "formik";
import ChoiceFields from "./Field/ChoiceFields";
import { FaCirclePlus } from "react-icons/fa6";
import { Choice } from "../../../types/Item";
import { useTranslation } from "react-i18next";
import DynamicTags from "./Tags/DynamicTags";
import { useObjectToEdit } from "../../../zustand/ObjectToEditState";
import { useEffect } from "react";
import Choices from "./Field/Choices";

const Form = () => {
  const [t] = useTranslation();
  const formik = useFormikContext<any>();
  const { setSuccess, Success, setSavedQuestionData } = useObjectToEdit();

  useEffect(() => {
    if (Success) {
      formik.setErrors({});
      formik.resetForm({ values: {} });
      setSuccess(false);
    }
  }, [Success]);

  useEffect(() => {
    setSavedQuestionData(formik.values);
  }, [formik?.values]);

  const handleAddChoice = () => {
    formik.setFieldValue("answers", [
      ...((formik?.values as any)?.answers as Choice[]),
      {
        content: null,
        answer_image: null,
        isCorrect: 0,
      },
    ]);
  };

  return (
    <Row className="w-100">
      <div className="exercise_form">
        <ValidationField
          className="textarea_exercise"
          name="content"
          label="details"
          type="TextArea"
        />
        <ValidationField
          className="file_exercise"
          name="image"
          label="attachment"
          type="File"
        />
        <ValidationField
          name="canAnswersBeShuffled"
          label="canAnswersBeShuffled"
          type="Checkbox"
        />
      </div>
      <div>
        <ValidationField
          className="hint"
          name="hint"
          label="hint"
          type="text"
          style={{ width: 200 }}
        />
      </div>
      <Choices />
      {formik?.values?.answers?.length < 5 && (
        <p className="add_new_button">
          <FaCirclePlus onClick={handleAddChoice} size={23} />{" "}
          {t("header.add_new_choice")}
        </p>
      )}
      <DynamicTags />
    </Row>
  );
};

export default Form;
