<template>
    <div class="modern-table-card p-6">
        <div class="card-body p-0">
            <div class="flex flex-col md:flex-row justify-between items-center mb-6">
                <h2 class="card-title text-2xl mb-4 md:mb-0">Daily Deliveries</h2>

                <!-- Controls -->
                <div class="flex flex-wrap gap-2 items-center">
                    <!-- Time Range -->
                    <div class="join">
                        <button class="join-item btn btn-sm" :class="{ 'btn-primary': rangeMode === 'week' }"
                            @click="setRange('week')">
                            Week
                        </button>
                        <button class="join-item btn btn-sm" :class="{ 'btn-primary': rangeMode === 'month' }"
                            @click="setRange('month')">
                            Month
                        </button>
                        <button class="join-item btn btn-sm" :class="{ 'btn-primary': rangeMode === 'quarter' }"
                            @click="setRange('quarter')">
                            Quarter
                        </button>
                    </div>

                    <div class="divider divider-horizontal mx-0"></div>

                    <!-- Year Comparison -->
                    <div class="dropdown dropdown-end">
                        <label tabindex="0" class="btn btn-sm btn-outline gap-2">
                            Compare Years
                            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24"
                                stroke="currentColor">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                    d="M19 9l-7 7-7-7" />
                            </svg>
                        </label>
                        <ul tabindex="0" class="dropdown-content z-[1] menu p-2 shadow bg-base-100 rounded-box w-52">
                            <li v-for="year in availableYears" :key="year">
                                <label class="label cursor-pointer">
                                    <span class="label-text">{{ year }}</span>
                                    <input type="checkbox" :value="year" v-model="selectedYears"
                                        class="checkbox checkbox-primary checkbox-sm" />
                                </label>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>

            <!-- Chart Container -->
            <div class="h-96 w-full relative">
                <div v-if="loading" class="absolute inset-0 flex items-center justify-center bg-base-100/50 z-10">
                    <span class="loading loading-spinner loading-lg text-primary"></span>
                </div>
                <Line v-if="chartData.labels.length > 0" :data="chartData" :options="chartOptions" />
                <div v-else-if="!loading" class="flex h-full items-center justify-center text-gray-500">
                    No data available for the selected period.
                </div>
            </div>

            <!-- Summary Text -->
            <div class="stats stats-horizontal shadow mt-4 w-full bg-base-200">
                <div class="stat">
                    <div class="stat-title">Total Gallons (Period)</div>
                    <div class="stat-value text-primary">{{ formatNumber(periodTotalGallons) }}</div>
                    <div class="stat-desc">Gallons delivered in selected range</div>
                </div>
                <div class="stat">
                    <div class="stat-title">Total Deliveries</div>
                    <div class="stat-value">{{ periodTotalCount }}</div>
                    <div class="stat-desc">Stops made in selected range</div>
                </div>
                <div class="stat">
                    <div class="stat-title">Avg Drop</div>
                    <div class="stat-value text-secondary">{{ formatNumber(averageDrop) }}</div>
                    <div class="stat-desc">Gallons</div>
                </div>
            </div>

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

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { adminService } from '../../../services/adminService';
import {
    Chart as ChartJS,
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
} from 'chart.js';
import { Line } from 'vue-chartjs';
import dayjs from 'dayjs';

// Register ChartJS components
ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
    Legend
);

// Types
type RangeMode = 'week' | 'month' | 'quarter';

// State
const loading = ref(false);
const rangeMode = ref<RangeMode>('week');
const selectedYears = ref<number[]>([]);
const currentYear = new Date().getFullYear();
const availableYears = ref([currentYear - 1, currentYear - 2, currentYear - 3, currentYear - 4]); // Dynamic in real app?

// Data storage
const primaryData = ref<any[]>([]);
// Store comparison data: { year: [data points] }
const comparisonData = ref<Record<number, any[]>>({});

// Computed Metrics
const periodTotalGallons = computed(() => primaryData.value.reduce((acc, curr) => acc + curr.gallons, 0));
const periodTotalCount = computed(() => primaryData.value.reduce((acc, curr) => acc + curr.count, 0));
const averageDrop = computed(() => periodTotalCount.value > 0 ? periodTotalGallons.value / periodTotalCount.value : 0);


// Chart Configuration
const chartOptions: any = {
    responsive: true,
    maintainAspectRatio: false,
    interaction: {
        mode: 'index',
        intersect: false,
    },
    plugins: {
        legend: {
            position: 'top' as const,
        },
        tooltip: {
            callbacks: {
                label: function (context: any) {
                    let label = context.dataset.label || '';
                    if (label) {
                        label += ': ';
                    }
                    if (context.parsed.y !== null) {
                        label += new Intl.NumberFormat('en-US').format(context.parsed.y) + ' gal';
                    }
                    return label;
                }
            }
        }
    },
    scales: {
        y: {
            beginAtZero: true,
            title: {
                display: true,
                text: 'Gallons'
            }
        }
    }
};

const chartData = computed(() => {
    // Labels depend on the primary date range
    const labels = primaryData.value.map(d => dayjs(d.date).format('MMM D'));

    const datasets = [
        {
            label: `Current (${currentYear})`,
            backgroundColor: '#00afb9', // Teal
            borderColor: '#00afb9',
            data: primaryData.value.map(d => d.gallons),
            tension: 0.3,
            pointRadius: 2,
        }
    ];

    // Add comparison datasets
    selectedYears.value.forEach((year, index) => {
        const yearData = comparisonData.value[year] || [];
        // We need to map comparison data to align with the primary labels/indices if possible
        // Simple approach: assume same array length and order for "same logic" comparison (e.g. "last 7 days")

        // Colors for comparisons
        const colors = ['#f07167', '#fed9b7', '#0081a7', '#6d597a'];
        const color = colors[index % colors.length];

        datasets.push({
            label: `${year}`,
            backgroundColor: color,
            borderColor: color,
            data: yearData.map(d => d.gallons),
            tension: 0.3,
            pointRadius: 2,
            borderDash: [5, 5]
        } as any);
    });

    return {
        labels,
        datasets
    };
});

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

const getDateRange = () => {
    const end = dayjs();
    let start = dayjs();

    if (rangeMode.value === 'week') start = end.subtract(7, 'day');
    else if (rangeMode.value === 'month') start = end.subtract(30, 'day');
    else if (rangeMode.value === 'quarter') start = end.subtract(90, 'day');

    return { start, end };
};

const fetchData = async () => {
    loading.value = true;
    const { start, end } = getDateRange();

    try {
        // Fetch Primary Data
        const response = await adminService.stats.getDailyStats(
            start.format('YYYY-MM-DD'),
            end.format('YYYY-MM-DD')
        );

        if (response.data && response.data.daily_stats) {
            primaryData.value = response.data.daily_stats;
        }

        // Fetch Comparison Data if selected
        // Note: For comparison, we need to shift the dates back by N years
        comparisonData.value = {}; // Reset

        const promises = selectedYears.value.map(async (year) => {
            const yearDiff = currentYear - year;
            const histStart = start.subtract(yearDiff, 'year');
            const histEnd = end.subtract(yearDiff, 'year');

            const res = await adminService.stats.getDailyStats(
                histStart.format('YYYY-MM-DD'),
                histEnd.format('YYYY-MM-DD')
            );

            if (res.data && res.data.daily_stats) {
                comparisonData.value[year] = res.data.daily_stats;
            }
        });

        await Promise.all(promises);

    } catch (err) {
        console.error("Error fetching daily stats", err);
    } finally {
        loading.value = false;
    }
};

const setRange = (mode: RangeMode) => {
    rangeMode.value = mode;
    // Debounce or immediate fetch?
    fetchData();
};

// Watchers
watch(selectedYears, () => {
    fetchData();
});

// Lifecycle
onMounted(() => {
    fetchData();
});

</script>

<style scoped>
/* Add extra chart styling if needed */
</style>
