<template>
  <div class="bg-neutral rounded-lg p-4 sm:p-6">
    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6">
      <div>
        <h2 class="text-xl font-bold">Period Totals</h2>
        <p class="text-sm text-base-content/70">
          Comparing {{ currentYear }} vs {{ compareYear }}
        </p>
      </div>
      <ExportButtons :data="exportData" filename="totals-comparison" />
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="flex justify-center items-center h-64">
      <span class="loading loading-spinner loading-lg"></span>
    </div>

    <!-- Error State -->
    <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>

    <!-- Comparison Cards -->
    <div v-else class="space-y-8">
      <!-- Today -->
      <div>
        <h3 class="text-lg font-semibold mb-3">Today</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <ComparisonCard
            v-if="comparisonData?.today"
            title="Gallons Delivered"
            :current-value="comparisonData.today.gallons.current"
            :previous-value="comparisonData.today.gallons.previous"
            :change-percent="comparisonData.today.gallons.change_percent"
            :change-direction="comparisonData.today.gallons.change_direction"
            :compare-year="compareYear"
            format="gallons"
          />
          <ComparisonCard
            v-if="comparisonData?.today"
            title="Deliveries"
            :current-value="comparisonData.today.deliveries.current"
            :previous-value="comparisonData.today.deliveries.previous"
            :change-percent="comparisonData.today.deliveries.change_percent"
            :change-direction="comparisonData.today.deliveries.change_direction"
            :compare-year="compareYear"
          />
        </div>
      </div>

      <!-- Week to Date -->
      <div>
        <h3 class="text-lg font-semibold mb-3">Week to Date</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <ComparisonCard
            v-if="comparisonData?.week_to_date"
            title="Gallons Delivered"
            :current-value="comparisonData.week_to_date.gallons.current"
            :previous-value="comparisonData.week_to_date.gallons.previous"
            :change-percent="comparisonData.week_to_date.gallons.change_percent"
            :change-direction="comparisonData.week_to_date.gallons.change_direction"
            :compare-year="compareYear"
            format="gallons"
          />
          <ComparisonCard
            v-if="comparisonData?.week_to_date"
            title="Deliveries"
            :current-value="comparisonData.week_to_date.deliveries.current"
            :previous-value="comparisonData.week_to_date.deliveries.previous"
            :change-percent="comparisonData.week_to_date.deliveries.change_percent"
            :change-direction="comparisonData.week_to_date.deliveries.change_direction"
            :compare-year="compareYear"
          />
        </div>
      </div>

      <!-- Month to Date -->
      <div>
        <h3 class="text-lg font-semibold mb-3">Month to Date</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <ComparisonCard
            v-if="comparisonData?.month_to_date"
            title="Gallons Delivered"
            :current-value="comparisonData.month_to_date.gallons.current"
            :previous-value="comparisonData.month_to_date.gallons.previous"
            :change-percent="comparisonData.month_to_date.gallons.change_percent"
            :change-direction="comparisonData.month_to_date.gallons.change_direction"
            :compare-year="compareYear"
            format="gallons"
          />
          <ComparisonCard
            v-if="comparisonData?.month_to_date"
            title="Deliveries"
            :current-value="comparisonData.month_to_date.deliveries.current"
            :previous-value="comparisonData.month_to_date.deliveries.previous"
            :change-percent="comparisonData.month_to_date.deliveries.change_percent"
            :change-direction="comparisonData.month_to_date.deliveries.change_direction"
            :compare-year="compareYear"
          />
        </div>
      </div>

      <!-- Year to Date -->
      <div>
        <h3 class="text-lg font-semibold mb-3">Year to Date</h3>
        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
          <ComparisonCard
            v-if="comparisonData?.year_to_date"
            title="Gallons Delivered"
            :current-value="comparisonData.year_to_date.gallons.current"
            :previous-value="comparisonData.year_to_date.gallons.previous"
            :change-percent="comparisonData.year_to_date.gallons.change_percent"
            :change-direction="comparisonData.year_to_date.gallons.change_direction"
            :compare-year="compareYear"
            format="gallons"
          />
          <ComparisonCard
            v-if="comparisonData?.year_to_date"
            title="Deliveries"
            :current-value="comparisonData.year_to_date.deliveries.current"
            :previous-value="comparisonData.year_to_date.deliveries.previous"
            :change-percent="comparisonData.year_to_date.deliveries.change_percent"
            :change-direction="comparisonData.year_to_date.deliveries.change_direction"
            :compare-year="compareYear"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import ComparisonCard from './components/ComparisonCard.vue';
import ExportButtons from './components/ExportButtons.vue';
import { statsService } from '../../services/statsService';
import type { TotalsComparisonData } from '../../types/stats';

// State
const loading = ref(false);
const error = ref<string | null>(null);
const comparisonData = ref<TotalsComparisonData | null>(null);
const currentYear = ref(new Date().getFullYear());
const compareYear = ref(new Date().getFullYear() - 1);

// Export data for CSV
const exportData = computed(() => {
  if (!comparisonData.value) return [];

  const periods = ['today', 'week_to_date', 'month_to_date', 'year_to_date'] as const;
  const metrics = ['gallons', 'deliveries'] as const;
  const rows: Record<string, unknown>[] = [];

  periods.forEach(period => {
    const periodData = comparisonData.value?.[period];
    if (periodData) {
      metrics.forEach(metric => {
        const metricData = periodData[metric];
        rows.push({
          period: period.replace(/_/g, ' '),
          metric,
          current_year: currentYear.value,
          current_value: metricData.current,
          previous_year: compareYear.value,
          previous_value: metricData.previous,
          change_percent: metricData.change_percent,
          change_direction: metricData.change_direction
        });
      });
    }
  });

  return rows;
});

// Methods
async function fetchData() {
  loading.value = true;
  error.value = null;

  try {
    const response = await statsService.getTotalsComparison();
    if (response.data.ok !== false) {
      comparisonData.value = response.data.comparison;
      currentYear.value = response.data.current_year;
      compareYear.value = response.data.compare_year;
    } else {
      error.value = 'Failed to load comparison data';
    }
  } catch (err) {
    console.error('Error fetching comparison data:', err);
    error.value = 'An error occurred while fetching data';
  } finally {
    loading.value = false;
  }
}

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