import { useCallback, useEffect, useMemo, useState, } from "react";
import { getAgent, } from "../editor/services/agentService";
import { getLinkedAgentId } from "./taskAgentLink";
import { normalizeTaskStatus } from "./taskStatus";
export function useTaskBoardAgentPanelState({ currentItemDescriptor, editContext, isMobile, mobileActiveTab, selectedTask, selectedTaskId, setMobileActiveTab, showEditorPanel, }) {
    const [previewItemName, setPreviewItemName] = useState("");
    const [previewItemPath, setPreviewItemPath] = useState("");
    const [agentContextItems, setAgentContextItems] = useState([]);
    const [contextItemNamesByKey, setContextItemNamesByKey] = useState({});
    const [contextItemPathsByKey, setContextItemPathsByKey] = useState({});
    const selectedTaskIsPlan = useMemo(() => {
        const taskType = String(selectedTask?.taskType ?? "").toLowerCase();
        return taskType === "plan" || selectedTask?.title === "Project Plan";
    }, [selectedTask]);
    const selectedTaskIsBlocked = useMemo(() => {
        if (!selectedTask)
            return false;
        if ((selectedTask.executionBlockedByProjectIds?.length ?? 0) > 0)
            return true;
        return selectedTask.executionState === "WaitingForDependency";
    }, [selectedTask]);
    const selectedTaskHasAssignedAgentProfile = useMemo(() => {
        if (!selectedTask)
            return false;
        return selectedTask.assigneeType === "Agent" && !!selectedTask.assigneeId;
    }, [selectedTask]);
    const canRunAssignedAgent = useMemo(() => {
        return !selectedTaskIsBlocked;
    }, [selectedTaskIsBlocked]);
    const runAssignedAgentDisabledReason = useMemo(() => {
        if (selectedTaskIsBlocked) {
            return "This task is blocked by unfinished dependencies.";
        }
        return undefined;
    }, [selectedTaskIsBlocked]);
    const currentAgentId = useMemo(() => {
        return getLinkedAgentId(selectedTask);
    }, [selectedTask]);
    const selectedTaskStatus = useMemo(() => {
        if (!selectedTask)
            return null;
        return normalizeTaskStatus(selectedTask.status, selectedTask.executionState);
    }, [selectedTask]);
    const selectedTaskHasResultData = useMemo(() => {
        return !!selectedTask?.resultData?.trim();
    }, [selectedTask?.resultData]);
    const shouldHideAgentPanelForSelectedTask = useMemo(() => {
        return (!!selectedTask &&
            selectedTaskIsPlan &&
            selectedTaskStatus === "Done" &&
            selectedTaskHasResultData);
    }, [
        selectedTask,
        selectedTaskIsPlan,
        selectedTaskStatus,
        selectedTaskHasResultData,
    ]);
    const displayAgentId = useMemo(() => {
        return currentAgentId;
    }, [currentAgentId]);
    useEffect(() => {
        if (isMobile && selectedTaskId) {
            setMobileActiveTab(1);
        }
    }, [selectedTaskId, isMobile, setMobileActiveTab]);
    useEffect(() => {
        if (isMobile && displayAgentId && !shouldHideAgentPanelForSelectedTask) {
            setMobileActiveTab(2);
        }
    }, [
        displayAgentId,
        isMobile,
        setMobileActiveTab,
        shouldHideAgentPanelForSelectedTask,
    ]);
    useEffect(() => {
        if (!isMobile)
            return;
        if (!shouldHideAgentPanelForSelectedTask)
            return;
        if (mobileActiveTab !== 2)
            return;
        setMobileActiveTab(1);
    }, [
        isMobile,
        mobileActiveTab,
        setMobileActiveTab,
        shouldHideAgentPanelForSelectedTask,
    ]);
    useEffect(() => {
        if (!showEditorPanel && mobileActiveTab === 3) {
            setMobileActiveTab(0);
        }
    }, [mobileActiveTab, setMobileActiveTab, showEditorPanel]);
    const currentItemKey = useMemo(() => {
        if (!currentItemDescriptor)
            return "";
        return `${currentItemDescriptor.id}|${currentItemDescriptor.language}|${currentItemDescriptor.version}`;
    }, [currentItemDescriptor]);
    const agentPanelMode = useMemo(() => {
        if (!selectedTask)
            return "no-task-selected";
        if (displayAgentId)
            return "agent";
        return "no-agent";
    }, [displayAgentId, selectedTask]);
    const previewItemVersion = useMemo(() => {
        if (!currentItemDescriptor)
            return null;
        return currentItemDescriptor.version === 0
            ? (editContext?.item?.version ?? null)
            : currentItemDescriptor.version;
    }, [currentItemDescriptor, editContext?.item?.version]);
    const contextItemOptions = useMemo(() => {
        return agentContextItems.map((contextItem) => {
            const key = `${contextItem.id}|${contextItem.language}|${contextItem.version}`;
            const name = contextItemNamesByKey[key] || contextItem.name || contextItem.id;
            const path = contextItemPathsByKey[key] || contextItem.path || "";
            return {
                value: key,
                label: name,
                description: `${path || contextItem.id} (${contextItem.language}/v${contextItem.version})`,
            };
        });
    }, [agentContextItems, contextItemNamesByKey, contextItemPathsByKey]);
    const selectedContextItemValue = useMemo(() => {
        if (currentItemKey)
            return currentItemKey;
        const first = agentContextItems[0];
        if (!first)
            return "";
        return `${first.id}|${first.language}|${first.version}`;
    }, [currentItemKey, agentContextItems]);
    const hasMultipleContextItems = contextItemOptions.length > 1;
    useEffect(() => {
        if (!currentAgentId) {
            setAgentContextItems([]);
            return;
        }
        let cancelled = false;
        getAgent(currentAgentId)
            .then((agent) => {
            if (cancelled)
                return;
            const rawContext = agent?.agentContext;
            if (!rawContext) {
                setAgentContextItems([]);
                return;
            }
            let parsed = null;
            try {
                parsed = JSON.parse(rawContext);
            }
            catch {
                parsed = null;
            }
            const items = (parsed?.items || []).filter((item) => !!item?.id && !!item?.language && typeof item?.version === "number");
            setAgentContextItems(items);
        })
            .catch(() => {
            if (cancelled)
                return;
            setAgentContextItems([]);
        });
        return () => {
            cancelled = true;
        };
    }, [currentAgentId]);
    useEffect(() => {
        if (!editContext || agentContextItems.length === 0) {
            setContextItemNamesByKey({});
            setContextItemPathsByKey({});
            return;
        }
        let cancelled = false;
        Promise.all(agentContextItems.map(async (contextItem) => {
            const key = `${contextItem.id}|${contextItem.language}|${contextItem.version}`;
            const descriptor = {
                id: contextItem.id,
                language: contextItem.language,
                version: contextItem.version,
            };
            const item = await editContext.itemsRepository.getItem(descriptor);
            return {
                key,
                name: item?.name || contextItem.name || "",
                path: item?.path || contextItem.path || "",
            };
        }))
            .then((results) => {
            if (cancelled)
                return;
            const nextNames = {};
            const nextPaths = {};
            for (const result of results) {
                nextNames[result.key] = result.name;
                nextPaths[result.key] = result.path;
            }
            setContextItemNamesByKey(nextNames);
            setContextItemPathsByKey(nextPaths);
        })
            .catch(() => {
            if (cancelled)
                return;
            setContextItemNamesByKey({});
            setContextItemPathsByKey({});
        });
        return () => {
            cancelled = true;
        };
    }, [editContext, agentContextItems]);
    const handleSelectContextItem = useCallback((value) => {
        const [id, language, versionText] = value.split("|");
        const version = Number(versionText);
        if (!id || !language || Number.isNaN(version) || !editContext?.loadItem) {
            return;
        }
        void editContext.loadItem({ id, language, version });
    }, [editContext]);
    useEffect(() => {
        if (!editContext || !currentItemDescriptor) {
            setPreviewItemName("");
            setPreviewItemPath("");
            return;
        }
        const activeItem = editContext.item;
        const itemMatchesDescriptor = activeItem?.id === currentItemDescriptor.id &&
            activeItem?.language === currentItemDescriptor.language;
        if (itemMatchesDescriptor) {
            setPreviewItemName(activeItem?.name || "");
            setPreviewItemPath(activeItem?.path || "");
            return;
        }
        let cancelled = false;
        editContext.itemsRepository
            .getItem(currentItemDescriptor)
            .then((item) => {
            if (cancelled)
                return;
            setPreviewItemName(item?.name || "");
            setPreviewItemPath(item?.path || "");
        })
            .catch(() => {
            if (cancelled)
                return;
            setPreviewItemName("");
            setPreviewItemPath("");
        });
        return () => {
            cancelled = true;
        };
    }, [
        currentItemDescriptor,
        currentItemDescriptor?.id,
        currentItemDescriptor?.language,
        currentItemDescriptor?.version,
        editContext,
        editContext?.item?.id,
        editContext?.item?.language,
        editContext?.item?.name,
        editContext?.item?.path,
    ]);
    return {
        agentPanelMode,
        canRunAssignedAgent,
        contextItemOptions,
        displayAgentId,
        handleSelectContextItem,
        hasMultipleContextItems,
        previewItemName,
        previewItemPath,
        previewItemVersion,
        runAssignedAgentDisabledReason,
        selectedContextItemValue,
        selectedTaskHasAssignedAgentProfile,
        selectedTaskIsBlocked,
        selectedTaskIsPlan,
        shouldHideAgentPanelForSelectedTask,
    };
}
//# sourceMappingURL=useTaskBoardAgentPanelState.js.map