/**
 * Tools View
 *
 * Tool usage metrics and breakdown:
 * - Most used tools
 * - Success/error rates
 * - Execution times
 * - Recent tool activity
 */
import React, { useMemo, useState } from 'react';
import { Box, Text, useInput } from 'ink';
import { useTheme } from '../../context/theme-context.js';
import { MetricCard, MetricRow } from '../components/metric-card.js';
import { BarChart } from '../components/mini-chart.js';
/**
 * Format duration
 */
function formatDuration(ms) {
    if (ms >= 1000) {
        return `${(ms / 1000).toFixed(2)}s`;
    }
    return `${Math.round(ms)}ms`;
}
/**
 * Format time ago
 */
function formatTimeAgo(timestamp) {
    if (!timestamp)
        return 'Never';
    const seconds = Math.floor((Date.now() - timestamp) / 1000);
    if (seconds < 60)
        return `${seconds}s ago`;
    const minutes = Math.floor(seconds / 60);
    if (minutes < 60)
        return `${minutes}m ago`;
    const hours = Math.floor(minutes / 60);
    return `${hours}h ago`;
}
/**
 * Tools View Component
 */
export function ToolsView({ data }) {
    const { colors } = useTheme();
    const { state: _state, tools } = data;
    const [sortBy, setSortBy] = useState('calls');
    const [selectedIndex, setSelectedIndex] = useState(0);
    // Handle keyboard input for sorting
    useInput((input, key) => {
        if (input === 'c')
            setSortBy('calls');
        else if (input === 's')
            setSortBy('success');
        else if (input === 'd')
            setSortBy('duration');
        else if (input === 'n')
            setSortBy('name');
        else if (key.upArrow && selectedIndex > 0)
            setSelectedIndex(selectedIndex - 1);
        else if (key.downArrow && selectedIndex < tools.length - 1)
            setSelectedIndex(selectedIndex + 1);
    });
    // Sort tools
    const sortedTools = useMemo(() => {
        const sorted = [...tools];
        switch (sortBy) {
            case 'calls':
                sorted.sort((a, b) => b.totalCalls - a.totalCalls);
                break;
            case 'success':
                sorted.sort((a, b) => {
                    const aRate = a.totalCalls > 0 ? a.successCount / a.totalCalls : 0;
                    const bRate = b.totalCalls > 0 ? b.successCount / b.totalCalls : 0;
                    return bRate - aRate;
                });
                break;
            case 'duration':
                sorted.sort((a, b) => b.avgDuration - a.avgDuration);
                break;
            case 'name':
                sorted.sort((a, b) => a.name.localeCompare(b.name));
                break;
        }
        return sorted;
    }, [tools, sortBy]);
    // Calculate aggregate stats
    const stats = useMemo(() => {
        const totalCalls = tools.reduce((sum, t) => sum + t.totalCalls, 0);
        const totalSuccess = tools.reduce((sum, t) => sum + t.successCount, 0);
        const totalErrors = tools.reduce((sum, t) => sum + t.errorCount, 0);
        const avgDuration = tools.length > 0
            ? tools.reduce((sum, t) => sum + t.avgDuration, 0) / tools.length
            : 0;
        const successRate = totalCalls > 0 ? (totalSuccess / totalCalls) * 100 : 100;
        return { totalCalls, totalSuccess, totalErrors, avgDuration, successRate };
    }, [tools]);
    // Top tools for bar chart
    const topToolsData = sortedTools.slice(0, 5).map((t) => ({
        label: t.name.slice(0, 12),
        value: t.totalCalls,
        color: colors.primary,
    }));
    // Selected tool details
    const selectedTool = sortedTools[selectedIndex];
    return (React.createElement(Box, { flexDirection: "column", paddingX: 1 },
        React.createElement(Box, { marginBottom: 1 },
            React.createElement(Text, { bold: true, color: colors.primary }, "\uD83D\uDD27 Tool Analytics"),
            React.createElement(Text, { dimColor: true },
                " \u2022 ",
                tools.length,
                " tools tracked")),
        React.createElement(Box, { borderStyle: "round", borderColor: colors.border, paddingX: 1, paddingY: 0, marginBottom: 1 },
            React.createElement(Box, { flexDirection: "column" },
                React.createElement(Text, { bold: true, color: colors.info }, "Summary"),
                React.createElement(Box, { marginTop: 1 },
                    React.createElement(MetricRow, { gap: 3 },
                        React.createElement(MetricCard, { icon: "\uD83D\uDCCA", label: "Total Calls", value: stats.totalCalls.toString(), status: "neutral" }),
                        React.createElement(MetricCard, { icon: "\u2713", label: "Success Rate", value: `${stats.successRate.toFixed(1)}%`, status: stats.successRate >= 95 ? 'success' : stats.successRate >= 80 ? 'warning' : 'error' }),
                        React.createElement(MetricCard, { icon: "\u274C", label: "Errors", value: stats.totalErrors.toString(), status: stats.totalErrors === 0 ? 'success' : 'error' }),
                        React.createElement(MetricCard, { icon: "\u23F1", label: "Avg Duration", value: formatDuration(stats.avgDuration), status: "neutral" }))))),
        topToolsData.length > 0 && (React.createElement(Box, { borderStyle: "round", borderColor: colors.border, paddingX: 1, paddingY: 0, marginBottom: 1 },
            React.createElement(Box, { flexDirection: "column" },
                React.createElement(Text, { bold: true, color: colors.info }, "Most Used Tools"),
                React.createElement(Box, { marginTop: 1 },
                    React.createElement(BarChart, { data: topToolsData, maxBarWidth: 25, showValues: true, labelWidth: 14 }))))),
        React.createElement(Box, { borderStyle: "round", borderColor: colors.border, paddingX: 1, paddingY: 0, marginBottom: 1 },
            React.createElement(Box, { flexDirection: "column" },
                React.createElement(Box, { justifyContent: "space-between" },
                    React.createElement(Text, { bold: true, color: colors.info }, "Tool List"),
                    React.createElement(Box, null,
                        React.createElement(Text, { dimColor: true }, "Sort: "),
                        React.createElement(Text, { color: sortBy === 'calls' ? colors.primary : colors.textMuted }, "[c]alls "),
                        React.createElement(Text, { color: sortBy === 'success' ? colors.primary : colors.textMuted }, "[s]uccess "),
                        React.createElement(Text, { color: sortBy === 'duration' ? colors.primary : colors.textMuted }, "[d]uration "),
                        React.createElement(Text, { color: sortBy === 'name' ? colors.primary : colors.textMuted }, "[n]ame"))),
                React.createElement(Box, { marginTop: 1 },
                    React.createElement(Box, { width: 16 },
                        React.createElement(Text, { bold: true, dimColor: true }, "Tool")),
                    React.createElement(Box, { width: 8 },
                        React.createElement(Text, { bold: true, dimColor: true }, "Calls")),
                    React.createElement(Box, { width: 10 },
                        React.createElement(Text, { bold: true, dimColor: true }, "Success")),
                    React.createElement(Box, { width: 10 },
                        React.createElement(Text, { bold: true, dimColor: true }, "Avg Time")),
                    React.createElement(Box, { width: 10 },
                        React.createElement(Text, { bold: true, dimColor: true }, "Last"))),
                sortedTools.slice(0, 10).map((tool, index) => {
                    const successRate = tool.totalCalls > 0
                        ? (tool.successCount / tool.totalCalls) * 100
                        : 100;
                    const isSelected = index === selectedIndex;
                    return (React.createElement(Box, { key: tool.name },
                        React.createElement(Box, { width: 16 },
                            React.createElement(Text, { color: isSelected ? colors.primary : colors.text, bold: isSelected },
                                isSelected ? '▶ ' : '  ',
                                tool.name.slice(0, 12))),
                        React.createElement(Box, { width: 8 },
                            React.createElement(Text, null, tool.totalCalls)),
                        React.createElement(Box, { width: 10 },
                            React.createElement(Text, { color: successRate >= 95 ? colors.success : successRate >= 80 ? colors.warning : colors.error },
                                successRate.toFixed(0),
                                "%")),
                        React.createElement(Box, { width: 10 },
                            React.createElement(Text, null, formatDuration(tool.avgDuration))),
                        React.createElement(Box, { width: 10 },
                            React.createElement(Text, { dimColor: true }, formatTimeAgo(tool.lastExecuted)))));
                }),
                tools.length > 10 && (React.createElement(Text, { dimColor: true },
                    "...and ",
                    tools.length - 10,
                    " more tools")))),
        selectedTool && (React.createElement(Box, { borderStyle: "round", borderColor: colors.primary, paddingX: 1, paddingY: 0 },
            React.createElement(Box, { flexDirection: "column" },
                React.createElement(Text, { bold: true, color: colors.primary }, selectedTool.name),
                React.createElement(Box, { marginTop: 1 },
                    React.createElement(MetricRow, { gap: 2 },
                        React.createElement(Box, { flexDirection: "column" },
                            React.createElement(Text, { color: colors.textMuted }, "Calls"),
                            React.createElement(Text, { bold: true }, selectedTool.totalCalls)),
                        React.createElement(Box, { flexDirection: "column" },
                            React.createElement(Text, { color: colors.textMuted }, "Success"),
                            React.createElement(Text, { bold: true, color: colors.success }, selectedTool.successCount)),
                        React.createElement(Box, { flexDirection: "column" },
                            React.createElement(Text, { color: colors.textMuted }, "Errors"),
                            React.createElement(Text, { bold: true, color: selectedTool.errorCount > 0 ? colors.error : colors.textMuted }, selectedTool.errorCount)))),
                React.createElement(Box, { marginTop: 1 },
                    React.createElement(Text, { color: colors.textMuted }, "Duration: "),
                    React.createElement(Text, null,
                        "min ",
                        formatDuration(selectedTool.minDuration === Infinity ? 0 : selectedTool.minDuration)),
                    React.createElement(Text, { dimColor: true }, " / "),
                    React.createElement(Text, null,
                        "avg ",
                        formatDuration(selectedTool.avgDuration)),
                    React.createElement(Text, { dimColor: true }, " / "),
                    React.createElement(Text, null,
                        "max ",
                        formatDuration(selectedTool.maxDuration))))))));
}
export default ToolsView;
//# sourceMappingURL=tools-view.js.map