<!-- src/pages/transactions/history.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li><router-link :to="{ name: 'transactionsAuthorize' }">Transactions</router-link></li>
          <li>History</li>
        </ul>
      </div>

      <!-- Main Content Card -->
      <!-- Page Header with Stats -->
      <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4 mt-4 mb-6">
        <div>
          <h1 class="text-2xl md:text-3xl font-bold flex items-center gap-3">
            <div
              class="w-10 h-10 rounded-xl bg-gradient-to-br from-primary to-primary/60 flex items-center justify-center shadow-lg">
              <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
                stroke="currentColor" class="w-5 h-5 text-primary-content">
                <path stroke-linecap="round" stroke-linejoin="round"
                  d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25" />
              </svg>
            </div>
            Delivery History
          </h1>
          <p class="text-base-content/60 mt-1 ml-13">View past deliveries and performance</p>
        </div>

        <!-- Date Range Picker -->
        <div class="flex gap-2 items-center bg-base-200 p-2 rounded-lg">
          <div class="form-control">
            <label class="label py-0 px-1">
              <span class="label-text text-xs font-semibold">Start</span>
            </label>
            <input type="date" v-model="startDate" class="input input-bordered input-sm focus:outline-none" />
          </div>
          <span class="text-base-content/50">-</span>
          <div class="form-control">
            <label class="label py-0 px-1">
              <span class="label-text text-xs font-semibold">End</span>
            </label>
            <input type="date" v-model="endDate" class="input input-bordered input-sm focus:outline-none" />
          </div>
        </div>
      </div>

      <!-- Summary Stats Pills -->
      <div v-if="!loading && deliveries.length > 0" class="flex flex-wrap gap-3 mb-6">
        <div class="stat-pill">
          <span class="stat-pill-value">{{ filteredDeliveries.length }}</span>
          <span class="stat-pill-label">Deliveries</span>
        </div>
        <div class="stat-pill bg-secondary/10 border-secondary/20">
          <span class="stat-pill-value text-secondary">{{ filteredTotalGallons.toLocaleString() }}</span>
          <span class="stat-pill-label">Gallons</span>
        </div>
        <div class="stat-pill bg-accent/10 border-accent/20">
          <span class="stat-pill-value text-accent">{{ Object.keys(townTotals).length }}</span>
          <span class="stat-pill-label">Towns</span>
        </div>
      </div>

      <!-- Main Content Card -->
      <div class="modern-table-card p-4 sm:p-6">
        <!-- Filter Toggles -->
        <div class="flex flex-wrap gap-4 mb-4 border-b border-base-content/10 pb-4">
          <span class="label-text font-bold uppercase text-xs tracking-wider pt-1">Filter:</span>
          <label class="label cursor-pointer gap-2 hover:bg-base-200 rounded-lg px-2 -ml-2">
            <input type="checkbox" v-model="showPrime" class="checkbox checkbox-success checkbox-sm" />
            <span class="label-text text-sm">
              Prime
              <span v-if="primeCount > 0" class="badge badge-success badge-sm ml-1">{{ primeCount }}</span>
            </span>
          </label>
          <label class="label cursor-pointer gap-2 hover:bg-base-200 rounded-lg px-2">
            <input type="checkbox" v-model="showEmergency" class="checkbox checkbox-error checkbox-sm" />
            <span class="label-text text-sm">
              Emergency
              <span v-if="emergencyCount > 0" class="badge badge-error badge-sm ml-1">{{ emergencyCount }}</span>
            </span>
          </label>
          <label class="label cursor-pointer gap-2 hover:bg-base-200 rounded-lg px-2">
            <input type="checkbox" v-model="showSameDay" class="checkbox checkbox-warning checkbox-sm" />
            <span class="label-text text-sm">
              Same Day
              <span v-if="sameDayCount > 0" class="badge badge-warning badge-sm ml-1">{{ sameDayCount }}</span>
            </span>
          </label>
        </div>

        <!-- Col Toggles (Collapsible maybe? Keeping visible for now) -->
        <div class="flex flex-wrap gap-4 mb-4 text-xs">
          <span class="label-text font-bold uppercase tracking-wider pt-1 opacity-60">Columns:</span>
          <label class="label cursor-pointer gap-2 p-0">
            <input type="checkbox" v-model="colName" class="checkbox checkbox-xs checkbox-primary" />
            <span class="label-text text-xs">Name</span>
          </label>
          <label class="label cursor-pointer gap-2 p-0">
            <input type="checkbox" v-model="colTown" class="checkbox checkbox-xs checkbox-primary" />
            <span class="label-text text-xs">Town</span>
          </label>
          <label class="label cursor-pointer gap-2 p-0">
            <input type="checkbox" v-model="colAddress" class="checkbox checkbox-xs checkbox-primary" />
            <span class="label-text text-xs">Address</span>
          </label>
          <label class="label cursor-pointer gap-2 p-0">
            <input type="checkbox" v-model="colGallons" class="checkbox checkbox-xs checkbox-primary" />
            <span class="label-text text-xs">Gallons</span>
          </label>
          <label class="label cursor-pointer gap-2 p-0">
            <input type="checkbox" v-model="colFlags" class="checkbox checkbox-xs checkbox-primary" />
            <span class="label-text text-xs">Flags</span>
          </label>
          <label class="label cursor-pointer gap-2 p-0">
            <input type="checkbox" v-model="colActions" class="checkbox checkbox-xs checkbox-primary" />
            <span class="label-text text-xs">Actions</span>
          </label>
        </div>

        <!-- Summary Stats (Legacy removal or keep? I moved main stats up. Keeping Town Totals here) -->
        <div v-if="!loading && deliveries.length > 0 && Object.keys(townTotals).length > 0" class="mb-4">
          <div class="flex flex-wrap gap-2">
            <span v-for="(data, town) in townTotals" :key="town" class="badge badge-outline badge-sm opacity-70">
              {{ town }}: {{ data.gallons.toLocaleString() }} gal ({{ data.count }})
            </span>
          </div>
        </div>

        <!-- Loading State -->
        <div v-if="loading" class="flex justify-center items-center py-20">
          <span class="loading loading-spinner loading-lg text-primary"></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="fetchDeliveries">Retry</button>
        </div>

        <!-- Empty State -->
        <div v-else-if="deliveries.length === 0" class="text-center py-20">
          <div class="w-16 h-16 bg-base-200 rounded-full flex items-center justify-center mx-auto mb-4">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-base-content/30" fill="none" viewBox="0 0 24 24"
              stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
            </svg>
          </div>
          <h3 class="mt-2 text-sm font-bold">No deliveries found</h3>
          <p class="mt-1 text-sm text-base-content/60">
            No completed deliveries
            <span v-if="startDate === endDate">on {{ formatDate(startDate) }}</span>
            <span v-else>from {{ formatDate(startDate) }} to {{ formatDate(endDate) }}</span>
          </p>
        </div>

        <!-- Deliveries Table (Desktop) -->
        <div v-else class="overflow-x-auto hidden xl:block">
          <table class="modern-table">
            <thead>
              <tr>
                <th v-if="colName">Name</th>
                <th v-if="colTown">Town</th>
                <th v-if="colAddress">Address</th>
                <th v-if="colGallons" class="text-right">Gallons</th>
                <th v-if="colFlags">Flags</th>
                <th v-if="colActions" class="text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="delivery in filteredDeliveries" :key="delivery.id" class="table-row-hover">
                <td v-if="colName" class="font-bold">
                  <router-link :to="{ name: 'customerProfile', params: { id: delivery.customerId } }"
                    class="link link-hover hover:text-primary">
                    {{ delivery.customerName }}
                  </router-link>
                </td>
                <td v-if="colTown">{{ delivery.town }}</td>
                <td v-if="colAddress" class="max-w-xs text-sm opacity-70">{{ delivery.address }}</td>
                <td v-if="colGallons" class="text-right font-mono font-bold">{{
                  Number(delivery.gallonsDelivered).toLocaleString() }}</td>
                <td v-if="colFlags">
                  <div class="flex gap-1 flex-wrap">
                    <span v-if="delivery.prime" class="badge badge-success badge-sm gap-1">
                      P
                    </span>
                    <span v-if="delivery.emergency" class="badge badge-error badge-sm gap-1">
                      E
                    </span>
                    <span v-if="delivery.sameDay" class="badge badge-warning badge-sm gap-1">
                      S
                    </span>
                  </div>
                </td>
                <td v-if="colActions" class="text-right">
                  <router-link :to="{ name: 'deliveryOrder', params: { id: delivery.id } }"
                    class="btn btn-sm btn-ghost">
                    View
                  </router-link>
                </td>
              </tr>
            </tbody>
            <tfoot v-if="colGallons">
              <tr class="font-bold bg-base-200/50">
                <td :colspan="visibleColsBeforeGallons">Total</td>
                <td class="text-right font-mono text-primary">{{ filteredTotalGallons.toLocaleString() }}</td>
                <td :colspan="visibleColsAfterGallons"></td>
              </tr>
            </tfoot>
          </table>
        </div>

        <!-- Mobile Cards -->
        <div class="xl:hidden space-y-4 pt-4">
          <div v-for="delivery in filteredDeliveries" :key="delivery.id" class="mobile-card">
            <div class="p-3">
              <div class="flex justify-between items-start">
                <div>
                  <router-link :to="{ name: 'customerProfile', params: { id: delivery.customerId } }"
                    class="font-bold text-base link link-hover">
                    {{ delivery.customerName }}
                  </router-link>
                  <p class="text-xs text-base-content/60">{{ delivery.town }}</p>
                </div>
                <div class="flex flex-col items-end">
                  <div class="font-mono font-bold text-primary">{{ Number(delivery.gallonsDelivered).toLocaleString() }}
                    gal</div>
                </div>
              </div>

              <div class="flex gap-1 mt-2">
                <span v-if="delivery.prime" class="badge badge-success badge-sm">Prime</span>
                <span v-if="delivery.emergency" class="badge badge-error badge-sm">Emergency</span>
                <span v-if="delivery.sameDay" class="badge badge-warning badge-sm">Same Day</span>
              </div>

              <div class="mt-3 pt-3 border-t border-base-content/10 flex justify-end">
                <router-link :to="{ name: 'deliveryOrder', params: { id: delivery.id } }"
                  class="btn btn-sm btn-ghost w-full">
                  View Details
                </router-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { deliveryService } from '../../services/deliveryService';
import type { DeliveryHistoryItem } from '../../types/models';

// State
const loading = ref(false);
const error = ref<string | null>(null);
const deliveries = ref<DeliveryHistoryItem[]>([]);
const today = new Date().toISOString().split('T')[0];
const startDate = ref(today);
const endDate = ref(today);

// Filter toggles
const showPrime = ref(true);
const showEmergency = ref(true);
const showSameDay = ref(true);

// Column visibility toggles
const colName = ref(true);
const colTown = ref(true);
const colAddress = ref(false);  // Off by default since most use case is quick view
const colGallons = ref(true);
const colFlags = ref(true);
const colActions = ref(true);

// Counts from API
const primeCount = ref(0);
const emergencyCount = ref(0);
const sameDayCount = ref(0);

// Computed
const visibleColsBeforeGallons = computed(() => {
  return [colName.value, colTown.value, colAddress.value].filter(Boolean).length || 1;
});

const visibleColsAfterGallons = computed(() => {
  return [colFlags.value, colActions.value].filter(Boolean).length || 1;
});

const filteredDeliveries = computed(() => {
  return deliveries.value.filter(d => {
    // If delivery has a flag and that filter is off, hide it
    if (d.prime && !showPrime.value) return false;
    if (d.emergency && !showEmergency.value) return false;
    if (d.sameDay && !showSameDay.value) return false;
    return true;
  });
});

const filteredTotalGallons = computed(() => {
  return filteredDeliveries.value.reduce((sum, d) => sum + Number(d.gallonsDelivered), 0);
});

const townTotals = computed(() => {
  const totals: Record<string, { gallons: number; count: number }> = {};
  for (const d of filteredDeliveries.value) {
    const town = d.town || 'Unknown';
    if (!totals[town]) {
      totals[town] = { gallons: 0, count: 0 };
    }
    totals[town].gallons += Number(d.gallonsDelivered);
    totals[town].count += 1;
  }
  // Sort by town name
  const sorted: Record<string, { gallons: number; count: number }> = {};
  Object.keys(totals).sort().forEach(key => {
    sorted[key] = totals[key];
  });
  return sorted;
});

// Methods
const fetchDeliveries = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await deliveryService.getHistory(startDate.value, endDate.value);
    if (response.data.ok) {
      deliveries.value = response.data.deliveries || [];
      primeCount.value = response.data.primeCount || 0;
      emergencyCount.value = response.data.emergencyCount || 0;
      sameDayCount.value = response.data.sameDayCount || 0;
    } else {
      error.value = 'Failed to fetch delivery history';
    }
  } catch (err: any) {
    console.error('Error fetching delivery history:', err);
    error.value = err.response?.data?.error || 'Failed to fetch delivery history';
  } finally {
    loading.value = false;
  }
};

const formatDate = (dateStr: string) => {
  const date = new Date(dateStr + 'T00:00:00');
  return date.toLocaleDateString('en-US', {
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// Watchers
watch([startDate, endDate], () => {
  fetchDeliveries();
});

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