import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { useEffect, useMemo, useState, useCallback, useRef } from "react";
import { FileText } from "lucide-react";
import { toast } from "sonner";
import { Textarea } from "../../components/ui/textarea";
import { Label } from "../../components/ui/label";
import { updateTask } from "../services/taskService";
import { useEditContext } from "../../editor/client/editContext";
export function PlanningView(props) {
    const { project, tasks, onSelectTask, onRefresh } = props;
    const editContext = useEditContext();
    const planTask = useMemo(() => {
        return (tasks.find((t) => String(t.taskType ?? "").toLowerCase() === "plan") ??
            tasks.find((t) => t.title === "Project Plan") ??
            null);
    }, [tasks]);
    const canEdit = project.permission === "Owner" || project.permission === "Editor";
    const [localResultData, setLocalResultData] = useState(planTask?.resultData ?? "");
    // Track whether the textarea is focused so we don't overwrite user edits
    const isFocusedRef = useRef(false);
    // Buffer incoming WS updates while focused; apply on blur
    const pendingUpdateRef = useRef(null);
    // Sync local state when planTask changes (but not while user is editing)
    useEffect(() => {
        if (!isFocusedRef.current) {
            setLocalResultData(planTask?.resultData ?? "");
        }
    }, [planTask?.taskId, planTask?.resultData]);
    const saveResultData = useCallback(async () => {
        if (!planTask)
            return;
        const trimmed = localResultData.trim();
        if (trimmed === (planTask.resultData ?? "").trim())
            return;
        const result = await updateTask({ taskId: planTask.taskId, resultData: trimmed || null });
        if (result.type !== "success") {
            toast.error(result.summary || "Failed to update plan");
            return;
        }
        // If a WS update arrived while we were editing, refresh to get latest
        if (pendingUpdateRef.current !== null) {
            pendingUpdateRef.current = null;
            await onRefresh?.();
        }
    }, [planTask, localResultData, onRefresh]);
    // Handle textarea focus/blur for WS conflict management
    const handleFocus = useCallback(() => {
        isFocusedRef.current = true;
    }, []);
    const handleBlur = useCallback(() => {
        isFocusedRef.current = false;
        void saveResultData();
    }, [saveResultData]);
    // Listen for task:updated WebSocket events to live-sync the plan textarea
    useEffect(() => {
        const addListener = editContext?.addSocketMessageListener;
        if (!addListener || !planTask)
            return;
        const handler = (message) => {
            if (message?.type !== "task:updated")
                return;
            const payload = message.payload;
            if (!payload || payload.taskId !== planTask.taskId)
                return;
            if (payload.resultData == null)
                return;
            if (isFocusedRef.current) {
                // User is actively editing - buffer the update
                pendingUpdateRef.current = payload.resultData;
            }
            else {
                // User is not editing - apply immediately
                setLocalResultData(payload.resultData);
                pendingUpdateRef.current = null;
            }
        };
        const unsubscribe = addListener(handler);
        return () => {
            unsubscribe();
        };
    }, [editContext, planTask?.taskId]);
    // While planning, poll for the Plan task to appear so the user can open it immediately
    // after the agent creates it (tasks are otherwise only refreshed on manual actions).
    useEffect(() => {
        if (!onRefresh)
            return;
        if (planTask)
            return;
        if (project.project.status !== "Planning")
            return;
        let cancelled = false;
        const tick = async () => {
            if (cancelled)
                return;
            try {
                await onRefresh();
            }
            catch {
                // ignore
            }
        };
        // Fire immediately, then poll briefly
        void tick();
        const id = window.setInterval(() => void tick(), 2000);
        return () => {
            cancelled = true;
            window.clearInterval(id);
        };
    }, [onRefresh, planTask, project.project.status]);
    return (_jsxs("div", { className: "rounded-lg border bg-white p-6 shadow-sm", children: [_jsxs("div", { className: "min-w-0", children: [_jsx("div", { className: "text-sm font-semibold text-slate-900", children: "Planning mode" }), _jsxs("div", { className: "mt-1 text-xs text-muted-foreground", children: ["This project is in ", _jsx("span", { className: "font-medium", children: project.project.status }), ". The Project Planner agent is shown in the right panel."] })] }), _jsxs("div", { className: "mt-5 grid gap-2", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(FileText, { className: "h-4 w-4 text-muted-foreground" }), _jsx(Label, { children: "Project Plan" })] }), planTask ? (_jsxs(_Fragment, { children: [_jsx(Textarea, { value: localResultData, onChange: (e) => setLocalResultData(e.target.value), onFocus: handleFocus, onBlur: handleBlur, rows: 12, placeholder: "Waiting for the planner to write the plan\u2026", disabled: !canEdit, className: "font-mono text-sm overflow-y-auto min-h-[220px] max-h-[360px] [field-sizing:fixed]" }), _jsxs("div", { className: "text-xs text-muted-foreground", children: ["Approve by moving this plan task to ", _jsx("span", { className: "font-medium text-foreground", children: "Done" }), "."] })] })) : (_jsxs("div", { className: "rounded-md border border-dashed bg-slate-50 p-8 text-center", children: [_jsx(FileText, { className: "mx-auto h-8 w-8 text-muted-foreground/40" }), _jsx("div", { className: "mt-2 text-sm font-medium text-muted-foreground", children: "No plan yet" }), _jsx("div", { className: "mt-1 text-xs text-muted-foreground", children: "Waiting for the planner to create the plan task." })] }))] })] }));
}
//# sourceMappingURL=PlanningView.js.map