<template>
    <div class="metricsDashboard">
        <div class="metricsDashboard__container">
            <div class="metricsDashboard__header">
                <h1 class="metricsDashboard__title">Metrics</h1>
                <p class="metricsDashboard__subtitle">Overview of token consumption and costs. (<a
                    href="https://openai.com/api/pricing/">See OpenAI pricing</a>)</p>
            </div>

            <div class="metricsDashboard__statsGrid">
                <StatCard
                    title="Input Tokens"
                    :value="animatedValues.input_tokens"
                    colorClass="blue"
                >
                    <svg slot="icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12"></polyline></svg>
                </StatCard>

                <StatCard
                    title="Output Tokens"
                    :value="animatedValues.output_tokens"
                    colorClass="purple"
                >
                    <svg slot="icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"></polygon></svg>
                </StatCard>

                <StatCard
                    title="Total Tokens"
                    :value="animatedValues.total"
                    colorClass="indigo"
                >
                    <svg slot="icon" xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 6 13.5 15.5 8.5 10.5 1 18"></polyline><polyline points="17 6 23 6 23 12"></polyline></svg>
                </StatCard>

            </div>

            <div class="metricsDashboard__chartsGrid">
                <TokenPieChart
                    :inputTokens="actualData.input_tokens"
                    :outputTokens="actualData.output_tokens"
                    :total="actualData.total"
                />

                <TokenLineChart :data="historicalData" />
            </div>
        </div>
    </div>
</template>

<script>


import TokenPieChart from "./elements/metrics/TokenPieChart.vue";
import StatCard from "./elements/metrics/StatCard.vue";
import TokenLineChart from "./elements/metrics/TokenLineChart.vue";

export default {
    components: {TokenLineChart, StatCard, TokenPieChart},
    data() {
        return {
            actualData: { input_tokens: 0, output_tokens: 0, total: 0, cost: 0 },
            animatedValues: { input_tokens: 0, output_tokens: 0, total: 0, cost: "0.00" },
            historicalData: []
        };
    },
    mounted() {
        this.fetchMetrics();
    },
    methods: {
        async refresh() {
            return this.fetchMetrics();
        },
        async fetchMetrics() {
            try {
                const csrfToken = document.querySelector('meta[name="csrf-token"]');
                const response = await fetch('/admin/agent/token-usage', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': csrfToken ? csrfToken.getAttribute('content') : '',
                    },
                    body: JSON.stringify({ date: new Date().toISOString().split('T')[0] }),
                    credentials: 'same-origin'
                });
                const data = await response.json();

                // Set data for Pie Chart and Stat Calculation
                this.actualData = {
                    input_tokens: data.input_tokens,
                    output_tokens: data.output_tokens,
                    total: data.total_tokens,
                    cost: data.total_tokens * 0.00002 // Example logic
                };

                // Set data for Bar Chart
                this.historicalData = this.formatWeeklyData(data.token_usage);

                this.animateValues();
            } catch (e) {
                console.error("Failed to fetch metrics", e);
            }
        },
        formatWeeklyData(apiUsage) {
            const dayNames = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];

            // 1. Create a map of existing data for quick lookup
            const lookup = {};
            apiUsage.forEach(item => {
                lookup[item.day] = item;
            });

            // 2. Map through all 7 days and fill blanks with 0
            return dayNames.map(day => {
                if (lookup[day]) {
                    return {
                        day: day,
                        input_tokens: lookup[day].input_tokens,
                        output_tokens: lookup[day].output_tokens
                    };
                }
                // If day doesn't exist in API, return zeroed data
                return {
                    day: day,
                    input_tokens: 0,
                    output_tokens: 0
                };
            });
        },
        animateValues() {
            const duration = 1500;
            const steps = 60;
            let step = 0;
            const timer = setInterval(() => {
                step++;
                const progress = step / steps;
                const easeOut = 1 - Math.pow(1 - progress, 3);
                this.animatedValues = {
                    input_tokens: Math.floor(this.actualData.input_tokens * easeOut),
                    output_tokens: Math.floor(this.actualData.output_tokens * easeOut),
                    total: Math.floor(this.actualData.total * easeOut),
                    cost: (this.actualData.cost * easeOut).toFixed(2)
                };
                if (step >= steps) clearInterval(timer);
            }, duration / steps);
        }
    }
};
</script>

<style lang="less" scoped>
@import "../../styles/admin/metrics.less";
</style>
