'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useMemo, useCallback, useRef } from 'react';
import { useRouter } from 'next/navigation';
import { ArrowLeft, Plus, FolderKanban, Settings } from 'lucide-react';
import { cn } from '../../../lib/utils.js';
import { Button } from '../../ui/button.js';
import { Badge } from '../../ui/badge.js';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../../ui/tabs.js';
import { WorkItemRow } from './work-item-row.js';
import { CreateWorkItemDialog } from './create-work-item-dialog.js';
import { ViewSwitcher } from '../../pm/view-switcher/view-switcher.js';
import { BoardView } from '../../pm/board-view/board-view.js';
import { TableView } from '../../pm/table-view/table-view.js';
import { CalendarView } from '../../pm/calendar-view/calendar-view.js';
import { AnalyticsDashboard } from '../../pm/analytics/analytics-dashboard.js';
import { TimelineViewWrapper } from '../../pm/timeline-view/timeline-view-wrapper.js';
import { CyclePanel } from '../../pm/cycle-panel/cycle-panel.js';
import { ModulePanel } from '../../pm/module-panel/module-panel.js';
import { EpicPanel } from '../../pm/epic-panel/epic-panel.js';
import { EstimateSettings } from '../../pm/estimate-settings/estimate-settings.js';
import { updateWorkItem } from '../../../app/actions/update-work-item.js';
import { listWorkItems } from '../../../app/actions/list-work-items.js';
import { listCycles } from '../../../app/actions/list-cycles.js';
import { listModules } from '../../../app/actions/list-modules.js';
import { usePmEvents } from '../../../hooks/use-pm-events.js';
export function ProjectDetailClient({ project, workItems: initialWorkItems, states, labels, cycles: initialCycles = [], modules: initialModules = [], epics: initialEpics = [], className, }) {
    const [workItems, setWorkItems] = useState(initialWorkItems);
    const [cycles, setCycles] = useState(initialCycles);
    const [modules, setModules] = useState(initialModules);
    const [epics, setEpics] = useState(initialEpics);
    const [groupBy, setGroupBy] = useState('all');
    const [viewMode, setViewMode] = useState('list');
    const [showCreateDialog, setShowCreateDialog] = useState(false);
    const router = useRouter();
    // Real-time updates via SSE — debounced refetch on PM entity changes
    const refreshTimeoutRef = useRef(null);
    const handlePmEvent = useCallback((event) => {
        // Debounce: batch rapid events into a single refetch
        if (refreshTimeoutRef.current)
            clearTimeout(refreshTimeoutRef.current);
        refreshTimeoutRef.current = setTimeout(async () => {
            if (event.eventType.startsWith('work_item_')) {
                const result = await listWorkItems(project.id);
                if (result.workItems)
                    setWorkItems(result.workItems);
            }
            else if (event.eventType.startsWith('cycle_')) {
                const result = await listCycles(project.id);
                if (result.cycles)
                    setCycles(result.cycles);
            }
            else if (event.eventType.startsWith('module_')) {
                const result = await listModules(project.id);
                if (result.modules)
                    setModules(result.modules);
            }
        }, 300);
    }, [project.id]);
    usePmEvents({ projectId: project.id, onEvent: handlePmEvent });
    const stateMap = useMemo(() => new Map(states.map((s) => [s.id, s])), [states]);
    const grouped = useMemo(() => {
        if (groupBy === 'state') {
            const map = new Map();
            for (const wi of workItems) {
                const state = stateMap.get(wi.stateId);
                const key = state?.name ?? 'Unknown';
                const arr = map.get(key) ?? [];
                arr.push(wi);
                map.set(key, arr);
            }
            return Array.from(map.entries()).map(([key, items]) => ({ label: key, items }));
        }
        if (groupBy === 'priority') {
            const order = ['Urgent', 'High', 'Medium', 'Low', 'None'];
            const map = new Map();
            for (const wi of workItems) {
                const key = wi.priority ?? 'None';
                const arr = map.get(key) ?? [];
                arr.push(wi);
                map.set(key, arr);
            }
            return order.filter((k) => map.has(k)).map((key) => ({ label: key, items: map.get(key) }));
        }
        return [{ label: 'All', items: workItems }];
    }, [workItems, groupBy, stateMap]);
    const handleWorkItemCreated = (workItem) => {
        setWorkItems((prev) => [...prev, workItem]);
        setShowCreateDialog(false);
    };
    const handleWorkItemUpdate = useCallback(async (workItemId, fields) => {
        // Optimistic local update
        setWorkItems((prev) => prev.map((wi) => (wi.id === workItemId ? { ...wi, ...fields } : wi)));
        await updateWorkItem(workItemId, fields);
    }, []);
    const handleCardClick = useCallback((workItem) => {
        router.push(`/projects/${project.slug}/items/${workItem.id}`);
    }, [router, project.slug]);
    return (_jsxs("div", { "data-testid": "project-detail-client", className: cn('space-y-4', className), children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx(Button, { variant: "ghost", size: "sm", className: "h-7 w-7 p-0", onClick: () => router.push('/projects'), "data-testid": "back-to-projects", children: _jsx(ArrowLeft, { className: "h-4 w-4" }) }), _jsx(FolderKanban, { className: "text-muted-foreground h-4 w-4" }), _jsx("h1", { className: "text-sm font-bold tracking-tight", children: project.name }), _jsx(Badge, { variant: "outline", className: "text-[10px]", children: project.identifierPrefix }), _jsxs("span", { className: "text-muted-foreground text-[10px]", children: [workItems.length, " items"] })] }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsx(ViewSwitcher, { activeView: viewMode, onViewChange: setViewMode }), _jsxs(Button, { variant: "outline", size: "sm", className: "h-7 text-xs", onClick: () => setShowCreateDialog(true), "data-testid": "create-work-item-btn", children: [_jsx(Plus, { className: "mr-1 h-3 w-3" }), "New Item"] }), _jsx(Button, { variant: "ghost", size: "sm", className: "h-7 w-7 p-0", onClick: () => router.push(`/projects/${project.slug}/settings`), "data-testid": "project-settings-btn", title: "Project Settings", children: _jsx(Settings, { className: "h-3.5 w-3.5" }) })] })] }), project.description ? (_jsx("p", { className: "text-muted-foreground text-xs", children: project.description })) : null, viewMode === 'list' && (_jsxs(Tabs, { value: groupBy, onValueChange: (v) => setGroupBy(v), "data-testid": "work-items-tabs", children: [_jsxs(TabsList, { className: "h-7", children: [_jsx(TabsTrigger, { value: "all", className: "px-2.5 text-xs", children: "All" }), _jsx(TabsTrigger, { value: "state", className: "px-2.5 text-xs", children: "By State" }), _jsx(TabsTrigger, { value: "priority", className: "px-2.5 text-xs", children: "By Priority" })] }), _jsx(TabsContent, { value: groupBy, className: "mt-3", children: workItems.length === 0 ? (_jsxs("div", { "data-testid": "work-items-empty", className: "text-muted-foreground flex flex-col items-center justify-center py-12 text-center", children: [_jsx(FolderKanban, { className: "mb-2 h-6 w-6 opacity-20" }), _jsx("p", { className: "text-xs", children: "No work items yet. Create your first work item." })] })) : (_jsx("div", { className: "space-y-4", children: grouped.map(({ label, items }) => (_jsxs("div", { "data-testid": `work-item-group-${label}`, children: [groupBy !== 'all' && (_jsxs("div", { className: "mb-2 flex items-center gap-2", children: [_jsx("span", { className: "text-xs font-medium", children: label }), _jsx("span", { className: "text-muted-foreground text-[10px]", children: items.length })] })), _jsx("div", { className: "divide-y rounded-lg border", children: items.map((wi) => (_jsx(WorkItemRow, { workItem: wi, state: stateMap.get(wi.stateId), projectPrefix: project.identifierPrefix }, wi.id))) })] }, label))) })) })] })), viewMode === 'board' && (_jsx(BoardView, { workItems: workItems, states: states, projectPrefix: project.identifierPrefix, onWorkItemUpdate: handleWorkItemUpdate, onCardClick: handleCardClick })), viewMode === 'table' && (_jsx(TableView, { workItems: workItems, states: states, labels: labels, projectPrefix: project.identifierPrefix, onWorkItemUpdate: handleWorkItemUpdate })), viewMode === 'calendar' && (_jsx(CalendarView, { workItems: workItems, states: states, projectPrefix: project.identifierPrefix, onWorkItemUpdate: handleWorkItemUpdate, onItemClick: handleCardClick })), viewMode === 'timeline' && (_jsx(TimelineViewWrapper, { projectId: project.id, workItems: workItems, states: states, projectPrefix: project.identifierPrefix, onItemClick: handleCardClick })), viewMode === 'analytics' && (_jsxs("div", { className: "space-y-6", children: [_jsxs("div", { className: "grid gap-6 md:grid-cols-2", children: [_jsx(CyclePanel, { projectId: project.id, cycles: cycles, onCyclesChange: setCycles }), _jsx(ModulePanel, { projectId: project.id, modules: modules, onModulesChange: setModules })] }), _jsx(EpicPanel, { projectId: project.id, epics: epics, onEpicsChange: setEpics }), _jsx(AnalyticsDashboard, { projectId: project.id, cycles: cycles }), _jsx(EstimateSettings, { projectId: project.id, currentEstimateType: project.estimateType })] })), _jsx(CreateWorkItemDialog, { open: showCreateDialog, onOpenChange: setShowCreateDialog, projectId: project.id, states: states, onCreated: handleWorkItemCreated })] }));
}
