import React, { useContext } from "react";
import { EditorContext } from "./../../../ricos-context/index.js";
import { elementFromString } from "./../../../tiptap/index.js";
import { DOMParser } from "./../../../tiptap/pm/model.js";
import { isOfType } from "../../ts-utils.js";
import { convertNewLinesToParagraphs } from "../../utils/convert-new-lines-to-paragraphs.js";
import { scrollToElementIfNeeded } from "../../utils/scroll-to-element-if-needed.js";
import { useAiRequestService } from "../../utils/use-ai-request-service.js";
const useAiModalActions = ({
  state,
  dispatch,
  getGatewayBaseUrl,
  appDefId,
  inputRef,
  listRef,
  selection,
  initialPromptOptions
}) => {
  const { adapter } = useContext(EditorContext);
  const config = React.useMemo(
    () => ({ type: "ai", getGatewayBaseUrl, appDefId }),
    [getGatewayBaseUrl, appDefId]
  );
  const { fetchPrompt } = useAiRequestService(config);
  const requestPromptData = React.useCallback(
    async (prompt, content) => {
      const response = await fetchPrompt(prompt, content);
      if (response.type === "ERROR" || response.type === "VALIDATION_ERROR" || response.type === "RATE_LIMIT_ERROR") {
        throw new Error(response.error);
      }
      const suggestionsAsHTML = response.results;
      const schema = adapter.tiptapEditor.schema;
      const parser = DOMParser.fromSchema(schema);
      return suggestionsAsHTML.map((s) => {
        const cleanedHtml = stripUnsupportedInlineStyles(s);
        const parsedContent = parser.parse(
          elementFromString(convertNewLinesToParagraphs(cleanedHtml))
        );
        return {
          content: parsedContent.toJSON(),
          plainContent: parsedContent.textContent,
          htmlContent: s
        };
      });
    },
    []
  );
  const streamPromptDataToState = React.useCallback(
    (suggestions, requestId) => {
      dispatch({
        type: "FINISH_LOADING",
        payload: {
          suggestions,
          requestId
        }
      });
      inputRef.current?.focus();
    },
    [dispatch]
  );
  const setSelectedPromptIndex = React.useCallback(
    (selectedPromptIndex, scrollToView = false) => {
      dispatch({
        type: "SET_SELECTED_PROMPT_INDEX",
        payload: {
          selectedPromptIndex
        }
      });
      if (listRef.current?.childNodes[selectedPromptIndex] && scrollToView) {
        scrollToElementIfNeeded(listRef.current?.childNodes[selectedPromptIndex], listRef.current);
      }
    },
    [listRef.current]
  );
  const setFreePromptValue = React.useCallback((value) => {
    dispatch({
      type: "SET_FREE_PROMPT_VALUE",
      payload: {
        value
      }
    });
  }, []);
  const submitTextualPrompt = React.useCallback(async (prompt, content) => {
    const requestId = Date.now().toString();
    dispatch({
      type: "SUBMIT_TEXTUAL_PROMPT",
      payload: {
        requestId
      }
    });
    try {
      const suggestions = await requestPromptData({ prompt }, content);
      inputRef.current?.focus();
      streamPromptDataToState(suggestions, requestId);
    } catch {
      dispatch({
        type: "SET_ERROR",
        payload: {
          requestPrompt: prompt,
          requestContent: content
        }
      });
    }
  }, []);
  const submitPrompt = React.useCallback(async (prompt, content = "") => {
    const requestId = Date.now().toString();
    dispatch({
      type: "SUBMIT_PROMPT",
      payload: {
        prompt,
        requestId
      }
    });
    try {
      const payload = "promptId" in prompt ? { promptId: prompt.promptId, promptParams: prompt.promptParams } : "promptSlug" in prompt ? { promptSlug: prompt.promptSlug, promptParams: prompt.promptParams } : null;
      if (payload === null) {
        throw new Error("Invalid prompt");
      }
      const suggestions = await requestPromptData(payload, content);
      inputRef.current?.focus();
      streamPromptDataToState(suggestions, requestId);
    } catch {
      dispatch({
        type: "SET_ERROR",
        payload: {
          requestPrompt: prompt,
          requestContent: content
        }
      });
    }
  }, []);
  const cancelPrompt = React.useCallback(() => {
    if (state.type === "IN_PROGRESS") {
      inputRef.current?.focus();
    }
    dispatch({
      type: "CANCEL_PROMPT"
    });
  }, [state]);
  const triggerFreePrompt = React.useCallback(() => {
    if (isOfType(["RESULTS"], state)) {
      if (state.textualPrompt.length) {
        const results = state.entries.filter(
          (entry) => entry.type === "result"
        );
        const lastResult = results[results.length - 1];
        return submitTextualPrompt(
          state.textualPrompt,
          lastResult?.response.htmlContent ?? selection
        );
      }
    }
    if (isOfType(["INITIAL"], state)) {
      if (state.initialPrompt) {
        return submitPrompt(
          initialPromptOptions?.promptPayloadFormatter ? initialPromptOptions?.promptPayloadFormatter(state.initialPrompt, state.textualPrompt) : state.initialPrompt,
          selection
        );
      }
      if (state.textualPrompt.length) {
        return submitTextualPrompt(state.textualPrompt, selection);
      }
    }
  }, [state]);
  const retryPrompt = React.useCallback(() => {
    if (!isOfType(["ERROR"], state)) {
      return;
    }
    if (typeof state.requestPrompt === "string") {
      return submitTextualPrompt(state.requestPrompt, state.requestContent);
    }
    return submitPrompt(state.requestPrompt, state.requestContent);
  }, [state]);
  const goBack = React.useCallback(() => {
    dispatch({
      type: "GO_BACK"
    });
  }, [state]);
  return {
    setSelectedPromptIndex,
    setFreePromptValue,
    submitPrompt,
    triggerFreePrompt,
    cancelPrompt,
    retryPrompt,
    goBack
  };
};
const stripUnsupportedInlineStyles = (html) => {
  const tempDiv = document.createElement("div");
  tempDiv.innerHTML = html;
  const elementsWithStyle = tempDiv.querySelectorAll("[style]");
  elementsWithStyle.forEach((element) => {
    element.removeAttribute("style");
  });
  return tempDiv.innerHTML;
};
export {
  useAiModalActions
};
//# sourceMappingURL=use-ai-modal-actions.js.map
