import React from "react";
import { Choice } from "../../../../../types/Item";
import ValidationField from "../../../../../Components/ValidationField/ValidationField";
import { useFormikContext } from "formik";
import { useTranslation } from "react-i18next";
import { getCharFromNumber } from "../../../../../utils/getCharFromNumber";
import CheckboxField from "./CheckboxField";
import TextField from "./TextField";
import File from "./File";
import { FaTrash } from "react-icons/fa";
import { toast } from "react-toastify";

const ChoiceFields = ({
  index,
  parent_index,
  data,
}: {
  index: number;
  parent_index: number;
  data: Choice;
}) => {
  const formik = useFormikContext<any>();

  const [t] = useTranslation();

  const handleDeleteChoice = () => {
    const arrayLength =
      formik.values.Questions?.[parent_index].QuestionOptions?.length;

    console.log(arrayLength);

    if (arrayLength === 1) {
      toast.error(
        t("validation.Sorry, the question must have at least one option"),
      );
      return;
    }

    const updatedQuestionOptions = formik.values.Questions?.[
      parent_index
    ].QuestionOptions.filter((_: any, i: any) => i !== index);
    formik.setFieldValue(
      `Questions[${parent_index}].QuestionOptions`,
      updatedQuestionOptions,
    );
  };
  return (
    <div className="ChoiceFields">
      <TextField
        className="textarea_exercise"
        placeholder={"choice"}
        label2={t(`input.choice`) + ` ` + `(${getCharFromNumber(index)})`}
        name={index}
        parent_index={parent_index}
        type="TextArea"
      />
      <File
        className="file_exercise"
        label={"attachment"}
        name={index}
        type="File"
        parent_index={parent_index}
      />

      <CheckboxField
        className=""
        label="The_correct_answer"
        name={index}
        type="Checkbox"
        parent_index={parent_index}
      />
      <p className="delete_question_options">
        <FaTrash onClick={handleDeleteChoice} size={17} />
      </p>
    </div>
  );
};

export default ChoiceFields;
