'use client';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useState, useEffect, useCallback } from 'react';
import { Link2, X, Plus, Loader2 } from 'lucide-react';
import { cn } from '../../../lib/utils.js';
import { Button } from '../../ui/button.js';
import { Badge } from '../../ui/badge.js';
import { RelationType } from '../../../../../../packages/core/src/domain/generated/output.js';
import { listWorkItemRelations } from '../../../app/actions/list-work-item-relations.js';
import { deleteWorkItemRelation } from '../../../app/actions/delete-work-item-relation.js';
import { AddRelationDialog } from './add-relation-dialog.js';
const RELATION_TYPE_LABELS = {
    [RelationType.Blocking]: 'Blocking',
    [RelationType.RelatesTo]: 'Relates to',
    [RelationType.Duplicate]: 'Duplicate of',
    [RelationType.StartsBefore]: 'Starts before',
    [RelationType.FinishesBefore]: 'Finishes before',
};
export function WorkItemRelationsPanel({ workItemId, workItemsMap, projectPrefix, initialRelations, className, }) {
    const [relations, setRelations] = useState(initialRelations ?? []);
    const [loading, setLoading] = useState(!initialRelations);
    const [error, setError] = useState(null);
    const [showAddDialog, setShowAddDialog] = useState(false);
    const [deletingId, setDeletingId] = useState(null);
    const fetchRelations = useCallback(async () => {
        setLoading(true);
        setError(null);
        const result = await listWorkItemRelations(workItemId);
        if (result.error) {
            setError(result.error);
        }
        else if (result.relations) {
            setRelations(result.relations);
        }
        setLoading(false);
    }, [workItemId]);
    useEffect(() => {
        if (!initialRelations) {
            void fetchRelations();
        }
    }, [fetchRelations, initialRelations]);
    const handleDelete = async (relationId) => {
        setDeletingId(relationId);
        const result = await deleteWorkItemRelation(relationId);
        if (result.error) {
            setError(result.error);
        }
        else {
            setRelations((prev) => prev.filter((r) => r.id !== relationId));
        }
        setDeletingId(null);
    };
    const handleRelationCreated = (relation) => {
        setRelations((prev) => [...prev, relation]);
        setShowAddDialog(false);
    };
    const grouped = groupRelationsByType(relations);
    const getLinkedItemIdentifier = (relation) => {
        const linkedId = relation.sourceWorkItemId === workItemId
            ? relation.targetWorkItemId
            : relation.sourceWorkItemId;
        const item = workItemsMap.get(linkedId);
        if (item) {
            return `${projectPrefix}-${item.sequenceId}`;
        }
        return linkedId.substring(0, 8);
    };
    const getLinkedItemTitle = (relation) => {
        const linkedId = relation.sourceWorkItemId === workItemId
            ? relation.targetWorkItemId
            : relation.sourceWorkItemId;
        const item = workItemsMap.get(linkedId);
        return item?.title ?? 'Unknown item';
    };
    return (_jsxs("div", { "data-testid": "work-item-relations-panel", className: cn('space-y-3', className), children: [_jsxs("div", { className: "flex items-center justify-between", children: [_jsxs("div", { className: "flex items-center gap-1.5", children: [_jsx(Link2, { className: "text-muted-foreground h-3.5 w-3.5" }), _jsx("span", { className: "text-xs font-medium", children: "Relations" }), relations.length > 0 && (_jsx("span", { className: "text-muted-foreground text-[10px]", children: relations.length }))] }), _jsxs(Button, { variant: "ghost", size: "sm", className: "h-6 px-1.5 text-[10px]", onClick: () => setShowAddDialog(true), "data-testid": "add-relation-btn", children: [_jsx(Plus, { className: "mr-0.5 h-3 w-3" }), "Add"] })] }), loading ? (_jsx("div", { className: "flex items-center justify-center py-4", "data-testid": "relations-loading", children: _jsx(Loader2, { className: "text-muted-foreground h-4 w-4 animate-spin" }) })) : null, error ? (_jsx("p", { className: "text-destructive text-[10px]", "data-testid": "relations-error", children: error })) : null, !loading && relations.length === 0 && !error && (_jsx("p", { className: "text-muted-foreground py-2 text-center text-[10px]", "data-testid": "relations-empty", children: "No relations yet." })), !loading && grouped.length > 0 && (_jsx("div", { className: "space-y-2", "data-testid": "relations-list", children: grouped.map(({ type, items }) => (_jsxs("div", { "data-testid": `relation-group-${type}`, children: [_jsx("span", { className: "text-muted-foreground mb-1 block text-[10px] font-medium", children: RELATION_TYPE_LABELS[type] ?? type }), _jsx("div", { className: "space-y-1", children: items.map((relation) => (_jsxs("div", { "data-testid": `relation-item-${relation.id}`, className: "hover:bg-accent/50 flex items-center gap-2 rounded px-2 py-1 transition-colors", children: [_jsx(Badge, { variant: "outline", className: "shrink-0 font-mono text-[10px]", children: getLinkedItemIdentifier(relation) }), _jsx("span", { className: "min-w-0 flex-1 truncate text-[11px]", children: getLinkedItemTitle(relation) }), _jsx(Button, { variant: "ghost", size: "sm", className: "h-5 w-5 shrink-0 p-0", onClick: () => handleDelete(relation.id), disabled: deletingId === relation.id, "data-testid": `delete-relation-${relation.id}`, children: deletingId === relation.id ? (_jsx(Loader2, { className: "h-3 w-3 animate-spin" })) : (_jsx(X, { className: "h-3 w-3" })) })] }, relation.id))) })] }, type))) })), _jsx(AddRelationDialog, { open: showAddDialog, onOpenChange: setShowAddDialog, sourceWorkItemId: workItemId, onCreated: handleRelationCreated })] }));
}
function groupRelationsByType(relations) {
    const map = new Map();
    for (const relation of relations) {
        const arr = map.get(relation.relationType) ?? [];
        arr.push(relation);
        map.set(relation.relationType, arr);
    }
    return Array.from(map.entries()).map(([type, items]) => ({ type, items }));
}
