import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { Bot, ChevronDown, Circle, Loader2, User } from "lucide-react";
import { isQuestionnaireExecutionState, isErroredExecutionState, isTaskReviewExecutionState, isToolApprovalExecutionState, isWorkingExecutionState, normalizeTaskStatus, } from "../taskStatus";
import { getDisplayableAssignee } from "../assigneeDisplay";
import { ProjectPropertiesPanel } from "../components/ProjectPropertiesPanel";
import { orderTasksByBlockedDependenciesWithDepth } from "../utils/taskDependencyOrdering";
const DEFAULT_COST_LIMIT = 25;
function getBlockedTaskIds(taskList, blockersByTaskId, taskById) {
    const ids = new Set();
    for (const task of taskList) {
        if (normalizeTaskStatus(task.status, task.executionState) === "Done") {
            continue;
        }
        if ((task.executionBlockedByProjectIds?.length ?? 0) > 0) {
            ids.add(task.taskId);
            continue;
        }
        const blockerIds = blockersByTaskId.get(task.taskId) || [];
        const isBlocked = blockerIds.some((blockerId) => {
            const blockerTask = taskById.get(blockerId);
            if (!blockerTask)
                return true;
            return (normalizeTaskStatus(blockerTask.status, blockerTask.executionState) !== "Done");
        });
        if (isBlocked) {
            ids.add(task.taskId);
        }
    }
    return ids;
}
export function WizardView(props) {
    const { tasks, projectTasksLoading = false, dependencies, subprojectTaskLists, subprojectTasksLoading = false, selectedTaskId, onSelectTask, communicationPanel, projectId, canEditProperties = false, projectCostUsed = 0, projectCostLimit = null, } = props;
    const normalizedCostUsed = Number.isFinite(projectCostUsed)
        ? Math.max(0, projectCostUsed)
        : 0;
    const effectiveCostLimit = typeof projectCostLimit === "number" && projectCostLimit > 0
        ? projectCostLimit
        : DEFAULT_COST_LIMIT;
    const costProgressPct = Math.max(0, Math.min((normalizedCostUsed / effectiveCostLimit) * 100, 100));
    const costProgressClassName = costProgressPct >= 100
        ? "bg-red-500"
        : costProgressPct >= 80
            ? "bg-amber-500"
            : "bg-emerald-500";
    const allVisibleTasks = useMemo(() => [...tasks, ...subprojectTaskLists.flatMap((subproject) => subproject.tasks)], [tasks, subprojectTaskLists]);
    const taskById = useMemo(() => {
        const map = new Map();
        for (const task of allVisibleTasks)
            map.set(task.taskId, task);
        return map;
    }, [allVisibleTasks]);
    const blockersByTaskId = useMemo(() => {
        const map = new Map();
        for (const dependency of dependencies) {
            if (dependency.dependencyType !== "BlockedBy")
                continue;
            const list = map.get(dependency.taskId) || [];
            list.push(dependency.dependsOnTaskId);
            map.set(dependency.taskId, list);
        }
        return map;
    }, [dependencies]);
    const orderedTaskEntries = useMemo(() => orderTasksByBlockedDependenciesWithDepth(tasks, dependencies), [tasks, dependencies]);
    const orderedTasks = useMemo(() => orderedTaskEntries.map(({ task }) => task), [orderedTaskEntries]);
    const doneTaskIds = useMemo(() => {
        const ids = new Set();
        for (const task of tasks) {
            if (normalizeTaskStatus(task.status, task.executionState) === "Done") {
                ids.add(task.taskId);
            }
        }
        return ids;
    }, [tasks]);
    const blockedTaskIds = useMemo(() => {
        return getBlockedTaskIds(orderedTasks, blockersByTaskId, taskById);
    }, [orderedTasks, blockersByTaskId, taskById]);
    const selectedTask = selectedTaskId
        ? taskById.get(selectedTaskId) || null
        : null;
    const completedCount = doneTaskIds.size;
    const [collapsedProjectIds, setCollapsedProjectIds] = useState({});
    useEffect(() => {
        setCollapsedProjectIds((previous) => {
            const next = {};
            for (const subproject of subprojectTaskLists) {
                next[subproject.projectId] = previous[subproject.projectId] ?? false;
            }
            return next;
        });
    }, [subprojectTaskLists]);
    const renderTaskRows = (orderedTaskList, blockedIds, groupProjectId, loading = false) => {
        if (orderedTaskList.length === 0) {
            if (loading) {
                return (_jsxs("div", { className: "flex items-center gap-2 text-xs text-slate-500", children: [_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }), _jsx("span", { children: "Loading tasks..." })] }));
            }
            return _jsx("div", { className: "text-xs text-slate-500", children: "No tasks yet." });
        }
        return orderedTaskList.map(({ task, depth }) => {
            const isSelected = selectedTask?.taskId === task.taskId;
            const taskStatus = normalizeTaskStatus(task.status, task.executionState);
            const executionState = task.executionState;
            const isExecuting = isWorkingExecutionState(executionState);
            const hasQuestions = isQuestionnaireExecutionState(executionState);
            const isWaitingForInput = executionState === "WaitingForInput";
            const isWaitingForUser = executionState === "WaitingForUser";
            const isUnassigned = executionState === "Unassigned";
            const isAgentNotStarted = executionState === "AgentNotStarted";
            const isWaitingForApproval = isTaskReviewExecutionState(executionState);
            const isWaitingForToolApproval = isToolApprovalExecutionState(executionState);
            const hasAgentError = isErroredExecutionState(executionState);
            const isWaiting = taskStatus === "Waiting" || executionState === "Waiting";
            const isReview = taskStatus === "Review";
            const isDone = taskStatus === "Done";
            const isBlocked = blockedIds.has(task.taskId);
            const statusLabel = isBlocked
                ? null
                : isExecuting
                    ? "Working"
                    : isWaiting
                        ? "Waiting"
                        : isWaitingForApproval || isReview
                            ? "Awaiting approval"
                            : isWaitingForToolApproval
                                ? "Awaiting tool approval"
                                : hasQuestions
                                    ? "Questions"
                                    : isWaitingForInput
                                        ? "Waiting for input"
                                        : isWaitingForUser
                                            ? "Waiting for user"
                                            : isUnassigned
                                                ? "Unassigned"
                                                : executionState === "WaitingForDependency"
                                                    ? "Blocked"
                                                    : isAgentNotStarted
                                                        ? "Not started"
                                                        : hasAgentError
                                                            ? "Agent error"
                                                            : isDone
                                                                ? "Done"
                                                                : null;
            const isPlanTask = String(task.taskType ?? "").toLowerCase() === "plan" ||
                task.title === "Project Plan";
            const displayTaskId = task.taskKey || task.taskId.slice(0, 8).toUpperCase();
            const assigneeValue = getDisplayableAssignee(task, { isPlanTask });
            return (_jsx("div", { style: { paddingLeft: `${depth * 16}px` }, children: _jsxs("button", { type: "button", onClick: () => onSelectTask(task.taskId), "data-testid": groupProjectId
                        ? `taskboard-wizard-task-${groupProjectId}-${task.taskId}`
                        : undefined, className: `flex w-full min-w-0 items-center justify-between gap-2 rounded-md px-2 py-2 text-left text-sm transition-colors duration-200 ${isSelected ? "bg-blue-50 text-blue-900" : "hover:bg-slate-50"}`, children: [_jsxs("span", { className: "min-w-0 flex-1 overflow-hidden", children: [_jsx("span", { className: "block text-[10px] font-semibold tracking-widest text-slate-400 uppercase", children: displayTaskId }), _jsx("span", { className: "block truncate", children: task.title }), _jsxs("span", { className: "mt-0.5 flex items-center gap-1 text-[11px] text-slate-500", children: [task.assigneeType === "Agent" ? (_jsx(Bot, { className: "h-3 w-3 shrink-0" })) : (_jsx(User, { className: "h-3 w-3 shrink-0" })), _jsx("span", { className: "truncate", "data-testid": `taskboard-wizard-task-assignee-${task.taskId}`, title: assigneeValue, children: assigneeValue })] })] }), _jsxs("span", { className: "flex min-w-0 shrink-0 items-center gap-2", children: [statusLabel ? (_jsx("span", { className: `rounded-full px-2 py-0.5 text-[11px] font-medium ${isExecuting
                                        ? "bg-sky-100 text-sky-700"
                                        : isWaiting
                                            ? "bg-amber-100 text-amber-700"
                                            : isWaitingForApproval || isReview
                                                ? "bg-amber-100 text-amber-700"
                                                : isWaitingForToolApproval
                                                    ? "bg-amber-100 text-amber-700"
                                                    : hasQuestions
                                                        ? "bg-amber-100 text-amber-700"
                                                        : isWaitingForInput
                                                            ? "bg-amber-100 text-amber-700"
                                                            : isWaitingForUser
                                                                ? "bg-amber-100 text-amber-700"
                                                                : isUnassigned
                                                                    ? "bg-slate-100 text-slate-700"
                                                                    : hasAgentError
                                                                        ? "bg-red-100 text-red-700"
                                                                        : isDone
                                                                            ? "bg-emerald-100 text-emerald-700"
                                                                            : "bg-slate-100 text-slate-700"}`, children: statusLabel })) : null, isExecuting ? (_jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin text-sky-600", "aria-label": "Agent running" })) : isWaiting ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-amber-500", "aria-label": "Waiting" })) : isWaitingForApproval || isReview ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-amber-500", "aria-label": "Awaiting approval" })) : isWaitingForToolApproval ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-amber-500", "aria-label": "Awaiting tool approval" })) : hasQuestions ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-amber-500", "aria-label": "Questions pending" })) : isWaitingForInput ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-amber-500", "aria-label": "Waiting for input" })) : isWaitingForUser ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-amber-500", "aria-label": "Waiting for user" })) : isUnassigned ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-slate-300", "aria-label": "Unassigned" })) : hasAgentError ? (_jsx(Circle, { className: "h-3.5 w-3.5 fill-red-500 text-red-500", "aria-label": "Agent error" })) : isDone ? (_jsx(Circle, { className: "h-3.5 w-3.5 fill-emerald-500 text-emerald-500", "aria-label": "Completed" })) : isBlocked ? (_jsx(Circle, { className: "h-3.5 w-3.5 text-amber-500", "aria-label": "Blocked by dependencies" })) : (_jsx(Circle, { className: "h-3.5 w-3.5 text-slate-300", "aria-label": "Not started" }))] })] }) }, task.taskId));
        });
    };
    const renderTaskPanel = (options) => {
        const { projectId: panelProjectId, title, taskList, completedTaskCount: panelCompletedTaskCount, blockedIds, collapsible = false, collapsed = false, } = options;
        const panelTotalCount = taskList.length;
        const panelProgressPercent = panelTotalCount > 0
            ? Math.round((panelCompletedTaskCount / panelTotalCount) * 100)
            : 0;
        return (_jsxs("div", { className: "min-w-0 rounded-xl border bg-white p-4", "data-testid": `taskboard-wizard-task-panel-${panelProjectId}`, children: [_jsxs("div", { className: "mb-2 flex items-center justify-between gap-2", children: [_jsx("div", { className: "min-w-0", children: collapsible ? (_jsxs("button", { type: "button", onClick: () => setCollapsedProjectIds((previous) => ({
                                    ...previous,
                                    [panelProjectId]: !collapsed,
                                })), "aria-expanded": !collapsed, "aria-controls": `taskboard-wizard-task-panel-content-${panelProjectId}`, "data-testid": `taskboard-wizard-task-panel-toggle-${panelProjectId}`, className: "flex items-center gap-2 text-left text-sm font-semibold text-slate-800", children: [_jsx(ChevronDown, { className: `h-4 w-4 transition-transform ${collapsed ? "-rotate-90" : "rotate-0"}` }), _jsx("span", { className: "truncate", children: title })] })) : (_jsx("span", { className: "text-sm font-semibold text-slate-800", children: title })) }), _jsxs("span", { className: "rounded-md bg-slate-100 px-2 py-0.5 text-xs font-semibold text-slate-700", children: [panelCompletedTaskCount, "/", panelTotalCount, " done"] })] }), _jsx("div", { className: "mb-3", children: _jsx("div", { className: "h-1.5 overflow-hidden rounded-full bg-slate-100", children: _jsx("div", { className: "h-full rounded-full bg-emerald-500 transition-all", style: { width: `${panelProgressPercent}%` } }) }) }), collapsed ? null : (_jsx("div", { id: `taskboard-wizard-task-panel-content-${panelProjectId}`, className: "min-w-0 space-y-1", children: renderTaskRows(taskList, blockedIds, panelProjectId, panelProjectId === projectId
                        ? projectTasksLoading
                        : subprojectTasksLoading) }))] }, panelProjectId));
    };
    const allTasksCard = (_jsxs("div", { className: "space-y-3", children: [renderTaskPanel({
                projectId,
                title: `${props.projectTitle} Tasks`,
                taskList: orderedTaskEntries,
                completedTaskCount: completedCount,
                blockedIds: blockedTaskIds,
            }), subprojectTasksLoading && subprojectTaskLists.length === 0 ? (_jsxs("div", { className: "flex items-center gap-2 px-2 text-sm text-slate-500", "data-testid": "taskboard-wizard-subprojects-loading", children: [_jsx(Loader2, { className: "h-4 w-4 animate-spin" }), _jsx("span", { children: "Loading subprojects..." })] })) : null, subprojectTaskLists.map((subproject) => {
                const orderedSubprojectTaskEntries = orderTasksByBlockedDependenciesWithDepth(subproject.tasks, dependencies);
                const orderedSubprojectTasks = orderedSubprojectTaskEntries.map(({ task }) => task);
                const subprojectBlockedTaskIds = getBlockedTaskIds(orderedSubprojectTasks, blockersByTaskId, taskById);
                const subprojectCompletedCount = orderedSubprojectTasks.filter((task) => normalizeTaskStatus(task.status, task.executionState) === "Done").length;
                return renderTaskPanel({
                    projectId: subproject.projectId,
                    title: `${subproject.title} (${orderedSubprojectTasks.length})`,
                    taskList: orderedSubprojectTaskEntries,
                    completedTaskCount: subprojectCompletedCount,
                    blockedIds: subprojectBlockedTaskIds,
                    collapsible: true,
                    collapsed: collapsedProjectIds[subproject.projectId] ?? false,
                });
            })] }));
    return (_jsxs("div", { className: `flex flex-col gap-3 p-2 md:p-4 ${communicationPanel ? "overflow-y-auto md:h-full md:min-h-0 md:overflow-hidden" : "h-full min-h-0 overflow-y-auto"}`, children: [_jsxs("div", { className: "grid shrink-0 gap-3 md:grid-cols-[minmax(0,1fr)_minmax(260px,320px)] md:items-start", children: [_jsx("div", { children: _jsx(ProjectPropertiesPanel, { projectId: projectId, canEdit: canEditProperties }) }), _jsxs("div", { className: "rounded-xl border border-slate-200 bg-white p-4 shadow-sm", "data-testid": "taskboard-wizard-project-cost-card", children: [_jsxs("div", { className: "mb-1.5 flex items-center justify-between gap-3 text-[11px] font-semibold uppercase tracking-wider text-slate-500", children: [_jsx("span", { children: "Current total cost" }), _jsxs("span", { className: "tracking-normal text-slate-600 normal-case", "data-testid": "taskboard-wizard-project-cost-value", children: ["$", normalizedCostUsed.toFixed(2), ` / $${effectiveCostLimit.toFixed(2)}`] })] }), _jsx("div", { className: "h-2 w-full overflow-hidden rounded-full bg-slate-100", "data-testid": "taskboard-wizard-project-cost-bar", children: _jsx("div", { className: `h-full ${costProgressClassName}`, style: { width: `${costProgressPct}%` } }) })] })] }), communicationPanel ? (_jsxs("div", { className: "grid gap-3 md:min-h-0 md:flex-1 md:grid-cols-[minmax(320px,0.95fr)_minmax(0,1.35fr)] md:overflow-hidden", children: [_jsx("div", { className: "min-w-0 md:min-h-0 md:overflow-y-auto", children: allTasksCard }), _jsx("div", { className: "flex flex-col overflow-hidden rounded-xl border border-slate-200 bg-white shadow-sm md:min-h-0 md:flex-1", children: communicationPanel })] })) : (allTasksCard)] }));
}
//# sourceMappingURL=WizardView.js.map