import { useCallback, useState } from "react";
import { useEditContext } from "../../client/editContext";
import { updateAgentContext, } from "../../services/agentService";
import { getComponentById } from "../../componentTreeHelper";
/**
 * Returns drop handlers that the agent prompt textarea can use to accept:
 * - File drops → forwarded to AgentDocumentList.uploadFiles
 * - Editor item drops (pages) → appended to agent context
 * - Editor component drops → appended to agent context
 */
export function useAgentTextareaDropHandlers({ agent, agentMetadata, setAgentMetadata, setAgent, documentListRef, documentsEnabled, }) {
    const editContext = useEditContext();
    const [isDragOver, setIsDragOver] = useState(false);
    const addComponentIdsToContext = useCallback(async (ids) => {
        if (!agent?.id || !ids?.length)
            return;
        const current = agentMetadata || {};
        const currentComponents = current.components || [];
        const existingIds = new Set(currentComponents.map((c) => c.componentId));
        const newComponentIds = ids.filter((id) => !!id && !existingIds.has(id));
        if (newComponentIds.length === 0)
            return;
        const pageItem = editContext?.currentItemDescriptor
            ? {
                id: editContext.currentItemDescriptor.id,
                language: editContext.currentItemDescriptor.language,
                version: editContext.currentItemDescriptor.version,
                name: editContext.item?.name,
                path: undefined,
            }
            : undefined;
        const newComponents = newComponentIds.map((componentId) => {
            let componentName;
            if (editContext?.page) {
                try {
                    const comp = getComponentById(componentId, editContext.page);
                    componentName = comp?.name || undefined;
                }
                catch {
                    // ignore lookup errors
                }
            }
            return {
                componentId,
                componentName,
                pageItem: pageItem,
            };
        });
        const next = {
            ...current,
            components: [...currentComponents, ...newComponents],
        };
        try {
            if (agent.status === "new") {
                setAgentMetadata(next);
                return;
            }
            await updateAgentContext(agent.id, next);
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
        }
        catch (e) {
            console.error("Failed to update agent context (add components)", e);
        }
    }, [agent, agentMetadata, editContext, setAgent, setAgentMetadata]);
    const addPagesToContextFromItems = useCallback(async (items) => {
        if (!agent?.id || !items?.length)
            return;
        const current = agentMetadata || {};
        const currentPages = current.items || [];
        const existingPageIds = new Set(currentPages.map((p) => `${p.id}-${p.language}-${p.version}`));
        const pagesToAdd = items
            .filter((it) => !!it?.id)
            .map((it) => {
            const anyIt = it;
            const page = {
                id: it.id,
                language: it.language,
                version: it.version,
            };
            const candidateName = anyIt?.displayName ||
                anyIt?.name;
            if (candidateName)
                page.name = candidateName;
            if (anyIt?.path)
                page.path = anyIt.path;
            return page;
        })
            .filter((p) => !existingPageIds.has(`${p.id}-${p.language}-${p.version}`));
        if (pagesToAdd.length === 0)
            return;
        const next = {
            ...current,
            items: [...currentPages, ...pagesToAdd],
        };
        try {
            if (agent.status === "new") {
                setAgentMetadata(next);
                return;
            }
            await updateAgentContext(agent.id, next);
            setAgentMetadata(next);
            setAgent((prev) => prev ? { ...prev, agentContext: JSON.stringify(next) } : prev);
        }
        catch (e) {
            console.error("Failed to update agent context (add items/pages)", e);
        }
    }, [agent, agentMetadata, setAgent, setAgentMetadata]);
    const onDragOver = useCallback((e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = "copy";
        if (!isDragOver)
            setIsDragOver(true);
    }, [isDragOver]);
    const onDragEnter = onDragOver;
    const onDragLeave = useCallback((e) => {
        // Only clear state when the cursor actually leaves the wrapper.
        // dragleave fires for every child element too.
        if (e.currentTarget === e.target) {
            setIsDragOver(false);
        }
    }, []);
    const onDrop = useCallback(async (e) => {
        e.preventDefault();
        setIsDragOver(false);
        try {
            // 1) File drops → forward to documents upload
            if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
                if (documentsEnabled) {
                    await documentListRef.current?.uploadFiles(e.dataTransfer.files);
                }
                return;
            }
            // 2) Editor drag objects → add to agent context
            const dragObj = editContext?.dragObject;
            if (dragObj?.type === "component") {
                const idsFromComponents = (dragObj.components || [])
                    .map((c) => c.id)
                    .filter((x) => !!x);
                const idFromData = e.dataTransfer.getData("componentId");
                const allIds = Array.from(new Set([...idsFromComponents, idFromData].filter((x) => !!x)));
                if (allIds.length) {
                    await addComponentIdsToContext(allIds);
                    return;
                }
            }
            if (dragObj?.type === "items" && dragObj.items?.length) {
                await addPagesToContextFromItems(dragObj.items);
                return;
            }
            // 3) Fallbacks
            const fallbackComponentId = e.dataTransfer.getData("componentId");
            if (fallbackComponentId) {
                await addComponentIdsToContext([fallbackComponentId]);
                return;
            }
            try {
                const textData = e.dataTransfer.getData("text/plain");
                if (textData) {
                    const parsed = JSON.parse(textData);
                    if (Array.isArray(parsed)) {
                        await addPagesToContextFromItems(parsed);
                        return;
                    }
                    else if (parsed?.id) {
                        await addPagesToContextFromItems([parsed]);
                        return;
                    }
                }
            }
            catch {
                // not JSON, ignore
            }
        }
        catch (err) {
            console.error("Textarea drop failed", err);
        }
    }, [
        addComponentIdsToContext,
        addPagesToContextFromItems,
        documentListRef,
        documentsEnabled,
        editContext,
    ]);
    return { isDragOver, onDragOver, onDragEnter, onDragLeave, onDrop };
}
//# sourceMappingURL=useAgentTextareaDropHandlers.js.map