import React, { useEffect }  from "react";
import { Modal, Spin } from "antd";
import FormikForm from "../../../Layout/Dashboard/FormikFormModel";
import ModelBody from "./Add";
import { getInitialValues, getValidationSchema } from "./formUtil";
import {  useGetAllQuestion, useUpdateQuestion } from "../../../api/Question";
import { useQueryClient } from "react-query";
import { useTranslation } from "react-i18next";
import { useNavigate, useParams } from "react-router-dom";
import { ParamsEnum } from "../../../enums/params";
import { useObjectToEdit } from "../../../zustand/ObjectToEditState";
import { removeStringKeys } from "../../../utils/removeStringKeys";
import SpinContainer from "../../../Components/Layout/SpinContainer";

const ModalForm: React.FC = () => {

  const {question_id,subject_id} = useParams<ParamsEnum>()

  const { mutate, isSuccess, isLoading } = useUpdateQuestion();
  const {data,isLoading:dataLoading}= useGetAllQuestion({show:question_id})

  const object_to_edit = data?.data ;
    
  const handleSubmit = (values: any) => {
    console.log(values, "values");
      const DataToSend = structuredClone(values);
  
    const keysToRemove = ['image', 'answer_image'];
    const updatedObject = removeStringKeys(DataToSend, keysToRemove);
  
    mutate({ ...updatedObject });
  };
  
  const navigate = useNavigate()
  const handleCancel = () => {
    navigate(-1)
  };

  const [t] = useTranslation();

  useEffect(() => {
   if(isSuccess){
    navigate(-1)  
   }
  }, [isSuccess])
  

  if(dataLoading){
    return <SpinContainer/>
  }

  return (
    <div className="exercise_add">

        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
        
          <main className="w-100 exercise_add_main">
          <header className="exercise_add_header mb-4">
            {" "}
            {t("practical.edit")} {t("models.exercise")}{" "}
          </header>
            <ModelBody />
            <div className="exercise_add_buttons">
              <div onClick={handleCancel}>{t("practical.back")}</div>
              <button disabled={isLoading} className="relative" type="submit">
                {t("practical.edit")}

                {isLoading && (
                  <span className="Spinier_Div">
                    <Spin />
                  </span>
                )}
              </button>
            </div>
          </main>
        </FormikForm>

    </div>
  );
};

export default ModalForm;
