<template>
  <div class="bg-neutral rounded-lg p-4 sm:p-6">
    <!-- Controls -->
    <div class="flex flex-wrap items-end gap-4 mb-6">
      <div>
        <label class="label pb-1">
          <span class="label-text font-semibold">Compare Years</span>
        </label>
        <YearSelector v-model="selectedYears" />
      </div>
      <div class="ml-auto self-end">
        <ExportButtons :data="exportData" filename="gallons-weekly" />
      </div>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="flex justify-center items-center h-[400px]">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <!-- Error -->
    <div v-else-if="error" class="alert alert-error">
      <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <span>{{ error }}</span>
      <button class="btn btn-sm" @click="fetchData">Retry</button>
    </div>

    <!-- Chart -->
    <div v-else class="w-full h-[420px] relative">
      <Line v-if="chartData" :data="chartData as any" :options="chartOptions as any" />
      <div v-else class="flex items-center justify-center h-full text-base-content/50">
        No data available for the selected years.
      </div>
    </div>

    <!-- Summary stats -->
    <div v-if="!loading && !error" class="grid grid-cols-2 sm:grid-cols-4 gap-4 mt-6">
      <div
        v-for="(stat, index) in summaryStats"
        :key="stat.year"
        class="stat bg-base-100 rounded-lg p-3"
      >
        <div class="stat-title text-sm">{{ stat.year }} Total</div>
        <div class="stat-value text-lg" :style="{ color: yearColors[index % yearColors.length].border }">
          {{ stat.totalGallons.toLocaleString() }}
        </div>
        <div class="stat-desc">{{ stat.totalDeliveries }} deliveries</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
  Legend,
  Filler
} from 'chart.js';
import { Line } from 'vue-chartjs';
import YearSelector from './components/YearSelector.vue';
import ExportButtons from './components/ExportButtons.vue';
import { statsService } from '../../services/statsService';
import type { WeeklyGallonsYearData } from '../../types/stats';

ChartJS.register(CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, Filler);

const currentYear = new Date().getFullYear();

const selectedYears = ref<number[]>([currentYear, currentYear - 1]);
const loading = ref(false);
const error = ref<string | null>(null);
const weeklyData = ref<WeeklyGallonsYearData[]>([]);

const yearColors = [
  { border: 'rgb(59, 130, 246)',  background: 'rgba(59, 130, 246, 0.12)' },
  { border: 'rgb(16, 185, 129)',  background: 'rgba(16, 185, 129, 0.12)' },
  { border: 'rgb(249, 115, 22)',  background: 'rgba(249, 115, 22, 0.12)' },
  { border: 'rgb(139, 92, 246)', background: 'rgba(139, 92, 246, 0.12)' },
];

// Month name at the ISO week that starts each month (approximate, works for most years)
const MONTH_AT_WEEK: Record<number, string> = {
  1: 'Jan', 5: 'Feb', 9: 'Mar', 14: 'Apr', 18: 'May', 22: 'Jun',
  27: 'Jul', 31: 'Aug', 36: 'Sep', 40: 'Oct', 44: 'Nov', 48: 'Dec'
};

// 52-element label array: month name at the right week, empty string elsewhere
const xLabels = Array.from({ length: 52 }, (_, i) => MONTH_AT_WEEK[i + 1] ?? '');

const chartData = computed(() => {
  if (weeklyData.value.length === 0) return null;

  const datasets = weeklyData.value.map((yearData, index) => {
    // Slot gallons into a 52-element array indexed by week_number (1-52)
    const slots = new Array<number | null>(52).fill(null);
    for (const pt of yearData.data) {
      const idx = (pt.week_number ?? 0) - 1;
      if (idx >= 0 && idx < 52) slots[idx] = pt.gallons;
    }
    const color = yearColors[index % yearColors.length];
    return {
      label: String(yearData.year),
      data: slots,
      borderColor: color.border,
      backgroundColor: color.background,
      tension: 0.35,
      fill: false,
      pointRadius: 3,
      pointHoverRadius: 6,
      spanGaps: true,
    };
  });

  return { labels: xLabels, datasets };
});

const chartOptions = computed(() => ({
  responsive: true,
  maintainAspectRatio: false,
  interaction: { mode: 'index' as const, intersect: false },
  plugins: {
    title: {
      display: true,
      text: 'Weekly Gallons Delivered — Full Year',
      font: { size: 16 },
    },
    legend: { position: 'top' as const },
    tooltip: {
      callbacks: {
        title: (items: any[]) => `Week ${items[0]?.dataIndex + 1}`,
        label: (ctx: any) => {
          const v = ctx.parsed?.y;
          if (v == null) return `${ctx.dataset.label}: —`;
          return `${ctx.dataset.label}: ${Number(v).toLocaleString()} gal`;
        },
      },
    },
  },
  scales: {
    x: {
      grid: { display: false },
      ticks: {
        autoSkip: false,
        maxRotation: 0,
        callback: (_val: any, index: number) => xLabels[index] || null,
      },
    },
    y: {
      beginAtZero: true,
      title: { display: true, text: 'Gallons' },
      ticks: {
        callback: (v: string | number) =>
          typeof v === 'number' ? v.toLocaleString() : v,
      },
    },
  },
}));

const summaryStats = computed(() =>
  weeklyData.value.map(yd => ({
    year: yd.year,
    totalGallons: yd.data.reduce((s, d) => s + d.gallons, 0),
    totalDeliveries: yd.data.reduce((s, d) => s + d.deliveries, 0),
  }))
);

const exportData = computed(() => {
  const rows: Record<string, unknown>[] = [];
  weeklyData.value.forEach(yd =>
    yd.data.forEach(d =>
      rows.push({
        year: yd.year,
        week_number: d.week_number,
        week_start: d.week_start,
        week_end: d.week_end,
        gallons: d.gallons,
        deliveries: d.deliveries,
      })
    )
  );
  return rows;
});

async function fetchData() {
  loading.value = true;
  error.value = null;
  try {
    // Always full year. Backend replaces the year in start/end per selected year.
    const response = await statsService.getWeeklyGallons({
      start_date: `${currentYear}-01-01`,
      end_date: `${currentYear}-12-31`,
      years: selectedYears.value,
    });
    if (response.data.ok !== false) {
      weeklyData.value = response.data.years || [];
    } else {
      error.value = 'Failed to load data';
    }
  } catch {
    error.value = 'An error occurred while fetching data';
  } finally {
    loading.value = false;
  }
}

watch(selectedYears, fetchData, { deep: true });
onMounted(fetchData);
</script>
