import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import { ExternalLink, Link2, Search, Filter } from 'lucide-react';
import { formatDuration } from './utils';
import { ToolErrorDisplay } from './ToolErrorDisplay';
import { ToolHeader, ToolHeaderSeparator, ToolHeaderMeta, ToolHeaderSuccess, ToolHeaderError, ToolContentBox, } from './shared';
function formatDate(timestamp) {
    if (!timestamp)
        return '';
    const date = new Date(timestamp);
    return date.toLocaleDateString(undefined, {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
    });
}
function SessionLink({ session, onNavigate, compact, }) {
    if (compact) {
        return (_jsxs("button", { type: "button", onClick: () => onNavigate?.(session.id), disabled: !onNavigate, className: "w-full text-left py-1 px-2 rounded text-xs hover:bg-muted/50 transition-colors flex items-center justify-between gap-2", children: [_jsx("span", { className: "truncate text-foreground", children: session.title || 'Untitled' }), onNavigate && (_jsx(ExternalLink, { className: "w-3 h-3 text-muted-foreground flex-shrink-0" }))] }));
    }
    return (_jsxs("button", { type: "button", onClick: () => onNavigate?.(session.id), disabled: !onNavigate, className: "w-full text-left p-2 rounded-md border border-border hover:bg-muted/50 transition-colors group", children: [_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("span", { className: "font-medium text-sm truncate text-foreground", children: session.title || 'Untitled' }), onNavigate && (_jsx(ExternalLink, { className: "w-3 h-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" }))] }), _jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground mt-1", children: [session.agent && (_jsx("span", { className: "text-violet-600 dark:text-violet-400", children: session.agent })), session.agent && session.provider && _jsx("span", { children: "\u00B7" }), session.provider && _jsx("span", { children: session.provider }), session.messageCount !== undefined && (_jsxs(_Fragment, { children: [_jsx("span", { children: "\u00B7" }), _jsxs("span", { children: [session.messageCount, " msgs"] })] })), session.createdAt && (_jsxs(_Fragment, { children: [_jsx("span", { children: "\u00B7" }), _jsx("span", { children: formatDate(session.createdAt) })] }))] })] }));
}
function MessageLink({ message, onNavigate, compact, }) {
    const sessionId = 'sessionId' in message ? message.sessionId : '';
    const sessionTitle = 'sessionTitle' in message ? message.sessionTitle : null;
    const content = 'content' in message
        ? message.content
        : 'contentPreview' in message
            ? message.contentPreview
            : 'matchedContent' in message
                ? message.matchedContent
                : '';
    if (compact) {
        return (_jsxs("button", { type: "button", onClick: () => onNavigate?.(sessionId), disabled: !onNavigate || !sessionId, className: "w-full text-left py-1 px-2 rounded text-xs hover:bg-muted/50 transition-colors flex items-center justify-between gap-2", children: [_jsx("span", { className: "truncate text-foreground/80", children: content?.slice(0, 50) || sessionTitle || sessionId.slice(0, 8) }), onNavigate && sessionId && (_jsx(ExternalLink, { className: "w-3 h-3 text-muted-foreground flex-shrink-0" }))] }));
    }
    return (_jsxs("button", { type: "button", onClick: () => onNavigate?.(sessionId), disabled: !onNavigate || !sessionId, className: "w-full text-left p-2 rounded-md border border-border hover:bg-muted/50 transition-colors group", children: [_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("span", { className: "text-xs text-muted-foreground", children: sessionTitle || sessionId.slice(0, 8) }), onNavigate && sessionId && (_jsx(ExternalLink, { className: "w-3 h-3 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" }))] }), content && (_jsx("div", { className: "text-xs text-foreground/80 mt-1 line-clamp-2", children: content })), _jsxs("div", { className: "flex items-center gap-2 text-xs text-muted-foreground mt-1", children: [message.role && _jsx("span", { className: "capitalize", children: message.role }), message.createdAt && (_jsxs(_Fragment, { children: [_jsx("span", { children: "\u00B7" }), _jsx("span", { children: formatDate(message.createdAt) })] }))] })] }));
}
function ArgsPreview({ args, toolName, }) {
    const renderArg = (key, value) => {
        if (value === undefined || value === null)
            return null;
        if (typeof value === 'boolean' && !value)
            return null;
        if (Array.isArray(value) && value.length === 0)
            return null;
        return (_jsxs("span", { className: "inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-muted text-muted-foreground", children: [_jsxs("span", { className: "opacity-60", children: [key, ":"] }), _jsx("span", { className: "text-foreground/80", children: typeof value === 'string' ? value : JSON.stringify(value) })] }, key));
    };
    const importantArgs = {
        query_sessions: ['agent', 'sessionType', 'startDate', 'endDate'],
        query_messages: ['sessionId', 'role', 'search', 'toolName'],
        search_history: ['query'],
        get_session_context: ['sessionId', 'includeMessages'],
        get_parent_session: ['includeMessages'],
    };
    const keysToShow = importantArgs[toolName] || Object.keys(args).slice(0, 3);
    const argsToRender = keysToShow
        .filter((k) => args[k] !== undefined && args[k] !== null)
        .map((k) => renderArg(k, args[k]))
        .filter(Boolean);
    if (argsToRender.length === 0)
        return null;
    return (_jsxs("div", { className: "flex items-center gap-1.5 flex-wrap text-xs mb-2 pb-2 border-b border-border", children: [_jsx(Filter, { className: "w-3 h-3 text-muted-foreground flex-shrink-0" }), argsToRender] }));
}
export function DatabaseToolRenderer({ toolName, contentJson, toolDurationMs, isExpanded, onToggle, onNavigateToSession, compact, }) {
    const result = contentJson.result || {};
    const args = (contentJson.args || {});
    const hasToolError = typeof result === 'object' && 'ok' in result && result.ok === false;
    const errorMessage = hasToolError && 'error' in result && typeof result.error === 'string'
        ? result.error
        : null;
    const timeStr = formatDuration(toolDurationMs);
    if (toolName === 'present_action') {
        const links = result.links || [];
        const summary = result.summary;
        const title = result.title;
        if (links.length === 0 && !summary)
            return null;
        return (_jsxs("div", { className: "mt-2 mb-1", children: [title && (_jsx("div", { className: "text-sm font-medium text-foreground mb-1.5", children: title })), summary && (_jsxs("div", { className: "text-xs text-muted-foreground mb-2 flex items-center gap-1.5", children: [_jsx(Link2, { className: "w-3.5 h-3.5 text-teal-500" }), _jsx("span", { children: summary })] })), links.length > 0 && (_jsx("div", { className: "space-y-1.5", children: links.map((link) => (_jsxs("button", { type: "button", onClick: () => onNavigateToSession?.(link.sessionId), disabled: !onNavigateToSession, className: "w-full text-left px-3 py-2 rounded-lg border border-teal-500/30 bg-teal-500/5 hover:bg-teal-500/10 transition-colors group flex items-center justify-between gap-2", children: [_jsxs("div", { children: [_jsx("div", { className: "font-medium text-sm text-foreground", children: link.title }), link.description && (_jsx("div", { className: "text-xs text-muted-foreground mt-0.5", children: link.description }))] }), onNavigateToSession && (_jsx(ExternalLink, { className: "w-4 h-4 text-teal-600 dark:text-teal-400 opacity-60 group-hover:opacity-100 transition-opacity flex-shrink-0" }))] }, link.sessionId))) }))] }));
    }
    const getDescription = () => {
        switch (toolName) {
            case 'query_sessions': {
                const sessions = result.sessions || [];
                const total = result.total;
                return `${sessions.length} session${sessions.length !== 1 ? 's' : ''}${total ? ` of ${total}` : ''}`;
            }
            case 'query_messages': {
                const messages = result.messages || [];
                return `${messages.length} message${messages.length !== 1 ? 's' : ''}`;
            }
            case 'search_history': {
                const query = args.query;
                const results = result.results || [];
                const queryPreview = query
                    ? `"${query.slice(0, 20)}${query.length > 20 ? '…' : ''}"`
                    : '';
                return `${results.length} result${results.length !== 1 ? 's' : ''}${queryPreview ? ` for ${queryPreview}` : ''}`;
            }
            case 'get_session_context': {
                const session = result.session;
                return (session?.title ||
                    args.sessionId?.slice(0, 8) ||
                    'session');
            }
            case 'get_parent_session': {
                const parentSession = result
                    .parentSession;
                return parentSession?.title || 'parent session';
            }
            default:
                return toolName;
        }
    };
    const renderContent = () => {
        const hasArgs = Object.keys(args).length > 0 && !compact;
        switch (toolName) {
            case 'query_sessions': {
                const sessions = result.sessions || [];
                return (_jsxs("div", { className: compact ? 'p-1' : 'p-2', children: [hasArgs && _jsx(ArgsPreview, { args: args, toolName: toolName }), sessions.length === 0 ? (_jsx("div", { className: "text-xs text-muted-foreground", children: "No sessions found" })) : (_jsxs("div", { className: compact ? 'space-y-0.5' : 'space-y-2', children: [sessions.slice(0, compact ? 5 : 10).map((session) => (_jsx(SessionLink, { session: session, onNavigate: onNavigateToSession, compact: compact }, session.id))), sessions.length > (compact ? 5 : 10) && (_jsxs("div", { className: "text-xs text-muted-foreground text-center", children: ["+", sessions.length - (compact ? 5 : 10), " more"] }))] }))] }));
            }
            case 'query_messages': {
                const messages = result.messages || [];
                return (_jsxs("div", { className: compact ? 'p-1' : 'p-2', children: [hasArgs && _jsx(ArgsPreview, { args: args, toolName: toolName }), messages.length === 0 ? (_jsx("div", { className: "text-xs text-muted-foreground", children: "No messages found" })) : (_jsxs("div", { className: compact ? 'space-y-0.5' : 'space-y-2', children: [messages.slice(0, compact ? 5 : 10).map((msg) => (_jsx(MessageLink, { message: msg, onNavigate: onNavigateToSession, compact: compact }, msg.id))), messages.length > (compact ? 5 : 10) && (_jsxs("div", { className: "text-xs text-muted-foreground text-center", children: ["+", messages.length - (compact ? 5 : 10), " more"] }))] }))] }));
            }
            case 'search_history': {
                const results = result.results || [];
                const query = args.query;
                return (_jsxs("div", { className: compact ? 'p-1' : 'p-2', children: [query && !compact && (_jsxs("div", { className: "flex items-center gap-1.5 text-xs mb-2 pb-2 border-b border-border", children: [_jsx(Search, { className: "w-3 h-3 text-muted-foreground flex-shrink-0" }), _jsx("span", { className: "text-muted-foreground", children: "Query:" }), _jsxs("span", { className: "text-foreground font-medium", children: ["\"", query, "\""] })] })), results.length === 0 ? (_jsx("div", { className: "text-xs text-muted-foreground", children: "No results found" })) : (_jsxs("div", { className: compact ? 'space-y-0.5' : 'space-y-2', children: [results.slice(0, compact ? 5 : 10).map((r, i) => (_jsx(MessageLink, { message: r, onNavigate: onNavigateToSession, compact: compact }, `${r.sessionId}-${r.messageId}-${i}`))), results.length > (compact ? 5 : 10) && (_jsxs("div", { className: "text-xs text-muted-foreground text-center", children: ["+", results.length - (compact ? 5 : 10), " more"] }))] }))] }));
            }
            case 'get_session_context':
            case 'get_parent_session': {
                const session = toolName === 'get_parent_session'
                    ? result.parentSession
                    : result.session;
                const stats = result.stats;
                const messages = result.messages;
                if (!session) {
                    return (_jsx("div", { className: `text-xs text-muted-foreground ${compact ? 'p-1' : 'p-2'}`, children: "Session not found" }));
                }
                if (compact) {
                    return (_jsx("div", { className: "p-1", children: _jsx(SessionLink, { session: session, onNavigate: onNavigateToSession, compact: true }) }));
                }
                return (_jsxs("div", { className: "p-2 space-y-3", children: [_jsx(SessionLink, { session: session, onNavigate: onNavigateToSession }), stats && (_jsxs("div", { className: "flex gap-4 text-xs text-muted-foreground", children: [stats.totalMessages !== undefined && (_jsxs("span", { children: [stats.totalMessages, " messages"] })), stats.totalToolCalls !== undefined && (_jsxs("span", { children: [stats.totalToolCalls, " tool calls"] }))] })), messages && messages.length > 0 && (_jsxs("div", { className: "space-y-1", children: [_jsx("div", { className: "text-xs font-medium text-muted-foreground", children: "Recent messages:" }), _jsx("div", { className: "space-y-1 max-h-48 overflow-y-auto", children: messages.slice(0, 5).map((msg) => (_jsxs("div", { className: "text-xs p-1.5 rounded bg-muted/30", children: [_jsxs("span", { className: "font-medium capitalize text-foreground/70", children: [msg.role, ":", ' '] }), _jsx("span", { className: "text-foreground/60 line-clamp-2", children: msg.content })] }, msg.id))) })] }))] }));
            }
            default:
                return (_jsx("pre", { className: "text-xs p-2 overflow-auto max-h-48", children: JSON.stringify(result, null, 2) }));
        }
    };
    return (_jsxs("div", { className: "text-xs", children: [_jsxs(ToolHeader, { toolName: toolName, isExpanded: isExpanded, onToggle: onToggle, isError: hasToolError, colorVariant: "default", canExpand: true, children: [!compact && (_jsxs(_Fragment, { children: [_jsx(ToolHeaderSeparator, {}), _jsx("span", { className: "text-foreground/70 min-w-0 truncate", children: getDescription() })] })), !hasToolError && !compact && (_jsxs(_Fragment, { children: [_jsx(ToolHeaderSeparator, {}), _jsx(ToolHeaderSuccess, { children: "Done" }), _jsx(ToolHeaderSeparator, {}), _jsx(ToolHeaderMeta, { children: timeStr })] })), hasToolError && !compact && (_jsxs(_Fragment, { children: [_jsx(ToolHeaderSeparator, {}), _jsx(ToolHeaderError, { children: "Error" }), _jsxs(ToolHeaderMeta, { children: ["\u00B7 ", timeStr] })] }))] }), isExpanded && hasToolError && errorMessage && (_jsx(ToolErrorDisplay, { error: errorMessage })), isExpanded && !hasToolError && (_jsx("div", { className: compact ? 'mt-1 ml-3' : 'mt-2 ml-5', children: compact ? (_jsx("div", { className: "border border-border rounded-md overflow-hidden max-h-48 overflow-y-auto", children: renderContent() })) : (_jsx(ToolContentBox, { title: "results", maxHeight: "max-h-96", children: renderContent() })) }))] }));
}
//# sourceMappingURL=DatabaseToolRenderer.js.map