import { useCallback } from "react";
import { useFormikContext } from "formik";
import { getLatexOnCustomPased } from "../utils/keyDownUtils";

export function useHandlePasteKeyDown() {
  const formik = useFormikContext<any>();

  const handleCustomPasteKeyDown = useCallback(
    async (e: React.KeyboardEvent<HTMLInputElement>, fieldName: string) => {
      const latexCtlrShiftV = await getLatexOnCustomPased(e,!e.ctrlKey || !e.shiftKey || e.code !== "KeyV" );
      const latexCtlrCheftBackquote = await getLatexOnCustomPased(e,!e.ctrlKey || !e.shiftKey || e.code !== "Backquote" );
      if (!latexCtlrShiftV && !latexCtlrCheftBackquote) return;

      const input = e.target as HTMLInputElement;
      const toInsert = !!latexCtlrShiftV ? `$$ ${latexCtlrShiftV} $$` : `$$$ ${latexCtlrCheftBackquote} $$$`

      e.preventDefault?.();

      input.focus(); 
      document.execCommand('insertText', false, toInsert);

      input.dispatchEvent(new Event("input", { bubbles: true }));

    },
    []
  );

  return handleCustomPasteKeyDown;
}
