"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CostTracker = void 0;
const jsx_runtime_1 = require("react/jsx-runtime");
const react_1 = require("react");
const Card_1 = require("../common/Card");
const Button_1 = require("../forms/Button");
const Select_1 = require("../forms/Select");
const CostTracker = ({ timeRange = 'month', groupBy = 'provider', showProjections = true, showBudgetAlerts = true, budget = 100, refreshInterval = 60000, onBudgetExceeded, }) => {
    const [costData, setCostData] = (0, react_1.useState)([]);
    const [totalCost, setTotalCost] = (0, react_1.useState)(0);
    const [projection, setProjection] = (0, react_1.useState)(0);
    const [isLoading, setIsLoading] = (0, react_1.useState)(true);
    (0, react_1.useEffect)(() => {
        const fetchCostData = async () => {
            setIsLoading(true);
            try {
                // Mock data - replace with actual API call
                const mockData = [
                    {
                        provider: 'OpenAI',
                        model: 'GPT-4',
                        inputCost: 15.50,
                        outputCost: 31.00,
                        totalCost: 46.50,
                        tokenCount: 1550000,
                        requestCount: 523,
                        date: new Date('2024-01-15'),
                    },
                    {
                        provider: 'OpenAI',
                        model: 'GPT-3.5 Turbo',
                        inputCost: 2.40,
                        outputCost: 3.60,
                        totalCost: 6.00,
                        tokenCount: 3000000,
                        requestCount: 1523,
                        date: new Date('2024-01-14'),
                    },
                    {
                        provider: 'Anthropic',
                        model: 'Claude 3 Opus',
                        inputCost: 12.00,
                        outputCost: 18.00,
                        totalCost: 30.00,
                        tokenCount: 400000,
                        requestCount: 234,
                        date: new Date('2024-01-13'),
                    },
                    {
                        provider: 'Apple',
                        model: 'Apple Intelligence',
                        inputCost: 0,
                        outputCost: 0,
                        totalCost: 0,
                        tokenCount: 100000,
                        requestCount: 456,
                        date: new Date('2024-01-12'),
                    },
                ];
                setCostData(mockData);
                const total = mockData.reduce((sum, item) => sum + item.totalCost, 0);
                setTotalCost(total);
                // Calculate projection based on current usage
                const daysInPeriod = timeRange === 'month' ? 30 : timeRange === 'week' ? 7 : 1;
                const avgDailyCost = total / Math.min(daysInPeriod, 15); // Mock: 15 days of data
                setProjection(avgDailyCost * daysInPeriod);
                if (showBudgetAlerts && budget && total > budget) {
                    onBudgetExceeded?.(total);
                }
            }
            catch (error) {
                console.error('Failed to fetch cost data:', error);
            }
            finally {
                setIsLoading(false);
            }
        };
        fetchCostData();
        if (refreshInterval > 0) {
            const interval = setInterval(fetchCostData, refreshInterval);
            return () => clearInterval(interval);
        }
    }, [timeRange, budget, showBudgetAlerts, refreshInterval, onBudgetExceeded]);
    const formatCurrency = (amount) => {
        return new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',
        }).format(amount);
    };
    const groupCostData = () => {
        const grouped = {};
        costData.forEach((item) => {
            let key;
            switch (groupBy) {
                case 'provider':
                    key = item.provider;
                    break;
                case 'model':
                    key = `${item.provider} - ${item.model}`;
                    break;
                case 'day':
                    key = item.date.toLocaleDateString();
                    break;
                case 'hour':
                    key = `${item.date.toLocaleDateString()} ${item.date.getHours()}:00`;
                    break;
                default:
                    key = item.provider;
            }
            if (!grouped[key])
                grouped[key] = [];
            grouped[key].push(item);
        });
        return grouped;
    };
    const calculateGroupTotals = (items) => {
        return items.reduce((acc, item) => ({
            inputCost: acc.inputCost + item.inputCost,
            outputCost: acc.outputCost + item.outputCost,
            totalCost: acc.totalCost + item.totalCost,
            tokenCount: acc.tokenCount + item.tokenCount,
            requestCount: acc.requestCount + item.requestCount,
        }), {
            inputCost: 0,
            outputCost: 0,
            totalCost: 0,
            tokenCount: 0,
            requestCount: 0,
        });
    };
    if (isLoading) {
        return ((0, jsx_runtime_1.jsx)(Card_1.Card, { className: "cost-tracker", children: (0, jsx_runtime_1.jsx)("div", { className: "p-6", children: (0, jsx_runtime_1.jsxs)("div", { className: "animate-pulse space-y-4", children: [(0, jsx_runtime_1.jsx)("div", { className: "h-6 bg-gray-200 rounded w-1/3" }), (0, jsx_runtime_1.jsx)("div", { className: "grid grid-cols-3 gap-4", children: [...Array(3)].map((_, i) => ((0, jsx_runtime_1.jsx)("div", { className: "h-20 bg-gray-200 rounded" }, i))) })] }) }) }));
    }
    const budgetPercentage = budget ? (totalCost / budget) * 100 : 0;
    const isOverBudget = budgetPercentage > 100;
    return ((0, jsx_runtime_1.jsx)(Card_1.Card, { className: "cost-tracker", children: (0, jsx_runtime_1.jsxs)("div", { className: "p-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex justify-between items-center mb-6", children: [(0, jsx_runtime_1.jsx)("h3", { className: "text-lg font-semibold", children: "Cost Tracker" }), (0, jsx_runtime_1.jsxs)(Select_1.Select, { value: timeRange, className: "w-32", children: [(0, jsx_runtime_1.jsx)("option", { value: "today", children: "Today" }), (0, jsx_runtime_1.jsx)("option", { value: "week", children: "This Week" }), (0, jsx_runtime_1.jsx)("option", { value: "month", children: "This Month" }), (0, jsx_runtime_1.jsx)("option", { value: "year", children: "This Year" })] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "grid grid-cols-1 md:grid-cols-3 gap-4 mb-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "bg-blue-50 rounded-lg p-4", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-sm text-blue-600 font-medium", children: "Total Cost" }), (0, jsx_runtime_1.jsx)("div", { className: "text-2xl font-bold text-blue-900", children: formatCurrency(totalCost) }), (0, jsx_runtime_1.jsxs)("div", { className: "text-xs text-blue-600 mt-1", children: [costData.reduce((sum, item) => sum + item.requestCount, 0).toLocaleString(), " requests"] })] }), showProjections && ((0, jsx_runtime_1.jsxs)("div", { className: "bg-purple-50 rounded-lg p-4", children: [(0, jsx_runtime_1.jsx)("div", { className: "text-sm text-purple-600 font-medium", children: "Projected Cost" }), (0, jsx_runtime_1.jsx)("div", { className: "text-2xl font-bold text-purple-900", children: formatCurrency(projection) }), (0, jsx_runtime_1.jsxs)("div", { className: "text-xs text-purple-600 mt-1", children: ["End of ", timeRange] })] })), showBudgetAlerts && budget && ((0, jsx_runtime_1.jsxs)("div", { className: `rounded-lg p-4 ${isOverBudget ? 'bg-red-50' : 'bg-green-50'}`, children: [(0, jsx_runtime_1.jsx)("div", { className: `text-sm font-medium ${isOverBudget ? 'text-red-600' : 'text-green-600'}`, children: "Budget Status" }), (0, jsx_runtime_1.jsxs)("div", { className: `text-2xl font-bold ${isOverBudget ? 'text-red-900' : 'text-green-900'}`, children: [budgetPercentage.toFixed(1), "%"] }), (0, jsx_runtime_1.jsxs)("div", { className: `text-xs mt-1 ${isOverBudget ? 'text-red-600' : 'text-green-600'}`, children: ["of ", formatCurrency(budget)] })] }))] }), showBudgetAlerts && budget && ((0, jsx_runtime_1.jsxs)("div", { className: "mb-6", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex justify-between text-sm text-gray-600 mb-2", children: [(0, jsx_runtime_1.jsx)("span", { children: "Budget Usage" }), (0, jsx_runtime_1.jsxs)("span", { children: [formatCurrency(totalCost), " / ", formatCurrency(budget)] })] }), (0, jsx_runtime_1.jsx)("div", { className: "w-full bg-gray-200 rounded-full h-3", children: (0, jsx_runtime_1.jsx)("div", { className: `h-3 rounded-full transition-all ${isOverBudget ? 'bg-red-500' : budgetPercentage > 80 ? 'bg-yellow-500' : 'bg-green-500'}`, style: { width: `${Math.min(budgetPercentage, 100)}%` } }) })] })), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsxs)("h4", { className: "font-medium text-gray-900 mb-4", children: ["Cost Breakdown by ", groupBy.charAt(0).toUpperCase() + groupBy.slice(1)] }), (0, jsx_runtime_1.jsx)("div", { className: "space-y-3", children: Object.entries(groupCostData()).map(([key, items]) => {
                                const totals = calculateGroupTotals(items);
                                return ((0, jsx_runtime_1.jsxs)("div", { className: "border rounded-lg p-4", children: [(0, jsx_runtime_1.jsxs)("div", { className: "flex justify-between items-center mb-2", children: [(0, jsx_runtime_1.jsx)("h5", { className: "font-medium text-gray-900", children: key }), (0, jsx_runtime_1.jsx)("span", { className: "text-lg font-bold", children: formatCurrency(totals.totalCost) })] }), (0, jsx_runtime_1.jsxs)("div", { className: "grid grid-cols-2 md:grid-cols-4 gap-4 text-sm", children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("span", { className: "text-gray-600", children: "Input Cost:" }), (0, jsx_runtime_1.jsx)("span", { className: "ml-2 font-medium", children: formatCurrency(totals.inputCost) })] }), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("span", { className: "text-gray-600", children: "Output Cost:" }), (0, jsx_runtime_1.jsx)("span", { className: "ml-2 font-medium", children: formatCurrency(totals.outputCost) })] }), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("span", { className: "text-gray-600", children: "Tokens:" }), (0, jsx_runtime_1.jsx)("span", { className: "ml-2 font-medium", children: totals.tokenCount.toLocaleString() })] }), (0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)("span", { className: "text-gray-600", children: "Requests:" }), (0, jsx_runtime_1.jsx)("span", { className: "ml-2 font-medium", children: totals.requestCount.toLocaleString() })] })] }), (0, jsx_runtime_1.jsxs)("div", { className: "mt-3 flex h-2 rounded-full overflow-hidden", children: [(0, jsx_runtime_1.jsx)("div", { className: "bg-blue-500", style: { width: `${(totals.inputCost / totals.totalCost) * 100}%` } }), (0, jsx_runtime_1.jsx)("div", { className: "bg-green-500", style: { width: `${(totals.outputCost / totals.totalCost) * 100}%` } })] })] }, key));
                            }) })] }), (0, jsx_runtime_1.jsx)("div", { className: "mt-6 flex justify-end", children: (0, jsx_runtime_1.jsx)(Button_1.Button, { variant: "outline", size: "sm", children: "Export Cost Report" }) })] }) }));
};
exports.CostTracker = CostTracker;
exports.default = exports.CostTracker;
//# sourceMappingURL=CostTracker.js.map