import Divider from "../../layout/Divider";
import Stack from "../../layout/Stack";
import React from "react";
import MarkdownEditorPreviewComponent from "../../mdx/markdown/MarkdownEditorPreviewComponent";
import { ChatCompletionMessageParam } from "openai/resources/index";

type Props = {
    streamRes: string;
    setStreamRes: React.Dispatch<React.SetStateAction<string>>;
    history: ChatCompletionMessageParam[];
    loading?: boolean;
};

export default function AIPromptPreview({
    setStreamRes,
    streamRes,
    history,
    loading,
}: Props) {
    const responseContentRef = React.useRef<HTMLDivElement>(null);
    const isContentInterrupted = React.useRef(false);

    React.useEffect(() => {
        if (isContentInterrupted.current) return;

        if (responseContentRef.current) {
            responseContentRef.current.scrollTop =
                responseContentRef.current.scrollHeight;
        }
    }, [streamRes]);

    if (loading || !streamRes?.match(/./)) return null;

    return (
        <Stack className="w-full">
            <MarkdownEditorPreviewComponent
                value={streamRes}
                maxHeight="40vh"
                wrapperProps={{
                    className: "border-none p-0 ai-response-content",
                    componentRef: responseContentRef as any,
                    onMouseEnter: () => {
                        isContentInterrupted.current = true;
                    },
                    onMouseLeave: () => {
                        isContentInterrupted.current = false;
                    },
                }}
            />
            <Divider />
        </Stack>
    );
}
