import { Button, Modal, Spin, Switch } from "antd";
import TextArea from "antd/es/input/TextArea";
import { Field, getIn, useFormikContext } from "formik";
import React, { useEffect, useState } from "react";
import { convertMathMLToLaTeX } from "../../utils/convertMathMLToLaTeX";
import { useTranslation } from "react-i18next";
import ImageBoxFieldMemo from "../CustomFields/ImageBoxField/ImageBoxFieldMemo";
import { useGetUrl } from "../../api/image";
import Loading from "../Utils/Loading/Loading";
import { Spinner } from "reactstrap";

const AddImageModal = ({
  name,
  setIsModalOpen,
  isModalOpen,
  setCurrentValue,
}: {
  name: string;
  setIsModalOpen: (value: boolean) => void;
  isModalOpen: boolean;
  setCurrentValue: (value: string) => void;
}) => {
  const { values, setFieldValue, getFieldProps } = useFormikContext<any>();
  const [imageUrl,setImageUrl] = useState<any>("")

  const {isSuccess,data,isLoading,mutateAsync:sendFile}= useGetUrl()




  const currentValue = getFieldProps(name).value;

const File = getIn(values, `${name}_image_with_content`);            

  const handleOk = async () => {

    if(!File)return;
      await sendFile({image:File}).then((response:any) => {
        const oldValue = currentValue ?? "";
        const imageUrl = response?.data?.url

        const final =  oldValue + `<<img>> ${imageUrl} <<img>>`
        
          setFieldValue(name, final);
          setCurrentValue(final);
          setFieldValue(`${name}_image_with_content`, null);
    
          setIsModalOpen(false);
      })

  };

  const handleCancel = () => {
    setIsModalOpen(false);
    // setLatex("");
  };

  const handleChangeInputLatex = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
  ) => {
    const newValue = e.target.value;
    // setLatex(newValue);

  };



  const [t] = useTranslation();
  return (
    <Modal
      footer={false}
      open={isModalOpen}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <div className="imageModal">
              <label className="mb-3"> {t("header.past_your_image")} </label>
        <div className="bg-upload">
            <Field key={File} component={ImageBoxFieldMemo} name={`${name}_image_with_content`}/>
        </div>

        <div className="buttons">
          <div className="back_button pointer" onClick={handleCancel}>
            {t("practical.cancel")}
          </div>
          <Button className="add_button"  onClick={handleOk} disabled={isLoading || !File} loading={isLoading} >
            {t(`practical.${"add"}`)}
          </Button>
        </div>
      </div>
    </Modal>
  );
};

export default AddImageModal;
