<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>
      <h1 class="text-3xl font-bold mt-4">Automatic Deliveries</h1>

      <!-- Main Content Card -->
      <div class="bg-neutral rounded-lg p-4 sm:p-6 mt-6">
        <!-- Header -->
        <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-4">
          <h2 class="text-lg font-bold">Customers on Automatic Delivery</h2>
          <div class="badge badge-ghost">{{ deliveries.length }} customers found</div>
        </div>
        <div class="divider"></div>

        <!-- Data Display -->
        <div>
          <!-- DESKTOP VIEW: Sortable Table -->
          <div class="overflow-x-auto hidden xl:block">
            <table class="table w-full">
              <thead>
                <tr>
                  <!-- SORTABLE HEADERS -->
                  <th @click="sortBy('tank_level_percent')" class="cursor-pointer hover:text-white">Tank Level</th>
                  <th @click="sortBy('days_since_last_fill')" class="cursor-pointer hover:text-white">Days Since Fill</th>
                  <th @click="sortBy('customer_full_name')" class="cursor-pointer hover:text-white">Name</th>
                  <th>Address</th>
                  <th @click="sortBy('house_factor')" class="cursor-pointer hover:text-white">Usage Factor</th>
                  <th class="text-right">Actions</th>
                </tr>
              </thead>
              <tbody>
                <!-- Loop over the new 'sortedDeliveries' computed property -->
                <tr v-for="oil in sortedDeliveries" :key="oil.id" class="hover:bg-blue-600 hover:text-white">
                  <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="link link-hover">
                      {{ oil.customer_full_name }}
                    </router-link>
                  </td>
                  <td>{{ oil.customer_address }}, {{ oil.customer_town }}</td>
                  <td>{{ oil.house_factor }}</td>
                  <td class="text-right">
                    <div class="flex items-center justify-end gap-2">
                     <router-link :to="{ name: 'customerEdit', params: { id: oil.customer_id } }" class="btn btn-sm btn-secondary">Edit Customer</router-link>
                   <router-link :to="{ name: 'finalizeTicketAuto', params: { id: oil['id'] } }">
              <button class="btn btn-secondary btn-sm">Finalize</button>
            </router-link>
                   <router-link :to="{ name: 'TicketAuto', params: { id: oil['id'] } }">
              <button class="btn btn-success btn-sm">
                Print Ticket
              </button>
            </router-link>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- MOBILE VIEW: Cards -->
          <div class="xl:hidden space-y-4">
            <div v-for="oil in sortedDeliveries" :key="oil.id" class="card bg-base-100 shadow-md">
              <div class="card-body p-4">
                <div class="flex justify-between items-start">
                  <div>
                    <h2 class="card-title text-base">{{ oil.customer_full_name }}</h2>
                    <p class="text-xs text-gray-400">{{ oil.customer_address }}, {{ oil.customer_town }}</p>
                  </div>
                  <div class="text-right">
                    <div class="font-bold">{{ oil.days_since_last_fill }}</div>
                    <div class="text-xs text-gray-400">days ago</div>
                  </div>
                </div>

                <div class="mt-4">
                  <label class="label p-0 mb-1"><span class="label-text">Tank Level</span></label>
                  <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-gray-400 text-right">{{ oil.estimated_gallons_left }} / {{ oil.tank_size }} gal estimated</div>
                  </div>
                </div>
                
                <div class="card-actions justify-end flex-wrap gap-2 mt-4">
                  <router-link :to="{ name: 'customerEdit', params: { id: oil.customer_id } }" class="btn btn-sm btn-secondary">Edit Customer</router-link>
                   <router-link :to="{ name: 'finalizeTicketAuto', params: { id: oil['id'] } }">
              <button class="btn btn-secondary btn-sm">Finalize</button>
            </router-link>
                   <router-link :to="{ name: 'TicketAuto', params: { id: oil['id'] } }">
              <button class="btn btn-success btn-sm">
                Print Ticket
              </button>
            </router-link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <Footer />
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import axios from 'axios'
import authHeader from '../../services/auth.header'
import Footer from '../../layouts/footers/footer.vue'

// Define a type for the delivery object for better code quality
interface AutoDelivery {
  id: number;
  customer_id: number;
  last_fill: string | null;
  estimated_gallons_left: number;
  days_since_last_fill: number;
  customer_full_name: string;
  customer_address: string;
  customer_town: string;
  house_factor: number;
  tank_size: number;
}

export default defineComponent({
  name: 'AutomaticHome',
  components: {
    Footer,
  },
  data() {
    return {
      user: null,
      deliveries: [] as AutoDelivery[],
      // --- NEW: Data properties for sorting ---
      sortKey: 'estimated_gallons_left' as keyof AutoDelivery | 'tank_level_percent',
      sortAsc: true,
    }
  },
  computed: {
    // --- NEW: Computed property to handle sorting ---
    sortedDeliveries(): AutoDelivery[] {
      // Create a copy to avoid mutating the original array
      const sorted = [...this.deliveries];

      sorted.sort((a, b) => {
        let valA: any;
        let valB: any;

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

        // Handle nulls or different types if necessary
        if (valA === null) return 1;
        if (valB === null) return -1;
        
        // Comparison logic
        if (valA < valB) {
          return this.sortAsc ? -1 : 1;
        }
        if (valA > valB) {
          return this.sortAsc ? 1 : -1;
        }
        return 0;
      });

      return sorted;
    }
  },
  created() {
    this.userStatus();
    this.get_oil_orders();
  },
  methods: {
    // --- NEW: Method to handle sorting ---
    sortBy(key: keyof AutoDelivery | 'tank_level_percent') {
      if (this.sortKey === key) {
        // If clicking the same key, reverse the direction
        this.sortAsc = !this.sortAsc;
      } else {
        // If clicking a new key, set it and default to ascending
        this.sortKey = key;
        this.sortAsc = true;
      }
    },
    // --- NEW: Helper method for percentage calculation ---
    getTankLevelPercentage(oil: AutoDelivery): number {
      if (!oil.tank_size || oil.tank_size === 0 || oil.last_fill === null) {
        return 0; // Return 0 if tank size is invalid or it's a new customer
      }
      return (oil.estimated_gallons_left / oil.tank_size) * 100;
    },
    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) {
            this.user = response.data.user;
          }
        })
        .catch(() => {
          this.user = null;
        });
    },
    get_oil_orders() {
      const path = import.meta.env.VITE_AUTO_URL + '/delivery/all/customers';
      axios.get(path, { withCredentials: true, headers: authHeader() })
        .then((response: any) => {
          this.deliveries = response.data;
        })
        .catch((error: any) => {
          console.error("Failed to fetch automatic deliveries:", error);
        });
    },
  },
})
</script>