<template>
    <div class="modern-table-card p-6">
        <div class="card-body p-0">
            <h2 class="card-title text-2xl mb-6 flex items-center gap-2">
                Totals Comparison
            </h2>

            <!-- Period Selector -->
            <div class="flex justify-center mb-8">
                <div class="join">
                    <button class="join-item btn" :class="{ 'btn-primary': period === 'day' }"
                        @click="setPeriod('day')">
                        Daily
                    </button>
                    <button class="join-item btn" :class="{ 'btn-primary': period === 'month' }"
                        @click="setPeriod('month')">
                        Monthly
                    </button>
                    <button class="join-item btn" :class="{ 'btn-primary': period === 'year' }"
                        @click="setPeriod('year')">
                        Yearly
                    </button>
                </div>
            </div>

            <!-- Date Picker for Reference (Only for Day/Month) -->
            <div v-if="period !== 'year'" class="flex justify-center mb-8">
                <div class="form-control w-full max-w-xs">
                    <label class="label">
                        <span class="label-text">Select Date</span>
                    </label>
                    <input type="date" v-model="referenceDate" @change="fetchData"
                        class="input input-bordered w-full max-w-xs" />
                </div>
            </div>

            <div v-if="loading" class="flex justify-center py-10">
                <span class="loading loading-spinner loading-lg text-primary"></span>
            </div>

            <!-- Stat Cards Grid -->
            <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
                <div v-for="(yearData, index) in totalsData" :key="yearData.year"
                    class="stat bg-base-200 rounded-box shadow" :class="{ 'border-2 border-primary': index === 0 }">
                    <div class="stat-figure text-primary" v-if="index === 0">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                            class="inline-block w-8 h-8 stroke-current">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                        </svg>
                    </div>

                    <div class="stat-title font-bold text-lg">{{ yearData.period_label }}</div>
                    <div class="stat-value text-2xl md:text-3xl">{{ formatNumber(yearData.gallons) }}</div>
                    <div class="stat-desc font-semibold">{{ formatNumber(yearData.count) }} deliveries</div>

                    <!-- Comparison pill (vs previous year) -->
                    <!-- Only show for non-oldest year -->
                    <div v-if="index < totalsData.length - 1" class="mt-2">
                        <div class="badge" :class="getDiffClass(yearData.gallons, totalsData[index + 1].gallons)">
                            {{ calculateDiff(yearData.gallons, totalsData[index + 1].gallons) }}%
                            <span class="ml-1 text-xs opacity-70">vs {{ totalsData[index + 1].year }}</span>
                        </div>
                    </div>

                </div>
            </div>

        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { adminService } from '../../../services/adminService';
import dayjs from 'dayjs';

type Period = 'day' | 'month' | 'year';

const period = ref<Period>('day');
const referenceDate = ref(dayjs().format('YYYY-MM-DD'));
const loading = ref(false);
const totalsData = ref<any[]>([]);

const setPeriod = (p: Period) => {
    period.value = p;
    fetchData();
}

const formatNumber = (num: number) => {
    return new Intl.NumberFormat('en-US').format(num);
}

const calculateDiff = (current: number, previous: number) => {
    if (previous === 0) return current > 0 ? '+100' : '0';
    const diff = ((current - previous) / previous) * 100;
    return (diff > 0 ? '+' : '') + diff.toFixed(1);
}

const getDiffClass = (current: number, previous: number) => {
    const diff = calculateDiff(current, previous);
    if (diff === '0') return 'badge-ghost';
    return diff.startsWith('+') ? 'badge-success gap-2' : 'badge-error gap-2';
}

const fetchData = async () => {
    loading.value = true;
    try {
        const response = await adminService.stats.getTotals(period.value, referenceDate.value);
        if (response.data && response.data.totals) {
            totalsData.value = response.data.totals;
        }
    } catch (err) {
        console.error("Failed to fetch totals", err);
    } finally {
        loading.value = false;
    }
}

onMounted(() => {
    fetchData();
})
</script>
