<!-- src/pages/automatic/home.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>Automatic Deliveries</li>
        </ul>
      </div>
      <!-- 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="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />
              </svg>
            </div>
            Automatic Deliveries
          </h1>
          <p class="text-base-content/60 mt-1 ml-13">Manage automatic delivery customers and schedules</p>
        </div>

        <!-- NEW: Search Bar -->
        <div class="form-control w-full lg:w-auto">
          <div class="input-group">
            <input v-model="searchQuery" type="text" placeholder="Search customer, town, address..."
              class="input input-bordered w-full lg:w-80" />
            <button class="btn btn-square">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24"
                stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
              </svg>
            </button>
          </div>
        </div>

        <!-- Quick Stats -->
        <div class="flex flex-wrap gap-3">
          <div class="stat-pill">
            <span class="stat-pill-value">{{ sortedDeliveries.length }}</span>
            <span class="stat-pill-label">Customers</span>
          </div>
          <div class="stat-pill" v-if="urgentCount > 0">
            <span class="stat-pill-value text-error">{{ urgentCount }}</span>
            <span class="stat-pill-label">Urgent (&lt;=7 days)</span>
          </div>
        </div>
      </div>

      <!-- Main Content Card -->
      <div class="modern-table-card">

        <!-- Data Display -->
        <div>
          <!-- DESKTOP VIEW: Sortable Table -->
          <div class="hidden lg:block w-full">
            <table class="modern-table w-full table-fixed">
              <thead>
                <tr>
                  <!-- SORTABLE HEADERS -->
                  <th @click="sortBy('tank_level_percent')" class="cursor-pointer select-none whitespace-nowrap w-[15%]"
                    :class="{ 'text-primary': sortKey === 'tank_level_percent' }">
                    Tank Level
                    <span v-if="sortKey === 'tank_level_percent'" class="ml-1">{{ sortAsc ? '&#9650;' : '&#9660;' }}</span>
                    <span v-else class="ml-1 opacity-30 text-xs">&#8693;</span>
                  </th>
                  <th @click="sortBy('days_since_last_fill')" class="cursor-pointer select-none whitespace-nowrap w-[10%]"
                    :class="{ 'text-primary': sortKey === 'days_since_last_fill' }">
                    Days Since Fill
                    <span v-if="sortKey === 'days_since_last_fill'" class="ml-1">{{ sortAsc ? '&#9650;' : '&#9660;' }}</span>
                    <span v-else class="ml-1 opacity-30 text-xs">&#8693;</span>
                  </th>
                  <th @click="sortBy('customer_full_name')" class="cursor-pointer select-none whitespace-nowrap w-[15%]"
                    :class="{ 'text-primary': sortKey === 'customer_full_name' }">
                    Customer
                    <span v-if="sortKey === 'customer_full_name'" class="ml-1">{{ sortAsc ? '&#9650;' : '&#9660;' }}</span>
                    <span v-else class="ml-1 opacity-30 text-xs">&#8693;</span>
                  </th>
                  <th @click="sortBy('house_factor')" class="cursor-pointer select-none whitespace-nowrap w-[8%]"
                    :class="{ 'text-primary': sortKey === 'house_factor' }">
                    Usage
                    <span v-if="sortKey === 'house_factor'" class="ml-1">{{ sortAsc ? '&#9650;' : '&#9660;' }}</span>
                    <span v-else class="ml-1 opacity-30 text-xs">&#8693;</span>
                  </th>
                  <th @click="sortBy('days_remaining')" class="cursor-pointer select-none whitespace-nowrap w-[8%]"
                    :class="{ 'text-primary': sortKey === 'days_remaining' }">
                    Days Left
                    <span v-if="sortKey === 'days_remaining'" class="ml-1">{{ sortAsc ? '&#9650;' : '&#9660;' }}</span>
                    <span v-else class="ml-1 opacity-30 text-xs">&#8693;</span>
                  </th>
                  <th @click="sortBy('hot_water_summer')" class="cursor-pointer select-none whitespace-nowrap w-[5%] hidden xl:table-cell"
                    :class="{ 'text-primary': sortKey === 'hot_water_summer' }">
                    HW Tank
                    <span v-if="sortKey === 'hot_water_summer'" class="ml-1">{{ sortAsc ? '&#9650;' : '&#9660;' }}</span>
                    <span v-else class="ml-1 opacity-30 text-xs">&#8693;</span>
                  </th>
                  <th class="w-auto">Address</th>
                  <th class="text-right w-[140px]">Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="oil in sortedDeliveries" :key="oil.id" class="table-row-hover"
                  :class="{ 'row-urgent': oil.auto_status == 3 }">
                  <td>
                    <div v-if="oil.last_fill === null" class="text-gray-500">New Auto</div>
                    <div v-else class="flex items-center gap-3">
                      <progress class="progress w-24" :value="oil.estimated_gallons_left" :max="oil.tank_size" :class="{
                        'progress-success': getTankLevelPercentage(oil) > 60,
                        'progress-warning': getTankLevelPercentage(oil) >= 25 && getTankLevelPercentage(oil) <= 60,
                        'progress-error': getTankLevelPercentage(oil) < 25
                      }"></progress>
                      <span class="font-mono text-xs">{{ oil.estimated_gallons_left }} / {{ oil.tank_size }} gal</span>
                    </div>
                  </td>
                  <td>{{ oil.days_since_last_fill }} days</td>
                  <td>
                    <router-link :to="{ name: 'customerProfile', params: { id: oil.customer_id } }"
                      class="group">
                      <div class="font-bold text-base group-hover:text-primary transition-colors truncate">
                        {{ oil.customer_full_name }}
                      </div>
                      <div class="text-xs font-mono opacity-60 flex items-center gap-1">
                        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3">
                          <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0zM4.501 20.118a7.5 7.5 0 0114.998 0A17.933 17.933 0 0112 21.75c-2.676 0-5.216-.584-7.499-1.632z" />
                        </svg>
                        #{{ oil.account_number }}
                      </div>
                    </router-link>
                  </td>
                  <td>
                    <span class="font-mono">{{ Number(oil.house_factor).toFixed(4) }}</span>
                  </td>
                  <td>
                    <div>
                      <span v-if="oil.days_remaining >= 999" class="text-base-content/40">N/A</span>
                      <span v-else class="font-bold" :class="{
                        'text-error': oil.days_remaining <= 7,
                        'text-warning': oil.days_remaining > 7 && oil.days_remaining <= 14,
                        'text-success': oil.days_remaining > 14
                      }">{{ oil.days_remaining }}d</span>
                      <div v-if="oil.gallons_per_day > 0" class="text-xs opacity-50">{{ oil.gallons_per_day }} gal/day</div>
                    </div>
                  </td>
                  <td class="hidden xl:table-cell">{{ oil.hot_water_summer ? 'Yes' : 'No' }}</td>
                  <td>
                    <div class="flex flex-col">
                      <span class="font-medium text-sm truncate" :title="oil.customer_address">{{ oil.customer_address }}</span>
                      <div class="flex items-center gap-1">
                        <span class="text-xs opacity-70 truncate">{{ oil.customer_town }}, {{ getStateAbbr(oil.customer_state) }} {{ oil.customer_zip }}</span>
                        <a :href="getMapLink(oil)" target="_blank"
                          class="btn btn-xs btn-circle btn-ghost text-base-content/60 hover:text-primary hover:bg-primary/10"
                          title="View on Google Maps">
                          <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M15 10.5a3 3 0 11-6 0 3 3 0 016 0z" />
                            <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 10.5c0 7.142-7.5 11.25-7.5 11.25S4.5 17.642 4.5 10.5a7.5 7.5 0 1115 0z" />
                          </svg>
                        </a>
                      </div>
                    </div>
                  </td>
                  <td class="text-right">
                    <div class="grid grid-cols-2 gap-1 justify-items-end">
                      <router-link v-if="oil.auto_status != 3" :to="{ name: 'payAutoAuthorize', params: { id: oil['id'] } }" class="btn btn-xs btn-warning btn-outline w-full">Auth</router-link>
                      <router-link v-if="oil.auto_status == 3" :to="{ name: 'finalizeTicketAuto', params: { id: oil.open_ticket_id || oil['id'] } }" class="btn btn-xs btn-accent btn-outline w-full">Final</router-link>
                      <router-link v-else :to="{ name: 'finalizeTicketAutoNocc', params: { id: oil['id'] } }" class="btn btn-xs btn-accent btn-outline w-full">Final</router-link>
                      <router-link :to="{ name: 'TicketAuto', params: { id: oil['id'] } }" class="btn btn-xs btn-success btn-outline w-full">Print</router-link>
                      <router-link :to="{ name: 'customerEdit', params: { id: oil.customer_id } }" class="btn btn-xs btn-info btn-outline w-full">Edit</router-link>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- MOBILE VIEW: Cards -->
          <div class="lg:hidden space-y-4 px-4 pb-4">
            <div v-for="oil in sortedDeliveries" :key="oil.id" class="mobile-card"
              :class="{ 'mobile-card-urgent': oil.auto_status == 3 }">
              <div class="p-3">
                <div class="flex justify-between items-start">
                  <div>
                    <h2 class="text-base font-bold">{{ oil.customer_full_name }}</h2>
                    <div class="flex items-start gap-1 mt-1">
                      <a :href="getMapLink(oil)" target="_blank" class="text-primary mt-0.5" title="View on Map">
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="w-3 h-3">
                          <path fill-rule="evenodd"
                            d="M9.69 18.933l.003.001C9.89 19.02 10 19 10 19s.11.02.308-.066l.002-.001.006-.003.018-.008a5.741 5.741 0 00.281-.14c.186-.096.446-.24.757-.433.62-.384 1.445-.966 2.274-1.765C15.302 14.988 17 12.493 17 9A7 7 0 103 9c0 3.492 1.698 5.988 3.355 7.584a13.731 13.731 0 002.273 1.765 11.842 11.842 0 00.976.544l.062.029.018.008.006.003zM10 11.25a2.25 2.25 0 100-4.5 2.25 2.25 0 000 4.5z"
                            clip-rule="evenodd" />
                        </svg>
                      </a>
                      <p class="text-xs text-base-content/60">{{ formatAddressStr(oil) }}</p>
                    </div>
                  </div>
                  <div class="text-right">
                    <div class="font-bold">{{ oil.days_since_last_fill }}</div>
                    <div class="text-xs text-base-content/60">days ago</div>
                  </div>
                </div>

                <div class="mt-4">
                  <div class="grid grid-cols-2 gap-4">
                    <div>
                      <p class="text-xs text-base-content/50">Usage Factor</p>
                      <div class="text-sm font-medium font-mono">{{ Number(oil.house_factor).toFixed(4) }}</div>
                    </div>
                    <div>
                      <p class="text-xs text-base-content/50">Hot Water Tank</p>
                      <div class="text-sm font-medium">{{ oil.hot_water_summer ? 'Yes' : 'No' }}</div>
                    </div>
                    <div>
                      <p class="text-xs text-base-content/50">Days Remaining</p>
                      <div v-if="oil.days_remaining >= 999" class="text-sm text-base-content/40">N/A</div>
                      <div v-else class="text-sm font-bold" :class="{
                        'text-error': oil.days_remaining <= 7,
                        'text-warning': oil.days_remaining > 7 && oil.days_remaining <= 14,
                        'text-success': oil.days_remaining > 14
                      }">{{ oil.days_remaining }} days</div>
                    </div>
                  </div>
                  <div class="mt-4">
                    <p class="text-xs text-base-content/50 mb-1">Tank Level</p>
                    <div v-if="oil.last_fill === null" class="text-gray-500 text-sm">New Auto Customer</div>
                    <div v-else>
                      <progress class="progress w-full" :value="oil.estimated_gallons_left" :max="oil.tank_size" :class="{
                        'progress-success': getTankLevelPercentage(oil) > 60,
                        'progress-warning': getTankLevelPercentage(oil) >= 25 && getTankLevelPercentage(oil) <= 60,
                        'progress-error': getTankLevelPercentage(oil) < 25
                      }"></progress>
                      <div class="text-xs text-base-content/60 text-right mt-1">{{ oil.estimated_gallons_left }} / {{
                        oil.tank_size
                        }} gal estimated</div>
                    </div>
                  </div>
                </div>

                <div class="flex gap-2 pt-3 mt-3 border-t border-base-content/10 flex-wrap">
                  <router-link :to="{ name: 'customerEdit', params: { id: oil.customer_id } }"
                    class="btn btn-sm btn-info btn-outline flex-1">Edit</router-link>
                  <router-link v-if="oil.auto_status != 3" :to="{ name: 'payAutoAuthorize', params: { id: oil['id'] } }"
                    class="flex-1">
                    <button class="btn btn-warning btn-sm btn-outline w-full">Auth</button>
                  </router-link>
                  <router-link :to="{ name: 'finalizeTicketAutoNocc', params: { id: oil['id'] } }" class="flex-1">
                    <button class="btn btn-accent btn-sm btn-outline w-full">Finalize</button>
                  </router-link>
                  <router-link v-if="oil.auto_status == 3"
                    :to="{ name: 'finalizeTicketAuto', params: { id: oil.open_ticket_id || oil['id'] } }"
                    class="flex-1">
                    <button class="btn btn-accent btn-sm btn-outline w-full">Finalize</button>
                  </router-link>
                  <router-link :to="{ name: 'TicketAuto', params: { id: oil['id'] } }" class="flex-1">
                    <button class="btn btn-success btn-sm btn-outline w-full">Ticket</button>
                  </router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import { AutoDelivery } from '../../types/models'
import { formatAddress, getGoogleMapsLink } from '../../utils/addressUtils'

// Reactive data
const user = ref(null)
const deliveries = ref<AutoDelivery[]>([])
// --- NEW: Data properties for sorting ---
const sortKey = ref<'tank_level_percent' | 'hot_water_summer' | 'confidence_score' | 'days_remaining' | keyof AutoDelivery>('tank_level_percent')
const sortAsc = ref(true)
const searchQuery = ref('')

// Computed: urgent count (<=7 days remaining)
const urgentCount = computed((): number => {
  return deliveries.value.filter(d => d.days_remaining != null && d.days_remaining <= 7 && d.days_remaining < 999).length
})

// Computed property to handle sorting AND searching
const sortedDeliveries = computed((): AutoDelivery[] => {
  // First, filter by search query
  let filtered = deliveries.value;

  if (searchQuery.value && searchQuery.value.trim() !== '') {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(item => {
      const name = item.customer_full_name?.toLowerCase() || '';
      const town = item.customer_town?.toLowerCase() || '';
      const addr = item.customer_address?.toLowerCase() || '';
      return name.includes(query) || town.includes(query) || addr.includes(query);
    });
  }

  // Create a copy to avoid mutating the original array
  const sorted = [...filtered];

  sorted.sort((a, b) => {
    // First, prioritize auto_status = 3 to be at the top
    if (a.auto_status === 3 && b.auto_status !== 3) {
      return -1;
    }
    if (a.auto_status !== 3 && b.auto_status === 3) {
      return 1;
    }

    // Then sort by the selected key
    let valA: any;
    let valB: any;

    // Special case for our calculated percentage
    if (sortKey.value === 'tank_level_percent') {
      valA = getTankLevelPercentage(a);
      valB = getTankLevelPercentage(b);
    } else {
      valA = a[sortKey.value as keyof AutoDelivery];
      valB = b[sortKey.value as keyof AutoDelivery];
      if (sortKey.value === 'hot_water_summer') {
        valA = valA || 0;
        valB = valB || 0;
      }
    }

    // Handle nulls or different types if necessary
    if (valA === null || valA === undefined) return 1;
    if (valB === null || valB === undefined) return -1;

    // Comparison logic
    if (valA < valB) {
      return sortAsc.value ? -1 : 1;
    }
    if (valA > valB) {
      return sortAsc.value ? 1 : -1;
    }
    return 0;
  });

  return sorted;
})

// State abbreviation mapping
const STATE_ABBR_MAP: { [key: number]: string } = {
  0: 'MA', 1: 'RI', 2: 'NH', 3: 'ME', 4: 'VT', 5: 'CT', 6: 'NY', 7: 'NJ',
  8: 'PA', 9: 'DE', 10: 'MD', 11: 'DC', 12: 'VA', 13: 'WV', 14: 'NC',
  15: 'SC', 16: 'GA', 17: 'FL', 18: 'AL', 19: 'MS', 20: 'TN', 21: 'KY',
  22: 'OH', 23: 'IN', 24: 'MI', 25: 'IL', 26: 'WI', 27: 'MN', 28: 'IA',
  29: 'MO', 30: 'AR', 31: 'LA', 32: 'TX', 33: 'OK', 34: 'KS', 35: 'NE',
  36: 'SD', 37: 'ND', 38: 'MT', 39: 'WY', 40: 'CO', 41: 'NM', 42: 'AZ',
  43: 'UT', 44: 'NV', 45: 'ID', 46: 'WA', 47: 'OR', 48: 'CA', 49: 'AK', 50: 'HI'
}

const getStateAbbr = (stateId: number | string): string => {
  const id = typeof stateId === 'string' ? parseInt(stateId) : stateId;
  return STATE_ABBR_MAP[id] || 'MA';
}

// Lifecycle
onMounted(() => {
  userStatus();
  get_oil_orders();
})

// Functions
const sortBy = (key: keyof AutoDelivery | 'tank_level_percent' | 'hot_water_summer' | 'confidence_score' | 'days_remaining') => {
  if (sortKey.value === key) {
    sortAsc.value = !sortAsc.value;
  } else {
    sortKey.value = key;
    sortAsc.value = true;
  }
}

const getTankLevelPercentage = (oil: AutoDelivery): number => {
  if (!oil.tank_size || oil.tank_size === 0 || oil.last_fill === null) {
    return 0;
  }
  return (oil.estimated_gallons_left / oil.tank_size) * 100;
}

const getConfidenceBadge = (score: number | null | undefined): string => {
  const s = score ?? 20
  if (s >= 70) return 'badge-success'
  if (s >= 40) return 'badge-warning'
  return 'badge-error'
}

const formatAddressStr = (oil: AutoDelivery): string => {
  return formatAddress(oil.customer_address, oil.customer_town, oil.customer_state, oil.customer_zip);
}

const getMapLink = (oil: AutoDelivery): string => {
  return getGoogleMapsLink(oil.customer_address, oil.customer_town, oil.customer_state, oil.customer_zip);
}

const userStatus = () => {
  const path = import.meta.env.VITE_BASE_URL + '/auth/whoami';
  axios.get(path, { withCredentials: true, headers: authHeader() })
    .then((response: any) => {
      if (response.data.ok) {
        user.value = response.data.user;
      }
    })
    .catch(() => {
      user.value = null;
    });
}

const get_oil_orders = () => {
  const path = import.meta.env.VITE_AUTO_URL + '/delivery/all/customers';
  axios.get(path, { withCredentials: true, headers: authHeader() })
    .then((response: any) => {
      deliveries.value = response.data;
    })
    .catch((error: any) => {
      console.error("Failed to fetch automatic deliveries:", error);
    });
}
</script>
