import { jsx } from "react/jsx-runtime";
import { useLingui } from "@lingui/react";
import { isEqual } from "lodash/fp";
import react from "react";
import { AutopilotChatEvent, AutopilotChatInternalEvent } from "../service/index.js";
import { useChatService } from "./chat-service.provider.js";
import { useChatState } from "./chat-state-provider.js";
import { useError } from "./error-provider.js";
const AutopilotAttachmentsContext = /*#__PURE__*/ react.createContext({
    attachments: [],
    attachmentsLoading: [],
    addAttachments: ()=>{},
    removeAttachment: ()=>{},
    clearAttachments: ()=>{}
});
function AutopilotAttachmentsProvider({ children }) {
    const { _ } = useLingui();
    const chatService = useChatService();
    const prompt = chatService?.getPrompt?.();
    const { allowedAttachments } = useChatState();
    const { setError } = useError();
    const [attachments, setAttachments] = react.useState(prompt?.attachments ?? []);
    const [attachmentsLoading, setAttachmentsLoading] = react.useState([]);
    const attachmentsRef = react.useRef(attachments);
    react.useEffect(()=>{
        const currentAttachmentsWithoutContent = attachmentsRef.current.map(({ content: _content, ...rest })=>rest);
        const newAttachmentsWithoutContent = attachments.map(({ content: _content, ...rest })=>rest);
        if (!isEqual(currentAttachmentsWithoutContent, newAttachmentsWithoutContent)) {
            const added = attachments.filter((newAtt)=>!attachmentsRef.current.some((currentAtt)=>currentAtt.name === newAtt.name && currentAtt.size === newAtt.size));
            const removed = attachmentsRef.current.filter((currentAtt)=>!attachments.some((newAtt)=>newAtt.name === currentAtt.name && newAtt.size === currentAtt.size));
            attachmentsRef.current = attachments;
            const eventBus = chatService?._eventBus;
            if (eventBus && (added.length > 0 || removed.length > 0)) {
                eventBus.publish(AutopilotChatEvent.Attachments, attachments);
                eventBus.publish(AutopilotChatEvent.SetAttachments, {
                    added,
                    removed
                });
            }
        }
    }, [
        attachments,
        chatService
    ]);
    const addAttachments = react.useCallback((newFiles)=>{
        const filesToAdd = [
            ...attachmentsRef.current,
            ...newFiles.filter((file)=>!attachmentsRef.current.some((existing)=>existing.name === file.name && existing.size === file.size))
        ];
        const totalCount = filesToAdd.length;
        if (allowedAttachments.maxCount && totalCount > allowedAttachments.maxCount) return void setError(_({
            id: 'autopilot-chat.error.too-many-files',
            values: {
                0: allowedAttachments.maxCount
            }
        }));
        if (!allowedAttachments.multiple && totalCount > 1) return void setError(_({
            id: 'autopilot-chat.error.multiple-files'
        }));
        setAttachments(filesToAdd);
    }, [
        allowedAttachments.maxCount,
        allowedAttachments.multiple,
        setError,
        _
    ]);
    const removeAttachment = react.useCallback((name, index)=>{
        setAttachments((current)=>current.filter((file, i)=>i !== index || file.name !== name));
    }, []);
    const clearAttachments = react.useCallback(()=>{
        setAttachments([]);
    }, []);
    react.useEffect(()=>{
        if (!chatService) return;
        const unsubscribeSetAttachmentsLoading = chatService.__internalService__.on(AutopilotChatInternalEvent.SetAttachmentsLoading, (state)=>{
            setAttachmentsLoading(state);
        });
        const unsubscribe = chatService.on(AutopilotChatEvent.SetPrompt, (p)=>{
            const newAttachments = 'string' == typeof p ? [] : p.attachments ?? [];
            addAttachments(newAttachments);
        });
        return ()=>{
            unsubscribeSetAttachmentsLoading();
            unsubscribe();
        };
    }, [
        chatService,
        addAttachments
    ]);
    return /*#__PURE__*/ jsx(AutopilotAttachmentsContext.Provider, {
        value: {
            attachments,
            attachmentsLoading,
            addAttachments,
            removeAttachment,
            clearAttachments
        },
        children: children
    });
}
function useAttachments() {
    const context = react.useContext(AutopilotAttachmentsContext);
    if (!context) throw new Error('useAttachments must be used within a AutopilotAttachmentsProvider');
    return context;
}
export { AutopilotAttachmentsContext, AutopilotAttachmentsProvider, useAttachments };
