<!-- src/pages/delivery/map.vue -->
<template>
  <div class="flex">
    <div class="w-full px-4 md:px-10 py-4">
      <!-- Breadcrumbs & Title -->
      <div class="text-sm breadcrumbs">
        <ul>
          <li><router-link :to="{ name: 'home' }">Home</router-link></li>
          <li><router-link :to="{ name: 'delivery' }">Delivery</router-link></li>
          <li>Delivery Map</li>
        </ul>
      </div>

      <!-- Main Content Card -->
      <div class="bg-neutral rounded-lg p-4 sm:p-6 mt-6">
        <!-- Header: Quick-select date buttons -->
        <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-4">
          <h2 class="text-lg font-bold">Delivery Map</h2>
          <div class="flex flex-wrap gap-2">
            <button
              v-for="btn in dateButtons"
              :key="btn.offset"
              @click="selectDay(btn.offset)"
              class="btn btn-sm"
              :class="!showAll && selectedDate === dateForOffset(btn.offset) ? 'btn-primary' : 'btn-outline'"
            >
              {{ btn.label }}
            </button>
            <button
              @click="selectAll"
              class="btn btn-sm"
              :class="showAll ? 'btn-warning' : 'btn-outline btn-warning'"
            >
              All Eligible
            </button>
          </div>
        </div>

        <div class="divider"></div>

        <!-- Stats Bar -->
        <div v-if="!loading && deliveries.length > 0" class="mb-4 flex flex-wrap gap-2">
          <span class="badge badge-primary">{{ deliveries.length }} Deliveries</span>
          <span class="badge badge-secondary">{{ uniqueTowns.length }} Towns</span>
          <span class="badge badge-accent">{{ mappedCount }} Mapped</span>
          <span class="badge badge-success">{{ grandTotal.toLocaleString() }} Gallons</span>
          <span v-if="unmappedCount > 0" class="badge badge-warning">{{ unmappedCount }} Without Coordinates</span>
        </div>

        <!-- Town Breakdown Bar -->
        <div v-if="!loading && townTotals.length > 0" class="mb-4 overflow-x-auto">
          <div class="flex gap-2 pb-2">
            <div
              v-for="total in townTotals"
              :key="total.town"
              class="flex items-center gap-2 px-3 py-1.5 rounded-full bg-base-200 text-sm whitespace-nowrap"
            >
              <span class="font-semibold">{{ total.town }}</span>
              <span class="px-2 py-0.5 rounded-full bg-base-content/10 text-xs font-mono">{{ total.gallons }} gal</span>
            </div>
          </div>
        </div>

        <!-- Loading State -->
        <div v-if="loading" class="flex justify-center items-center py-20">
          <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>
        </div>

        <!-- Empty State -->
        <div v-else-if="deliveries.length === 0" class="text-center py-20">
          <svg xmlns="http://www.w3.org/2000/svg" class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7" />
          </svg>
          <h3 class="mt-2 text-sm font-medium">No deliveries found</h3>
          <p class="mt-1 text-sm text-gray-500">{{ showAll ? 'No eligible deliveries found' : `No deliveries scheduled for ${formatDate(selectedDate)}` }}</p>
        </div>

        <!-- Map and List -->
        <div v-else>
          <!-- Map Container -->
          <div class="rounded-lg overflow-hidden mb-6" style="height: 500px;">
            <l-map
              ref="map"
              v-model:zoom="zoom"
              :center="mapCenter"
              :use-global-leaflet="false"
            >
              <l-tile-layer
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                layer-type="base"
                name="OpenStreetMap"
              ></l-tile-layer>
              <l-marker
                v-for="delivery in mappedDeliveries"
                :key="delivery.id"
                :lat-lng="[parseFloat(delivery.latitude!), parseFloat(delivery.longitude!)]"
              >
                <l-popup>
                  <div class="text-sm">
                    <p class="font-bold">{{ delivery.customerName }}</p>
                    <p>{{ delivery.street }}</p>
                    <p>{{ delivery.town }}, {{ STATE_ID_TO_ABBR[Number(delivery.state)] || delivery.state }} {{ delivery.zipcode }}</p>
                    <p class="mt-1">
                      <span v-if="delivery.isFill" class="font-semibold text-blue-600">FILL</span>
                      <span v-else>{{ delivery.gallonsOrdered }} gallons</span>
                    </p>
                    <p v-if="delivery.notes" class="mt-1 text-gray-600 italic">{{ delivery.notes }}</p>
                    <div class="mt-2">
                      <router-link
                        :to="{ name: 'deliveryOrder', params: { id: delivery.id } }"
                        class="text-blue-500 hover:underline"
                      >
                        View Delivery
                      </router-link>
                    </div>
                  </div>
                </l-popup>
              </l-marker>
            </l-map>
          </div>

          <!-- Address List for Copy/Paste -->
          <div class="bg-base-100 rounded-lg p-4">
            <div class="flex justify-between items-center mb-3">
              <h3 class="text-md font-semibold">Addresses</h3>
              <button @click="copyAddresses" class="btn btn-sm btn-primary">
                {{ copied ? '✓ Copied!' : 'Copy All' }}
              </button>
            </div>
            <pre ref="addressList" class="whitespace-pre-wrap text-sm font-mono select-all bg-base-200 rounded p-3">{{ addressText }}</pre>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import "leaflet/dist/leaflet.css";
import { LMap, LTileLayer, LMarker, LPopup } from "@vue-leaflet/vue-leaflet";
import { deliveryService } from '../../services/deliveryService';
import { DeliveryMapItem } from '../../types/models';
import { STATE_ID_TO_ABBR } from '../../constants/states';

// Date helpers
const dateButtons = [
  { label: 'Yesterday', offset: -1 },
  { label: 'Today',     offset: 0  },
  { label: 'Tomorrow',  offset: 1  },
  { label: '+2 Days',   offset: 2  },
  { label: '+3 Days',   offset: 3  },
];

const dateForOffset = (offset: number): string => {
  const d = new Date();
  d.setDate(d.getDate() + offset);
  return d.toISOString().split('T')[0];
};

const selectDay = (offset: number) => {
  showAll.value = false;
  selectedDate.value = dateForOffset(offset);
  fetchDeliveries();
};

const selectAll = () => {
  showAll.value = true;
  fetchDeliveries();
};

// State
const loading = ref(false);
const error = ref<string | null>(null);
const deliveries = ref<DeliveryMapItem[]>([]);
const selectedDate = ref(dateForOffset(0));
const showAll = ref(false);
const zoom = ref(11);

// Computed
const mappedDeliveries = computed(() =>
  deliveries.value.filter(d => d.latitude && d.longitude)
);

const mappedCount = computed(() => mappedDeliveries.value.length);
const unmappedCount = computed(() => deliveries.value.length - mappedCount.value);

const uniqueTowns = computed(() =>
  [...new Set(deliveries.value.map(d => d.town))]
);

interface TownTotal {
  town: string;
  gallons: number;
}

const townTotals = computed((): TownTotal[] => {
  const totals: Record<string, number> = {};
  for (const delivery of deliveries.value) {
    const town = delivery.town || 'Unknown';
    // For fills, estimate 200 gallons; otherwise use ordered gallons
    const gallons = delivery.isFill ? 200 : (delivery.gallonsOrdered || 0);
    totals[town] = (totals[town] || 0) + gallons;
  }
  return Object.entries(totals)
    .map(([town, gallons]) => ({ town, gallons }))
    .sort((a, b) => b.gallons - a.gallons);
});

const grandTotal = computed(() => {
  return townTotals.value.reduce((sum, t) => sum + t.gallons, 0);
});

const addressText = computed(() => {
  return deliveries.value
    .map(d => {
      const stateAbbr = STATE_ID_TO_ABBR[Number(d.state)] || d.state;
      return `${d.street} ${d.town} ${stateAbbr}`;
    })
    .join('\n');
});

const mapCenter = computed<[number, number]>(() => {
  if (mappedDeliveries.value.length === 0) {
    // Default to CT center
    return [41.6032, -73.0877];
  }
  const lats = mappedDeliveries.value.map(d => parseFloat(d.latitude!));
  const lngs = mappedDeliveries.value.map(d => parseFloat(d.longitude!));
  const avgLat = lats.reduce((a, b) => a + b, 0) / lats.length;
  const avgLng = lngs.reduce((a, b) => a + b, 0) / lngs.length;
  return [avgLat, avgLng];
});

// State for copy button
const copied = ref(false);

// Methods
const copyAddresses = async () => {
  try {
    await navigator.clipboard.writeText(addressText.value);
    copied.value = true;
    setTimeout(() => { copied.value = false; }, 2000);
  } catch (err) {
    console.error('Failed to copy addresses:', err);
  }
};

const fetchDeliveries = async () => {
  loading.value = true;
  error.value = null;
  try {
    const response = await deliveryService.getForMap(selectedDate.value, showAll.value);
    if (response.data.ok) {
      deliveries.value = response.data.deliveries || [];
    } else {
      error.value = 'Failed to fetch deliveries';
    }
  } catch (err: any) {
    console.error('Error fetching deliveries for map:', err);
    error.value = err.response?.data?.error || 'Failed to fetch deliveries';
  } 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'
  });
};

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

<style scoped>
.leaflet-container {
  z-index: 0;
}
</style>
