import React, { useEffect }  from "react";
import { Modal, Spin } from "antd";
import FormikForm from "../../Layout/Dashboard/FormikFormModel";
import { getInitialValues, getValidationSchema ,getInitialValuesBase, getValidationSchemaBase, processTags} from "./Model/formUtil";
import {  useAddQuestion, useDeleteQuestion, 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";
import Header from "../../Components/exercise/Header";
import Form from './Model/Edit'
import BaseForm from './Model/Malty/Edit'
import { Question } from "../../types/Item";
import { toast } from "react-toastify";

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

  const {question_id,subject_id} = useParams<ParamsEnum>()
  const {isBseQuestion,set_isBseQuestion,set_Tags_search,DeletedQuestions} = useObjectToEdit()

  const { mutate, isSuccess, isLoading } = useUpdateQuestion();
  const { mutate:DeleteQuestion} = useDeleteQuestion();

  const {data,isLoading:dataLoading}= useGetAllQuestion({show:question_id})

  const {data:Questions,isLoading:QuestionsDataLoading}= useGetAllQuestion({questionParentId:question_id})
  
  const object_to_edit = {...data?.data,Questions:Questions?.data } ;
  

  useEffect(() => {
    if(object_to_edit?.isBase === 1 && isBseQuestion !== true){
     set_isBseQuestion(true)

    }
  }, [object_to_edit?.isBase])


  const handleSubmit = (values: any) => {
      const DataToSend = structuredClone(values);
      set_Tags_search(null)
    console.log(DataToSend);

          if(isBseQuestion){
        
        const UpdateBseQuestion = {
          "id":DataToSend?.id,
          "content" : DataToSend?.content,
          "image": DataToSend?.image ?? "",
        }
        if( typeof UpdateBseQuestion?.image === "string"){
          delete UpdateBseQuestion["image"]
        }
          console.log(DeletedQuestions,"DeletedQuestions");
          
          mutate(UpdateBseQuestion)


          DeletedQuestions?.map((item:any)=>{
            DeleteQuestion({id:item?.id})
            
          })


          const Questions = DataToSend?.Questions;
        console.log(Questions,"Questions");
        
        Questions?.map((item:Question)=>{
            console.log(item);
            
          const itemToSend = structuredClone(item);
          const keysToRemove = ['image', 'answer_image'];
          const updatedObject = removeStringKeys(itemToSend, keysToRemove);
          console.log(updatedObject,"updatedObject"); 

            const tags = processTags(updatedObject)
            const oldQuestionOptions = [] as any;
            const newQuestionOptions = [] as any;
            
            updatedObject?.QuestionOptions?.forEach((item:any) => {
              if (item?.id) {
                oldQuestionOptions.push(item);
              } else {
                newQuestionOptions.push(item);
              }
            });
            const QuestionOptions = {
              old: oldQuestionOptions,
              new: newQuestionOptions
            } ;
            console.log(QuestionOptions);
            
            mutate({
              ...updatedObject,
              QuestionOptions,
              tags
             
            })
       
         
          
      })
      }else{
        
        const keysToRemove = ['image', 'answer_image'];
        const updatedObject = removeStringKeys(DataToSend, keysToRemove);
          delete updatedObject["parent_id"];  
          const tags = processTags(updatedObject)
          console.log(updatedObject,"updatedObject");
          const oldQuestionOptions = [] as any;
          const newQuestionOptions = [] as any;

          updatedObject?.QuestionOptions?.forEach((item:any) => {
            if (item?.id) {
              oldQuestionOptions.push(item);
            } else {
              newQuestionOptions.push(item);
            }
          });
          
          const QuestionOptions = {
            old: oldQuestionOptions,
            new: newQuestionOptions
          };
          console.log(QuestionOptions,"QuestionOptions");
          
          
        mutate({ ...updatedObject,QuestionOptions,tags });
      }
  };
  
  const navigate = useNavigate()
  const handleCancel = () => {
    navigate(-1)
  };

  const [t] = useTranslation();

  useEffect(() => {
   if(isSuccess){
    toast.success(t("validation.the_possess_done_successful"))
    // navigate(-1)  
   }
  }, [isSuccess])
  

  
  if(dataLoading && !!(object_to_edit?.isBase) && QuestionsDataLoading){
    return <SpinContainer/>
  }
  if(object_to_edit?.isBase === 1){

  
    return (
      <div className="exercise_add">
  
          <FormikForm
            handleSubmit={handleSubmit}
            initialValues={getInitialValuesBase(object_to_edit)}
            validationSchema={getValidationSchemaBase}
          >
          
            <main className="w-100 exercise_add_main">
            {/* <Header/> */}
            <header className="exercise_add_header mb-4">
        <div>
          {t("practical.edit")} {t("models.exercise")}{" "}
        </div>
        <div>
       
     {t("header.exercise") }
        </div>
             </header>
              <BaseForm />
              <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>
    );
  }

  return (
    <div className="exercise_add">

        <FormikForm
          handleSubmit={handleSubmit}
          initialValues={getInitialValues(object_to_edit)}
          validationSchema={getValidationSchema}
        >
        
          <main className="w-100 exercise_add_main">
          {/* <Header/> */}
          <header className="exercise_add_header mb-4">
      <div>
        {t("practical.edit")} {t("models.exercise")}{" "}
      </div>
      <div>
     
   {t("header.exercise") }
      </div>
    </header>
            <Form />
            <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 EditPage;
