<!-- src/pages/delivery/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>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="M8.25 18.75a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h6m-9 0H3.375a1.125 1.125 0 01-1.125-1.125V14.25m17.25 4.5a1.5 1.5 0 01-3 0m3 0a1.5 1.5 0 00-3 0m3 0h1.125c.621 0 1.129-.504 1.09-1.124a17.902 17.902 0 00-3.213-9.193 2.056 2.056 0 00-1.58-.86H14.25M16.5 18.75h-2.25m0-11.177v-.958c0-.568-.422-1.048-.987-1.106a48.554 48.554 0 00-10.026 0 1.106 1.106 0 00-.987 1.106v7.635m12-6.677v6.677m0 4.5v-4.5m0 0h-12" />
              </svg>
            </div>
            Delivery Overview
          </h1>
          <p class="text-base-content/60 mt-1 ml-13">Recent delivery activity</p>
        </div>

        <!-- Quick Stats -->
        <div class="flex flex-wrap gap-3">
          <div class="stat-pill">
            <span class="stat-pill-value">{{ delivery_count }}</span>
            <span class="stat-pill-label">Total Today</span>
          </div>
          <div class="stat-pill stat-pill-success">
            <span class="stat-pill-value">{{ delivery_count_delivered }}</span>
            <span class="stat-pill-label">Delivered</span>
          </div>
        </div>
      </div>

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



        <!-- DESKTOP VIEW: Table -->
        <div class="hidden xl:block overflow-x-auto">
          <table class="modern-table">
            <thead>
              <tr>
                <th>Delivery #</th>
                <th>Name</th>
                <th>Status</th>
                <th>Town / Address</th>
                <th>Gallons</th>
                <th>Date</th>
                <th>Options</th>
                <th>Payment</th>
                <th class="text-right">Actions</th>
              </tr>
            </thead>
            <tbody>
              <template v-for="oil in deliveries" :key="oil.id">
              <tr v-if="oil.id" class="hover:bg-blue-600 hover:text-white">
                <td>{{ oil.id }}</td>
                <td>
                  <router-link v-if="oil.customer_id" :to="{ name: 'customerProfile', params: { id: oil.customer_id } }" class="link link-hover">
                    {{ oil.customer_name }}
                  </router-link>
                  <span v-else>{{ oil.customer_name }}</span>
                </td>
                <td>
                  <span class="badge badge-sm" :class="{
                    'badge-warning': oil.delivery_status === computedDELIVERY_STATUS.WAITING,
                    'badge-success': [computedDELIVERY_STATUS.DELIVERED, computedDELIVERY_STATUS.FINALIZED].includes(oil.delivery_status as any),
                    'badge-info': oil.delivery_status === computedDELIVERY_STATUS.OUT_FOR_DELIVERY,
                    'badge-error': [computedDELIVERY_STATUS.TOMORROW, computedDELIVERY_STATUS.ISSUE].includes(oil.delivery_status as any),
                  }">
                    <span v-if="oil.delivery_status === computedDELIVERY_STATUS.WAITING">Waiting</span>
                    <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.CANCELLED">Cancelled</span>
                    <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.OUT_FOR_DELIVERY">Today</span>
                    <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.TOMORROW">Tomorrow_Delivery</span>
                    <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.PARTIAL_DELIVERY">Partial_Delivery</span>
                    <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.ISSUE">Issue</span>
                    <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.FINALIZED">Finalized</span>
                  </span>
                </td>
                <td>
                  <div>{{ oil.customer_town }}</div>
                  <div class="text-xs opacity-70">{{ oil.customer_address }}</div>
                </td>
                <td>
                  <span v-if="oil.customer_asked_for_fill == 1" class="badge badge-info text-lg h-auto py-1">FILL</span>
                  <span v-else class="text-success font-mono font-bold">{{ oil.gallons_ordered }} gal</span>
                </td>
                <td class="text-sm">{{ oil.expected_delivery_date }}</td>
                <td>
                  <div class="flex flex-col gap-1">
                    <span v-if="oil.prime" class="badge badge-error badge-xs">PRIME</span>
                    <span v-if="oil.same_day" class="badge badge-error badge-xs">SAME DAY</span>
                    <span v-if="oil.emergency" class="badge badge-error badge-xs">EMERGENCY</span>
                  </div>
                </td>
                <td class="text-sm">
                  <span v-if="oil.payment_type == 0">Cash</span>
                  <span v-else-if="oil.payment_type == 1">CC</span>
                  <span v-else-if="oil.payment_type == 2">Cash/CC</span>
                  <span v-else-if="oil.payment_type == 3">Check</span>
                  <span v-else-if="oil.payment_type == 4">Other</span>
                </td>
                <td class="text-right">
                  <div class="flex items-center justify-end gap-1">
                    <router-link :to="{ name: 'deliveryOrder', params: { id: oil.id } }" class="btn btn-xs btn-neutral btn-outline">View</router-link>
                    <router-link :to="{ name: 'deliveryEdit', params: { id: oil.id } }" class="btn btn-xs btn-info btn-outline">Edit</router-link>
                    <router-link :to="{ name: 'finalizeTicket', params: { id: oil.id } }" v-if="!isFinalizedStatus(oil.delivery_status)" class="btn btn-xs btn-accent btn-outline">Finalize</router-link>
                    <router-link :to="{ name: 'Ticket', params: { id: oil.id } }" class="btn btn-xs btn-success btn-outline">Print</router-link>
                  </div>
                </td>
              </tr>
              </template>
            </tbody>
          </table>
        </div>

        <!-- MOBILE VIEW: Cards -->
        <div class="xl:hidden space-y-4">
          <template v-for="oil in deliveries" :key="oil.id">
          <div 
            v-if="oil.id" 
            class="mobile-card"
            :class="{ 
              'mobile-card-urgent': oil.emergency, 
              'mobile-card-prime': oil.prime && !oil.emergency,
              'mobile-card-sameday': oil.same_day && !oil.prime && !oil.emergency
            }"
          >
            <div class="p-3">
              <div class="flex justify-between items-start">
                <div>
                  <h2 class="text-base font-bold">{{ oil.customer_name }}</h2>
                  <p class="text-xs text-base-content/60">Delivery #{{ oil.id }}</p>
                </div>
                <div class="badge badge-sm" :class="{
                  'badge-warning': oil.delivery_status === computedDELIVERY_STATUS.WAITING,
                  'badge-success': [computedDELIVERY_STATUS.DELIVERED, computedDELIVERY_STATUS.FINALIZED].includes(oil.delivery_status as any),
                  'badge-info': oil.delivery_status === computedDELIVERY_STATUS.OUT_FOR_DELIVERY,
                  'badge-error': [computedDELIVERY_STATUS.TOMORROW, computedDELIVERY_STATUS.ISSUE].includes(oil.delivery_status as any),
                }">
                  <span v-if="oil.delivery_status === computedDELIVERY_STATUS.WAITING">Waiting</span>
                  <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.DELIVERED">Delivered</span>
                  <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.OUT_FOR_DELIVERY">Today</span>
                  <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.TOMORROW">Tomorrow</span>
                  <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.PARTIAL_DELIVERY">Partial</span>
                  <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.ISSUE">Issue</span>
                  <span v-else-if="oil.delivery_status === computedDELIVERY_STATUS.FINALIZED">Finalized</span>
                </div>
              </div>

              <div class="flex gap-2 mt-2">
                <div v-if="oil.prime" class="badge badge-error badge-sm">PRIME</div>
                <div v-if="oil.same_day" class="badge badge-error badge-sm">SAME DAY</div>
                <div v-if="oil.emergency" class="badge badge-error badge-sm">EMERGENCY</div>
              </div>

              <div class="text-sm mt-3 grid grid-cols-2 gap-x-4 gap-y-2">
                <div>
                   <p class="text-xs text-base-content/50">Address</p>
                   <p class="font-medium">{{ oil.customer_address }}</p>
                   <p class="text-xs">{{ oil.customer_town }}</p>
                </div>
                <div>
                   <p class="text-xs text-base-content/50">Gallons</p>
                   <p class="font-bold text-success">
                     <span v-if="oil.customer_asked_for_fill" class="badge badge-info badge-xs">FILL</span>
                     <span v-else>{{ oil.gallons_ordered }}</span>
                   </p>
                </div>
                <div>
                    <p class="text-xs text-base-content/50">Date</p>
                    <p class="font-medium">{{ oil.expected_delivery_date }}</p>
                 </div>
              </div>
              
              <div class="flex gap-2 pt-3 mt-3 border-t border-base-content/10 flex-wrap">
                 <router-link :to="{ name: 'deliveryOrder', params: { id: oil.id } }" class="btn btn-sm btn-ghost flex-1">View</router-link>
                 <router-link :to="{ name: 'deliveryEdit', params: { id: oil.id } }" class="btn btn-sm btn-info btn-outline flex-1">Edit</router-link>
                 <router-link :to="{ name: 'finalizeTicket', params: { id: oil.id } }" v-if="!isFinalizedStatus(oil.delivery_status)" class="btn btn-sm btn-accent btn-outline flex-1">Finalize</router-link>
                 <router-link :to="{ name: 'Ticket', params: { id: oil.id } }" class="btn btn-sm btn-success btn-outline flex-1">Print</router-link>
              </div>
            </div>
          </div>
          </template>
        </div>
      </div>

      <!-- Pagination -->
      <div class="mt-6 flex justify-center">
        <pagination @paginate="getPage" :records="recordsLength" v-model="page" :per-page="25" :options="options">
        </pagination>
      </div>

    </div>
  </div>
  
</template>


<script setup lang="ts">
import { ref, onMounted, computed, markRaw } from 'vue'
import { deliveryService } from '../../services/deliveryService'
import { Delivery } from '../../types/models'
import { DELIVERY_STATUS, DeliveryStatusType } from '../../constants/status';
import PaginationComp from '../../components/pagination.vue'
import SideBar from '../../layouts/sidebar/sidebar.vue'
import { notify } from "@kyvg/vue3-notification";
import authService from '../../services/authService';
import adminService from '../../services/adminService';

// Reactive data
const delivery_count = ref(0)
const delivery_count_delivered = ref(0)
const user = ref(null)
const deliveries = ref<Delivery[]>([])
const page = ref(1)
const perPage = ref(50)
const recordsLength = ref(0)
const options = ref({
  edgeNavigation: false,
  format: false,
  template: markRaw(PaginationComp)
})

// Computed
const computedDELIVERY_STATUS = computed(() => DELIVERY_STATUS)

// Functions
const isDeliveredStatus = (status: DeliveryStatusType): boolean => {
  return status === DELIVERY_STATUS.DELIVERED || status === 1; // Support both old (1) and new (11) values
}

const isFinalizedStatus = (status: DeliveryStatusType): boolean => {
  return status === DELIVERY_STATUS.FINALIZED;
}

const getPage = (pageVal: any) => {
  deliveries.value = [];
  get_oil_orders(pageVal)
}

const userStatus = async () => {
    try {
        const response = await authService.whoami();
        if (response.data.ok) {
            user.value = response.data.user;
        }
    } catch (error) {
        user.value = null;
    }
}

const get_oil_orders = async (pageVal: number) => {
  try {
    const response = await deliveryService.getAll(pageVal)
    deliveries.value = response.data?.deliveries || response.data || []
    // Assuming backend might not return total count in this endpoint, 
    // but if it did, we'd update recordsLength.
    // Pagination usually needs total records count. 
    // If getAll returns generic list, pagination might be limited.
  } catch (error) {
    console.error('Error fetching deliveries:', error)
    deliveries.value = []
  }
}

const deleteCall = async (delivery_id: any) => {
  try {
      const response = await deliveryService.delete(delivery_id);
      if (response.data.ok) {
          notify({
              title: "Success",
              text: "deleted delivery",
              type: "success",
          });
          getPage(page.value)
      } else {
          notify({
              title: "Failure",
              text: "error deleting delivery",
              type: "success", // Keeping original notification type although "error" might be better
          });
      }
  } catch (error) {
       notify({
        title: "Failure",
        text: "error deleting delivery",
        type: "error", // Changing to error type for catch block
      });
  }
}

const today_delivery_count = async () => {
    try {
        const response = await adminService.stats.deliveryCountToday();
        delivery_count.value = response.data.data;
    } catch (error) {
        console.error("Error fetching today's delivery count", error);
    }
}

const today_delivery_delivered = async () => {
    try {
        const response = await adminService.stats.deliveredCountToday();
        delivery_count_delivered.value = response.data.data;
    } catch (error) {
        console.error("Error fetching today's delivered count", error);
    }
}

// Lifecycle
onMounted(() => {
  userStatus()
  getPage(page.value);
  today_delivery_count();
  today_delivery_delivered();
})
</script>

<style scoped>
/* Stat Pills */
.stat-pill {
  @apply flex items-center gap-2 px-4 py-2 rounded-xl bg-base-200/80 border border-base-content/5;
}
.stat-pill-value {
  @apply text-xl font-bold;
}
.stat-pill-label {
  @apply text-xs text-base-content/60 uppercase tracking-wider;
}
.stat-pill-success {
  @apply bg-success/10 border-success/20;
}
.stat-pill-success .stat-pill-value {
  @apply text-success;
}
.stat-pill-info {
  @apply bg-info/10 border-info/20;
}
.stat-pill-info .stat-pill-value {
  @apply text-info;
}

/* Town Chips */
.town-chip {
  @apply flex items-center gap-2 px-3 py-1.5 rounded-full bg-base-200 hover:bg-base-300 transition-all text-sm whitespace-nowrap cursor-pointer;
}
.town-chip-count {
  @apply px-2 py-0.5 rounded-full bg-base-content/10 text-xs font-mono;
}
.town-chip-active {
  @apply bg-primary text-primary-content;
}
.town-chip-active .town-chip-count {
  @apply bg-primary-content/20;
}
.town-chip-clear {
  @apply bg-error/10 text-error hover:bg-error/20;
}

/* Modern Table Card */
.modern-table-card {
  @apply bg-gradient-to-br from-neutral to-neutral/80 rounded-2xl shadow-xl border border-base-content/5 overflow-hidden;
}

/* Modern Table */
.modern-table {
  @apply w-full;
}
.modern-table thead {
  @apply bg-base-content/5;
}
.modern-table th {
  @apply px-4 py-3 text-left text-xs font-semibold uppercase tracking-wider text-base-content/60;
}
.modern-table td {
  @apply px-4 py-4;
}
.modern-table tbody tr {
  @apply border-t border-base-content/5;
}

/* Sort Header */
.sort-header {
  @apply flex items-center gap-1 hover:text-primary transition-colors cursor-pointer;
}

/* Table Row Hover */
.table-row-hover {
  @apply transition-all duration-200;
}
.table-row-hover:hover {
  @apply bg-primary/5;
}

/* Row urgency highlighting */
.row-urgent {
  @apply bg-error/5 border-l-4 border-l-error;
}
.row-urgent:hover {
  @apply bg-error/10;
}
.row-prime {
  @apply bg-warning/5 border-l-4 border-l-warning;
}
.row-prime:hover {
  @apply bg-warning/10;
}
.row-sameday {
  @apply bg-info/5 border-l-4 border-l-info;
}
.row-sameday:hover {
  @apply bg-info/10;
}

/* Status Badge */
.status-badge {
  @apply inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-medium;
}
.status-dot {
  @apply w-1.5 h-1.5 rounded-full;
}
.status-waiting {
  @apply bg-warning/10 text-warning;
}
.status-waiting .status-dot {
  @apply bg-warning animate-pulse;
}
.status-outfordelivery {
  @apply bg-info/10 text-info;
}
.status-outfordelivery .status-dot {
  @apply bg-info animate-pulse;
}
.status-finalized {
  @apply bg-success/10 text-success;
}
.status-finalized .status-dot {
  @apply bg-success;
}
.status-cancelled, .status-issue {
  @apply bg-error/10 text-error;
}
.status-cancelled .status-dot, .status-issue .status-dot {
  @apply bg-error;
}
.status-default {
  @apply bg-base-content/10 text-base-content/60;
}
.status-default .status-dot {
  @apply bg-base-content/40;
}

/* Special Tags */
.special-tag {
  @apply inline-flex items-center gap-1 px-2 py-0.5 rounded text-xs font-bold uppercase tracking-wide;
}
.tag-emergency {
  @apply bg-error text-error-content animate-pulse;
}
.tag-prime {
  @apply bg-warning text-warning-content;
}
.tag-sameday {
  @apply bg-info text-info-content;
}

/* Gallons Badge */
.gallons-badge {
  @apply text-success font-mono font-bold;
}
.gallons-fill {
  @apply bg-info/10 text-info border-info/20;
}

/* Action Buttons */
.action-btn {
  @apply p-2 rounded-lg hover:bg-base-content/10 transition-colors text-base-content/60 hover:text-base-content;
}
.action-btn-secondary {
  @apply hover:bg-secondary/20 hover:text-secondary;
}
.action-btn-accent {
  @apply hover:bg-accent/20 hover:text-accent;
}
.action-btn-success {
  @apply hover:bg-success/20 hover:text-success;
}

/* Mobile Cards */
.mobile-card {
  @apply bg-base-100/50 backdrop-blur-sm rounded-xl mb-4 shadow-sm border border-base-content/5;
}
.mobile-card-urgent {
  @apply border-l-4 border-l-error bg-error/5;
}
.mobile-card-prime {
  @apply border-l-4 border-l-warning bg-warning/5;
}
.mobile-card-sameday {
  @apply border-l-4 border-l-info bg-info/5;
}
</style>