import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import React from 'react';
import { useTheme } from '../theme';
export const ToolCallCard = ({ toolCall, index, context, expanded, onToggleExpansion, formatStatusLabel, summarizeValue, pendingInterruption, onApproveInterruption, onDenyInterruption }) => {
    const theme = useTheme();
    const cardId = toolCall.id?.length ? toolCall.id : `${context}-${toolCall.name}-${index}`;
    const statusLabel = formatStatusLabel(toolCall.status);
    const lastUpdated = toolCall.updatedAt ? new Date(toolCall.updatedAt).toLocaleTimeString() : null;
    const summaryArgs = summarizeValue(toolCall.args);
    const summaryOutput = summarizeValue(toolCall.output);
    const hasError = Boolean(toolCall.error);
    const hasDetails = Boolean(toolCall.args || toolCall.output || toolCall.error);
    const palette = React.useMemo(() => {
        const base = theme.toolCallCard.base;
        const variant = hasError
            ? theme.toolCallCard.error
            : (context === 'stream' ? theme.toolCallCard.stream : {});
        return {
            ...base,
            ...variant
        };
    }, [context, hasError, theme.toolCallCard.base, theme.toolCallCard.error, theme.toolCallCard.stream]);
    const [actionState, setActionState] = React.useState('idle');
    const [actionError, setActionError] = React.useState(null);
    const interruptionStatus = pendingInterruption?.status;
    const isPendingApproval = interruptionStatus === 'pending';
    const isApproving = actionState === 'approving';
    const isDenying = actionState === 'denying';
    React.useEffect(() => {
        if (!isPendingApproval) {
            setActionState('idle');
            setActionError(null);
        }
    }, [isPendingApproval]);
    const handleApprove = React.useCallback(async () => {
        if (!pendingInterruption || !isPendingApproval || !onApproveInterruption) {
            return;
        }
        setActionError(null);
        setActionState('approving');
        try {
            await onApproveInterruption(pendingInterruption.id);
        }
        catch (error) {
            console.error('Failed to approve tool permission request', error);
            setActionError(error instanceof Error ? error.message : 'Failed to approve request.');
        }
        finally {
            setActionState('idle');
        }
    }, [isPendingApproval, onApproveInterruption, pendingInterruption]);
    const handleDeny = React.useCallback(async () => {
        if (!pendingInterruption || !isPendingApproval || !onDenyInterruption) {
            return;
        }
        setActionError(null);
        setActionState('denying');
        try {
            await onDenyInterruption(pendingInterruption.id);
        }
        catch (error) {
            console.error('Failed to deny tool permission request', error);
            setActionError(error instanceof Error ? error.message : 'Failed to deny request.');
        }
        finally {
            setActionState('idle');
        }
    }, [isPendingApproval, onDenyInterruption, pendingInterruption]);
    const approvalTitle = React.useMemo(() => {
        if (!pendingInterruption) {
            return null;
        }
        if (isPendingApproval) {
            return 'Tool permission required';
        }
        if (interruptionStatus === 'approved') {
            return 'Permission granted';
        }
        if (interruptionStatus === 'rejected') {
            return 'Permission denied';
        }
        return null;
    }, [interruptionStatus, isPendingApproval, pendingInterruption]);
    const approvalBody = React.useMemo(() => {
        if (!pendingInterruption) {
            return null;
        }
        if (pendingInterruption.message && pendingInterruption.message.trim().length > 0) {
            return pendingInterruption.message.trim();
        }
        if (isPendingApproval) {
            return 'The assistant needs your approval to continue with this tool call.';
        }
        if (interruptionStatus === 'approved') {
            return 'You approved this tool call. The assistant will continue.';
        }
        if (interruptionStatus === 'rejected') {
            return 'You denied this tool call. The assistant will respond without running it.';
        }
        return null;
    }, [interruptionStatus, isPendingApproval, pendingInterruption]);
    return (_jsxs("div", { className: palette.container, children: [_jsx("button", { type: 'button', onClick: () => hasDetails && onToggleExpansion(cardId), className: `${palette.button} ${hasDetails ? `cursor-pointer ${palette.buttonHover}` : palette.buttonDisabled}`, "aria-expanded": expanded, "aria-controls": `${cardId}-details`, disabled: !hasDetails, children: _jsxs("div", { className: 'flex flex-wrap items-center justify-between gap-1 sm:gap-2', children: [_jsxs("div", { className: 'flex items-center gap-1 sm:gap-2', children: [_jsx("span", { className: `text-xs font-semibold ${palette.name}`, children: toolCall.name }), context === 'stream' && !toolCall.completedAt && (_jsx("span", { className: palette.livePill, children: "Live" })), hasError && (_jsx("span", { className: palette.errorBadge, children: "Error" }))] }), _jsxs("div", { className: `flex flex-wrap items-center gap-1 text-[9px] font-medium uppercase tracking-wide ${palette.meta}`, children: [_jsx("span", { className: `rounded-full px-1.5 py-0.5 ${palette.statusPill}`, children: statusLabel }), lastUpdated && _jsxs("span", { className: 'normal-case', children: ["Updated ", lastUpdated] }), hasDetails && (_jsx("span", { className: `${palette.toggle} normal-case`, children: expanded ? 'Hide details' : 'Show details' }))] })] }) }), pendingInterruption && approvalTitle && (_jsxs("div", { className: palette.approvalCallout, role: 'status', "aria-live": 'polite', children: [_jsx("p", { className: palette.approvalTitle, children: approvalTitle }), approvalBody ? (_jsx("p", { className: palette.approvalBody, children: approvalBody })) : null, isPendingApproval ? (_jsxs("div", { className: palette.approvalActions, children: [_jsx("button", { type: 'button', onClick: handleApprove, className: palette.approvalApproveButton, disabled: isApproving || !onApproveInterruption, children: isApproving ? 'Approving…' : 'Approve' }), _jsx("button", { type: 'button', onClick: handleDeny, className: palette.approvalDenyButton, disabled: isDenying || !onDenyInterruption, children: isDenying ? 'Denying…' : 'Deny' })] })) : (_jsx("p", { className: palette.approvalStatus, children: interruptionStatus === 'approved' ? 'Approved' : 'Denied' })), actionError ? (_jsx("p", { className: palette.approvalError, role: 'alert', children: actionError })) : null] })), hasDetails && expanded && (_jsxs("div", { id: `${cardId}-details`, className: palette.detailContainer, children: [summaryArgs && (_jsxs("p", { className: `mb-1 text-[11px] break-words ${palette.summaryText}`, children: [_jsx("span", { className: `font-semibold ${palette.summaryLabel}`, children: "Args:" }), " ", summaryArgs] })), summaryOutput && (_jsxs("p", { className: `mb-2 text-[11px] break-words ${palette.summaryText}`, children: [_jsx("span", { className: `font-semibold ${palette.summaryLabel}`, children: "Output:" }), " ", summaryOutput] })), toolCall.args && (_jsxs("div", { children: [_jsx("p", { className: palette.detailHeading, children: "Arguments" }), _jsx("pre", { className: palette.detailPre, children: toolCall.args })] })), toolCall.output && (_jsxs("div", { children: [_jsx("p", { className: palette.detailHeading, children: "Output" }), _jsx("pre", { className: palette.detailPre, children: toolCall.output })] })), toolCall.error && (_jsxs("div", { children: [_jsx("p", { className: 'text-[11px] font-semibold uppercase tracking-wide text-rose-600', children: "Error" }), _jsx("pre", { className: palette.errorPre, children: toolCall.error })] }))] }))] }));
};
