import TextArea from "antd/es/input/TextArea";
import React, { Suspense, useEffect, useState } from "react";
import { parseTextAndLatex } from "../../utils/parseTextAndLatex";
import LatexPreview from "../CustomFields/MathComponent";
import { Checkbox } from "antd";
import { CheckboxProps } from "antd/lib";
import { useTranslation } from "react-i18next";
import { FaPlus } from "react-icons/fa";
import { useObjectToEdit } from "../../zustand/ObjectToEditState";
import SpinContainer from "../Layout/SpinContainer";
import { areFieldPropsEqual } from "./areFieldPropsEqual";
import { useHandlePasteKeyDown } from "../../Hooks/useHandlePasteKeyDown";
import { getLatexOnCtrlShiftQkeyDown, getLatexOnCtrlShiftThKeyDown } from "../../utils/keyDownUtils";
import { InlineMath } from "react-katex";
import 'katex/dist/katex.min.css';


const AddLazyLatexModal = React.lazy(() => import("./AddLaTexModal"));
const EditLazyLatexModal = React.lazy(() => import("./EditLaTexModal"));

const AddLazyImageModal = React.lazy(() => import("./AddImageModal"));


const LaTeXInputMemo: React.FC<any> = React.memo(
  ({ field, form, label, ...props }) => {
    const { name, value } = field;

    const { setFieldValue, touched, errors, getFieldProps, values } = form;

    const { ShowLatexOption, Success } = useObjectToEdit();
    const [showPreview, setShowPreview] = useState(false);
    const Preview = parseTextAndLatex(value ?? "");

    const onPreviewChange: CheckboxProps["onChange"] = (e) => {
      setShowPreview(e.target.checked);
    };

    const [t] = useTranslation();

    const [isLatexModalOpen, setIsLatexModalOpen] = useState(false);
    const [isLatexEditModalOpen, setIsLatexEditModalOpen] = useState(false);
    const [Latex, setLatex] = useState<string>("");
    
    const [isImageModalOpen, setIsImageModalOpen] = useState(false);

    const showLatexModal = () => {
      setIsLatexModalOpen(true);
    };

        const showImageModal = () => {
      setIsImageModalOpen(true);
    };


    const handleEditModal = (item: any) => {
      // console.log(item);
      // setLatex(item);
      // setIsEditModalOpen(true);
    };

    const [curCentValue, setCurrentValue] = useState(value);
    const handleChangeInput = (
      e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>,
    ) => {
      setCurrentValue(e.target.value);
    };
    const onBlur = () => {
      if (curCentValue !== value) {
        setFieldValue(name, curCentValue);
      }
    };

    useEffect(() => {
      if (Success) {
        setCurrentValue(null);
      }
    }, [Success]);

    useEffect(() => {
      if (value) {
        setCurrentValue(value);
      }
    }, [value]);

    const isError = !!touched?.[name] && !!errors?.[name];
    const errorMessage = isError ? ((errors?.[name] as string) ?? "") : "";


    let metaName = name.substring(0, name.lastIndexOf("."));
    if (metaName.includes(".") || metaName.includes("[")) {
      metaName += ".meta";
    } else {
      metaName += "meta";
    }
    const meta = getFieldProps(metaName).value;
    const direction = meta?.direction === "ltr" ? "ltr" : "rtl";

    const [Dir, setDir] = useState<"ltr" | "rtl">(direction);

    const handleChangeDirection = () => {
      if (Dir === "ltr") {
        setDir("rtl");
        setFieldValue(metaName, { ...(meta ?? {}), direction: "rtl" });
      } else {
        setDir("ltr");
        setFieldValue(metaName, { ...(meta ?? {}), direction: "ltr" });
      }
    };
    
      const handlePaste = useHandlePasteKeyDown();
    const handleOnKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) =>{
      if(!ShowLatexOption) return ;
        handlePaste(e,name)
        const latexOnCtrlSHiftQClick = getLatexOnCtrlShiftQkeyDown(e)
        // const latexOnCtrlSHiftThClick = getLatexOnCtrlShiftThKeyDown(e)
        latexOnCtrlSHiftQClick && document.execCommand('insertText', false,latexOnCtrlSHiftQClick);
        // latexOnCtrlSHiftThClick && document.execCommand('insertText', false,latexOnCtrlSHiftThClick);
    }
    return (
      <div className="LaTeXInput">
        <label htmlFor={name} className="text">
          <div>{t(label || name)}</div>{" "}
          <div className="error_message">{t(errorMessage)}</div>
        </label>

        <div className="LaTeXInputArea">
          <TextArea
            size="large"
            showCount
            maxLength={5000}
            autoSize={{ minRows: 6, maxRows: 10 }}
            style={{ height: "400px" }}
            onChange={handleChangeInput}
            value={curCentValue}
            onBlur={onBlur}
            dir={Dir}
            onKeyDown={handleOnKeyDown}
            {...props}
          />
          <div className="LaTeXInputOptions">
            <Checkbox
              onChange={handleChangeDirection}
              checked={direction === "ltr"}
            >
              {t("header.change_direction")}
            </Checkbox>

            {ShowLatexOption && (
              <>
                <Checkbox onChange={onPreviewChange}>
                  {t("header.show_preview")}
                </Checkbox>
                <button type="button" className="addMML" onClick={showLatexModal}>
                  <FaPlus /> {t("MML")}
                </button>
                <button type="button" className="addMML mx-2" onClick={showImageModal}>
                  <FaPlus /> {t("practical.image")}
                </button>
              </>
            )}
          </div>

{showPreview && (
  <div className="showPreviewInput">
        {Preview.map((item, idx) => {
      if (item.isLatex) {
        return <span dir="ltr" key={idx}><InlineMath  >{item.text}</InlineMath></span>;
      }else if(item.isImage){
        return <img key={idx} alt="img" width={200} src={item.text}/>
      }
       else {
        const lines = item.text.split('\n');
        return (
          <React.Fragment key={idx}>
            {lines.map((line, i) => (
              <React.Fragment key={`${idx}-${i}`}>
                {line}
                {i < lines.length - 1 && <br />} 
              </React.Fragment>
            ))}
          </React.Fragment>
        );
      }
    })}
  </div>
)}

        </div>

        <Suspense fallback={<SpinContainer />}>
          <AddLazyLatexModal
            name={name}
            Latex={Latex}
            isModalOpen={isLatexModalOpen}
            setIsModalOpen={setIsLatexModalOpen}
            setLatex={setLatex}
            setCurrentValue={setCurrentValue}
          />
          <EditLazyLatexModal
            name={name}
            Latex={Latex}
            isModalOpen={isLatexEditModalOpen}
            setIsModalOpen={setIsLatexEditModalOpen}
            setLatex={setLatex}
          />
          <AddLazyImageModal
            name={name}
            isModalOpen={isImageModalOpen}
            setIsModalOpen={setIsImageModalOpen}
            setCurrentValue={setCurrentValue}
          />
        </Suspense>
      </div>
    );
  },
  (prevProps, nextProps) => {
    return areFieldPropsEqual(prevProps, nextProps);
  },
);

export default LaTeXInputMemo;
