import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
import { ClipboardCheck, Search } from "lucide-react";
import { Input } from "../../components/ui/input";
import { cn } from "../../lib/utils";
import { getTaskBoardNavSnapshot, setTaskBoardNavState, subscribeTaskBoardNav, } from "../taskBoardNavStore";
import { useEditContext } from "../../editor/client/editContext";
import { getTasks } from "../services/taskService";
import { normalizeTaskStatus } from "../taskStatus";
export function TaskBoardMyTasksSidebar() {
    const editContext = useEditContext();
    const nav = useSyncExternalStore(subscribeTaskBoardNav, getTaskBoardNavSnapshot, getTaskBoardNavSnapshot);
    const [search, setSearch] = useState("");
    useEffect(() => {
        const currentUserName = editContext?.user?.name?.trim().toLowerCase();
        if (!currentUserName || nav.projectOptions.length === 0) {
            setTaskBoardNavState({ myTasks: [], myTasksLoading: false });
            return;
        }
        let cancelled = false;
        setTaskBoardNavState({ myTasksLoading: true });
        (async () => {
            const taskRequests = nav.projectOptions.map(async (project) => {
                const result = await getTasks(project.projectId);
                if (result.type !== "success")
                    return [];
                return (result.data ?? [])
                    .filter((task) => task.assigneeType === "user" &&
                    (task.assigneeId ?? "").trim().toLowerCase() === currentUserName)
                    .map((task) => ({
                    taskId: task.taskId,
                    projectId: project.projectId,
                    title: task.title,
                    projectTitle: project.title,
                    status: normalizeTaskStatus(task.status, task.executionState),
                    updatedAt: task.updatedAt,
                }));
            });
            const list = (await Promise.all(taskRequests)).flat().sort((a, b) => {
                const aTime = a.updatedAt ? new Date(a.updatedAt).getTime() : 0;
                const bTime = b.updatedAt ? new Date(b.updatedAt).getTime() : 0;
                return bTime - aTime;
            });
            if (cancelled)
                return;
            setTaskBoardNavState({ myTasks: list, myTasksLoading: false });
        })().catch(() => {
            if (cancelled)
                return;
            setTaskBoardNavState({ myTasks: [], myTasksLoading: false });
        });
        return () => {
            cancelled = true;
        };
    }, [editContext?.user?.name, nav.projectOptions]);
    const items = useMemo(() => {
        const query = search.trim().toLowerCase();
        if (!query)
            return nav.myTasks;
        return nav.myTasks.filter((task) => {
            return (task.title.toLowerCase().includes(query) ||
                task.projectTitle.toLowerCase().includes(query) ||
                task.status.toLowerCase().includes(query));
        });
    }, [nav.myTasks, search]);
    return (_jsxs("div", { className: "flex h-full min-h-0 flex-col bg-white", "data-testid": "taskboard-my-tasks-sidebar", children: [_jsx("div", { className: "border-b border-slate-200 px-3 py-2.5", children: _jsxs("div", { className: "relative", children: [_jsx(Search, { className: "pointer-events-none absolute top-1/2 left-2.5 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" }), _jsx(Input, { value: search, onChange: (event) => setSearch(event.target.value), placeholder: "Search my tasks...", className: "h-8 pl-8 text-xs", "data-testid": "taskboard-my-tasks-search" })] }) }), _jsx("div", { className: "min-h-0 flex-1 overflow-y-auto p-2", children: nav.myTasksLoading ? (_jsx("div", { className: "rounded-md border border-dashed px-3 py-8 text-center text-xs text-slate-400", children: "Loading my tasks..." })) : items.length === 0 ? (_jsx("div", { className: "rounded-md border border-dashed px-3 py-8 text-center text-xs text-slate-400", children: "No tasks assigned to you" })) : (_jsx("div", { className: "flex flex-col gap-1", children: items.map((task) => {
                        const selected = nav.selectedProjectId === task.projectId &&
                            nav.selectedTaskId === task.taskId;
                        return (_jsxs("button", { type: "button", className: cn("w-full rounded-md border px-2 py-2 text-left transition-colors", selected
                                ? "border-slate-300 bg-slate-50"
                                : "border-transparent hover:border-slate-200 hover:bg-slate-50/70"), onClick: () => nav.onSelectMyTask?.({
                                projectId: task.projectId,
                                taskId: task.taskId,
                            }), "data-testid": `taskboard-my-task-option-${task.taskId}`, children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(ClipboardCheck, { className: "h-3.5 w-3.5 text-slate-400" }), _jsx("span", { className: "truncate text-xs font-medium text-slate-800", children: task.title })] }), _jsx("div", { className: "mt-0.5 truncate pl-5 text-[10px] text-slate-500", children: task.projectTitle }), _jsx("div", { className: "mt-1 pl-5 text-[10px] font-semibold uppercase tracking-wider text-slate-400", children: task.status })] }, task.taskId));
                    }) })) })] }));
}
//# sourceMappingURL=TaskBoardMyTasksSidebar.js.map