<template>
  <div class="min-h-screen bg-gray-50">
    <!-- Navbar -->
    <Navbar />

    <div class="max-w-7xl mx-auto px-4 py-8">
      <!-- Page Title -->
      <div class="mb-8">
        <h2 class="text-3xl font-bold text-gray-800 mb-2">My Orders</h2>
        <p class="text-gray-600">Track and manage your food orders</p>
      </div>

      <!-- Tabs -->
      <div class="bg-white rounded-xl shadow-sm mb-6">
        <div class="flex border-b border-gray-200">
          <button @click="activeTab = 'today'" :class="activeTab === 'today' ? 'border-b-2 border-orange-500 text-orange-600' : 'text-gray-600'" class="flex-1 px-6 py-4 font-semibold hover:text-orange-600 transition">
            Today's Orders
          </button>
          <button @click="activeTab = 'history'" :class="activeTab === 'history' ? 'border-b-2 border-orange-500 text-orange-600' : 'text-gray-600'" class="flex-1 px-6 py-4 font-semibold hover:text-orange-600 transition">
            Order History
          </button>
        </div>
      </div>

      <!-- Filters & Search -->
      <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
        <div class="flex flex-col md:flex-row gap-4">
          <!-- Search -->
          <div class="flex-1">
            <div class="relative">
              <svg class="w-5 h-5 absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <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>
              <input v-model="searchQuery" type="text" placeholder="Search orders by restaurant or order number..." class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
            </div>
          </div>

          <!-- Month Filter (History Tab) -->
          <div v-if="activeTab === 'history'" class="flex gap-2">
            <select v-model="selectedMonth" class="px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-transparent">
              <option value="current">This Month</option>
              <option value="last">Last Month</option>
              <option value="all">All Time</option>
            </select>
          </div>

          <!-- Status Filter (Today Tab) -->
          <div v-if="activeTab === 'today'" class="flex gap-2 overflow-x-auto pb-2 md:pb-0">
            <button @click="selectedStatus = ''" :class="selectedStatus === '' ? 'bg-orange-500 text-white' : 'bg-white text-gray-700 border border-gray-300'" class="px-4 py-3 rounded-lg font-medium whitespace-nowrap hover:bg-orange-50 transition">
              All Orders
            </button>
            <button @click="selectedStatus = 'pending'" :class="selectedStatus === 'pending' ? 'bg-yellow-500 text-white' : 'bg-white text-gray-700 border border-gray-300'" class="px-4 py-3 rounded-lg font-medium whitespace-nowrap hover:bg-yellow-50 transition">
              Pending
            </button>
            <button @click="selectedStatus = 'preparing'" :class="selectedStatus === 'preparing' ? 'bg-blue-500 text-white' : 'bg-white text-gray-700 border border-gray-300'" class="px-4 py-3 rounded-lg font-medium whitespace-nowrap hover:bg-blue-50 transition">
              Preparing
            </button>
            <button @click="selectedStatus = 'delivered'" :class="selectedStatus === 'delivered' ? 'bg-green-500 text-white' : 'bg-white text-gray-700 border border-gray-300'" class="px-4 py-3 rounded-lg font-medium whitespace-nowrap hover:bg-green-50 transition">
              Delivered
            </button>
            <button @click="selectedStatus = 'cancelled'" :class="selectedStatus === 'cancelled' ? 'bg-red-500 text-white' : 'bg-white text-gray-700 border border-gray-300'" class="px-4 py-3 rounded-lg font-medium whitespace-nowrap hover:bg-red-50 transition">
              Cancelled
            </button>
          </div>
        </div>
      </div>

      <!-- Orders List -->
      <div v-if="loading" class="text-center py-16">
        <svg class="animate-spin h-12 w-12 text-orange-600 mx-auto" fill="none" viewBox="0 0 24 24">
          <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
          <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
        </svg>
        <p class="text-gray-600 mt-4">Loading orders...</p>
      </div>

      <div v-else-if="filteredOrders.length === 0" class="bg-white rounded-xl shadow-sm p-12 text-center">
        <div class="text-6xl mb-4">📦</div>
        <h3 class="text-xl font-bold text-gray-800 mb-2">No orders found</h3>
        <p class="text-gray-600 mb-6">You haven't placed any orders yet or no orders match your filter.</p>
        <button @click="router.push('/')" class="bg-orange-600 text-white px-6 py-3 rounded-lg font-semibold hover:bg-orange-700 transition">
          Start Ordering
        </button>
      </div>

      <div v-else class="space-y-3">
        <div v-for="order in filteredOrders" :key="order.id" class="bg-white rounded-xl shadow-sm hover:shadow-lg transition overflow-hidden">
          <!-- Order Header -->
          <div class="p-4">
            <div class="flex items-center justify-between gap-4">
              <div class="flex items-center gap-3 flex-1">
                <div class="w-10 h-10 bg-orange-100 rounded-lg flex items-center justify-center text-lg flex-shrink-0">
                  🍽️
                </div>
                <div class="flex-1 min-w-0">
                  <div class="flex items-center gap-2">
                    <h3 class="text-sm font-bold text-gray-800 truncate">{{ order.restaurant_name }}</h3>
                    <span class="text-xs px-2 py-0.5 rounded-full font-semibold whitespace-nowrap" :class="getStatusClass(order.status)">
                      {{ formatStatus(order.status) }}
                    </span>
                  </div>
                  <p class="text-xs text-gray-600">{{ order.order_number }} • {{ formatDate(order.created_at) }}</p>
                </div>
              </div>

              <div class="flex items-center gap-3">
                <div class="text-right">
                  <p class="text-sm font-bold text-orange-600">Rs {{ order.total }}</p>
                </div>
                <div class="flex items-center gap-1.5">
                  <button v-if="order.status === 'delivered' && !order.rating" @click.stop="rateOrder(order)" class="p-1.5 bg-yellow-500 text-white rounded-lg hover:bg-yellow-600 transition" title="Rate Order">
                    <svg class="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                      <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
                    </svg>
                  </button>
                  
                  <button v-if="order.status === 'delivered'" @click.stop="reorder(order)" class="p-1.5 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition" title="Reorder">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                    </svg>
                  </button>

                  <button v-if="order.status === 'pending'" @click.stop="openCancelModal(order.id)" class="p-1.5 bg-red-600 text-white rounded-lg hover:bg-red-700 transition" title="Cancel Order">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                    </svg>
                  </button>

                  <button @click.stop="showHelpModal(order)" class="p-1.5 border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition" title="Help">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.228 9c.549-1.165 2.03-2 3.772-2 2.21 0 4 1.343 4 3 0 1.4-1.278 2.575-3.006 2.907-.542.104-.994.54-.994 1.093m0 3h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                  </button>

                  <button @click="toggleOrderDetails(order.id)" class="p-1.5 hover:bg-gray-100 rounded-lg transition">
                    <svg class="w-4 h-4 text-gray-600 transition-transform" :class="{ 'rotate-180': expandedOrder === order.id }" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                    </svg>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- Order Progress -->
          <div v-if="order.status !== 'cancelled'" class="px-6 py-4 bg-gray-50">
            <div class="flex items-center justify-between relative">
              <!-- Progress Line -->
              <div class="absolute top-5 left-0 right-0 h-1 bg-gray-200">
                <div class="h-full bg-orange-500 transition-all duration-500" :style="{ width: getProgressWidth(order.status) }"></div>
              </div>

              <!-- Steps -->
              <div v-for="step in orderSteps" :key="step.status" class="flex flex-col items-center relative z-10">
                <div class="w-10 h-10 rounded-full flex items-center justify-center mb-2 transition-all" :class="isStepCompleted(order.status, step.status) ? 'bg-orange-500 text-white' : 'bg-white border-2 border-gray-300 text-gray-400'">
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" :d="step.icon"/>
                  </svg>
                </div>
                <span class="text-xs font-medium text-gray-600 text-center hidden md:block">{{ step.label }}</span>
              </div>
            </div>
          </div>

          <!-- Order Details (Expandable) -->
          <div v-if="expandedOrder === order.id" class="p-6 border-t border-gray-100">
            <!-- Order Items -->
            <div class="mb-6">
              <h4 class="font-bold text-gray-800 mb-3 flex items-center gap-2">
                <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
                </svg>
                Order Items
              </h4>
              <div class="space-y-3">
                <div v-for="item in order.items" :key="item.id" class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                  <div class="flex items-center gap-3">
                    <div class="w-12 h-12 bg-white rounded-lg flex items-center justify-center text-xl">
                      🍕
                    </div>
                    <div>
                      <p class="font-semibold text-gray-800">{{ item.product_name }}</p>
                      <p class="text-sm text-gray-600">Qty: {{ item.quantity }}</p>
                    </div>
                  </div>
                  <p class="font-bold text-gray-800">Rs {{ item.total_price }}</p>
                </div>
              </div>
            </div>

            <!-- Delivery Info -->
            <div class="mb-6">
              <h4 class="font-bold text-gray-800 mb-3 flex items-center gap-2">
                <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"/>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"/>
                </svg>
                Delivery Details
              </h4>
              <div class="space-y-3">
                <div class="p-4 bg-gray-50 rounded-lg">
                  <p class="text-sm text-gray-500 mb-1">Address</p>
                  <p class="text-gray-800 font-medium">{{ order.delivery_address }}</p>
                </div>
                <div class="flex gap-3">
                  <div class="flex-1 p-4 bg-gray-50 rounded-lg">
                    <p class="text-sm text-gray-500 mb-1">Phone</p>
                    <p class="text-gray-800 font-medium">{{ order.delivery_phone }}</p>
                  </div>
                  <div v-if="order.distance_km" class="flex-1 p-4 bg-gray-50 rounded-lg">
                    <p class="text-sm text-gray-500 mb-1">Distance</p>
                    <p class="text-gray-800 font-medium">{{ order.distance_km }} km</p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Price Breakdown -->
            <div class="mb-6">
              <h4 class="font-bold text-gray-800 mb-3 flex items-center gap-2">
                <svg class="w-5 h-5 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z"/>
                </svg>
                Price Breakdown
              </h4>
              <div class="space-y-2 p-4 bg-gray-50 rounded-lg">
                <div class="flex justify-between text-gray-700">
                  <span>Subtotal</span>
                  <span>Rs {{ order.subtotal }}</span>
                </div>
                <div class="flex justify-between text-gray-700">
                  <span>Delivery Fee</span>
                  <span>Rs {{ order.delivery_fee }}</span>
                </div>
                <div v-if="order.discount > 0" class="flex justify-between text-green-600">
                  <span>Discount</span>
                  <span>- Rs {{ order.discount }}</span>
                </div>
                <div class="border-t border-gray-300 pt-2 mt-2 flex justify-between font-bold text-lg text-gray-800">
                  <span>Total</span>
                  <span class="text-orange-600">Rs {{ order.total }}</span>
                </div>
              </div>
            </div>


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

    <!-- Rating Modal -->
    <div v-if="ratingModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4" @click="ratingModal = null">
      <div class="bg-white rounded-xl w-full max-w-md" @click.stop>
        <div class="bg-yellow-500 text-white p-6">
          <h2 class="text-2xl font-bold">Rate Your Order</h2>
        </div>
        <div class="p-6">
          <p class="text-gray-700 mb-4">How was your experience with {{ ratingModal.restaurant_name }}?</p>
          <div class="flex justify-center gap-2 mb-6">
            <button v-for="i in 5" :key="i" @click="selectedRating = i" class="text-4xl transition-transform hover:scale-110">
              {{ i <= selectedRating ? '⭐' : '☆' }}
            </button>
          </div>
          <textarea v-model="ratingComment" rows="3" placeholder="Add a comment (optional)" class="w-full px-4 py-2 border rounded-lg mb-4"></textarea>
          <div class="flex gap-3">
            <button @click="submitRating" :disabled="!selectedRating" class="flex-1 bg-yellow-500 text-white py-3 rounded-lg font-semibold hover:bg-yellow-600 disabled:opacity-50">
              Submit Rating
            </button>
            <button @click="ratingModal = null" class="px-6 py-3 border rounded-lg font-semibold hover:bg-gray-50">
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Help Modal -->
    <div v-if="helpModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4" @click="helpModal = null">
      <div class="bg-white rounded-xl w-full max-w-md" @click.stop>
        <div class="bg-blue-600 text-white p-6">
          <h2 class="text-2xl font-bold">Need Help?</h2>
        </div>
        <div class="p-6">
          <p class="text-gray-700 mb-4">Send a message to support regarding Order #{{ helpModal.order_number }}</p>
          <textarea v-model="helpMessage" rows="4" placeholder="Describe your issue..." class="w-full px-4 py-2 border rounded-lg mb-4"></textarea>
          <div class="flex gap-3">
            <button @click="submitHelp" :disabled="!helpMessage" class="flex-1 bg-blue-600 text-white py-3 rounded-lg font-semibold hover:bg-blue-700 disabled:opacity-50">
              Send Message
            </button>
            <button @click="helpModal = null" class="px-6 py-3 border rounded-lg font-semibold hover:bg-gray-50">
              Cancel
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Cancel Modal -->
    <div v-if="showCancelModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4">
      <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6">
        <h3 class="text-xl font-bold text-gray-800 mb-4">Cancel Order</h3>
        <p class="text-gray-600 mb-4">Please provide a reason for cancellation (minimum 10 characters):</p>
        <textarea v-model="cancelReason" rows="4" class="w-full border border-gray-300 rounded-xl p-3 focus:ring-2 focus:ring-orange-500 focus:border-transparent" placeholder="Enter cancellation reason..."></textarea>
        <p class="text-xs text-gray-500 mt-2">{{ cancelReason.length }}/500 characters</p>
        <div class="flex gap-3 mt-6">
          <button @click="showCancelModal = false; cancelReason = ''" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 py-3 rounded-xl font-semibold transition">Close</button>
          <button @click="confirmCancel" :disabled="!cancelReason || cancelReason.length < 10" class="flex-1 bg-orange-500 hover:bg-orange-600 text-white py-3 rounded-xl font-semibold transition disabled:opacity-50 disabled:cursor-not-allowed">
            Next
          </button>
        </div>
      </div>
    </div>

    <!-- Confirmation Modal -->
    <div v-if="showConfirmModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[9999] p-4">
      <div class="bg-white rounded-2xl shadow-2xl max-w-md w-full p-6">
        <div class="flex items-center justify-center w-16 h-16 bg-red-100 rounded-full mx-auto mb-4">
          <svg class="w-8 h-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
          </svg>
        </div>
        <h3 class="text-xl font-bold text-gray-800 text-center mb-2">Confirm Cancellation</h3>
        <p class="text-gray-600 text-center mb-6">Are you sure you want to cancel this order? This action cannot be undone.</p>
        <div class="flex gap-3">
          <button @click="showConfirmModal = false; showCancelModal = true" class="flex-1 bg-gray-200 hover:bg-gray-300 text-gray-800 py-3 rounded-xl font-semibold transition">Go Back</button>
          <button @click="cancelOrder" :disabled="cancelling" class="flex-1 bg-red-500 hover:bg-red-600 text-white py-3 rounded-xl font-semibold transition disabled:opacity-50 disabled:cursor-not-allowed">
            {{ cancelling ? 'Cancelling...' : 'Yes, Cancel Order' }}
          </button>
        </div>
      </div>
    </div>

    <!-- Toast Notification -->
    <transition enter-active-class="transition ease-out duration-300" enter-from-class="opacity-0 translate-y-2" enter-to-class="opacity-100 translate-y-0" leave-active-class="transition ease-in duration-200" leave-from-class="opacity-100 translate-y-0" leave-to-class="opacity-0 translate-y-2">
      <div v-if="showToast" class="fixed top-4 right-4 z-[9999] max-w-sm">
        <div :class="[
          'rounded-xl shadow-2xl p-4 flex items-center gap-3',
          toastType === 'success' ? 'bg-green-500 text-white' : 'bg-red-500 text-white'
        ]">
          <svg v-if="toastType === 'success'" class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
          </svg>
          <svg v-else class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
          </svg>
          <span class="font-semibold">{{ toastMessage }}</span>
        </div>
      </div>
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import api from '../../services/api';
import Navbar from '../../components/Navbar.vue';

const router = useRouter();
const loading = ref(true);
const orders = ref([]);
const searchQuery = ref('');
const selectedStatus = ref('');
const selectedMonth = ref('current');
const expandedOrder = ref(null);
const activeTab = ref('today');
const ratingModal = ref(null);
const selectedRating = ref(0);
const ratingComment = ref('');
const helpModal = ref(null);
const helpMessage = ref('');
const showCancelModal = ref(false);
const showConfirmModal = ref(false);
const cancelOrderId = ref(null);
const cancelReason = ref('');
const cancelling = ref(false);
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref('success');

const orderSteps = [
  { status: 'pending', label: 'Pending', icon: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z' },
  { status: 'accepted', label: 'Accepted', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' },
  { status: 'preparing', label: 'Preparing', icon: 'M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4' },
  { status: 'ready', label: 'Ready', icon: 'M5 13l4 4L19 7' },
  { status: 'picked_up', label: 'Picked Up', icon: 'M13 10V3L4 14h7v7l9-11h-7z' },
  { status: 'delivered', label: 'Delivered', icon: 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z' }
];

const filteredOrders = computed(() => {
  let filtered = orders.value;

  // Filter by tab
  if (activeTab.value === 'today') {
    const today = new Date().toDateString();
    filtered = filtered.filter(order => {
      const orderDate = new Date(order.created_at).toDateString();
      return orderDate === today && order.status !== 'delivered' && order.status !== 'cancelled';
    });
  } else {
    // History: filter by month
    const now = new Date();
    
    if (selectedMonth.value === 'current') {
      // Current month
      filtered = filtered.filter(order => {
        const orderDate = new Date(order.created_at);
        return orderDate.getMonth() === now.getMonth() && 
               orderDate.getFullYear() === now.getFullYear() &&
               (order.status === 'delivered' || order.status === 'cancelled');
      });
    } else if (selectedMonth.value === 'last') {
      // Last month
      const lastMonth = new Date(now.getFullYear(), now.getMonth() - 1, 1);
      filtered = filtered.filter(order => {
        const orderDate = new Date(order.created_at);
        return orderDate.getMonth() === lastMonth.getMonth() && 
               orderDate.getFullYear() === lastMonth.getFullYear() &&
               (order.status === 'delivered' || order.status === 'cancelled');
      });
    } else {
      // All time
      filtered = filtered.filter(order => 
        order.status === 'delivered' || order.status === 'cancelled'
      );
    }
  }

  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(order =>
      order.order_number.toLowerCase().includes(query) ||
      order.restaurant_name.toLowerCase().includes(query)
    );
  }

  if (selectedStatus.value && activeTab.value === 'today') {
    filtered = filtered.filter(order => order.status === selectedStatus.value);
  }

  return filtered;
});

const loadOrders = async () => {
  try {
    loading.value = true;
    const response = await api.get('/orders');
    orders.value = response.data.data || response.data || [];
  } catch (error) {
    console.error('Error loading orders:', error);
    // Mock data for demo
    orders.value = [
      {
        id: 1,
        order_number: 'ORD-2024-001',
        restaurant_name: 'Pizza Hut',
        status: 'delivered',
        total: 1500,
        subtotal: 1200,
        delivery_fee: 100,
        service_charge: 100,
        tax: 100,
        discount: 0,
        delivery_address: '123 Main Street, Colombo 03',
        delivery_phone: '0771234567',
        created_at: '2024-01-15T10:30:00',
        items: [
          { id: 1, name: 'Margherita Pizza', quantity: 1, subtotal: 800 },
          { id: 2, name: 'Garlic Bread', quantity: 2, subtotal: 400 }
        ]
      },
      {
        id: 2,
        order_number: 'ORD-2024-002',
        restaurant_name: 'KFC',
        status: 'preparing',
        total: 2000,
        subtotal: 1700,
        delivery_fee: 100,
        service_charge: 100,
        tax: 100,
        discount: 0,
        delivery_address: '456 Park Avenue, Colombo 05',
        delivery_phone: '0771234568',
        created_at: '2024-01-16T14:20:00',
        items: [
          { id: 3, name: 'Zinger Burger Meal', quantity: 2, subtotal: 1700 }
        ]
      }
    ];
  } finally {
    loading.value = false;
  }
};

const toggleOrderDetails = (orderId) => {
  expandedOrder.value = expandedOrder.value === orderId ? null : orderId;
};

const getStatusClass = (status) => {
  const classes = {
    'pending': 'bg-yellow-100 text-yellow-700',
    'accepted': 'bg-blue-100 text-blue-700',
    'preparing': 'bg-blue-100 text-blue-700',
    'ready': 'bg-purple-100 text-purple-700',
    'picked_up': 'bg-indigo-100 text-indigo-700',
    'delivered': 'bg-green-100 text-green-700',
    'cancelled': 'bg-red-100 text-red-700'
  };
  return classes[status] || 'bg-gray-100 text-gray-700';
};

const formatStatus = (status) => {
  return status.replace('_', ' ').replace(/\b\w/g, l => l.toUpperCase());
};

const formatDate = (date) => {
  const d = new Date(date);
  const now = new Date();
  const diff = Math.floor((now - d) / 1000 / 60 / 60 / 24);
  
  if (diff === 0) return 'Today at ' + d.toLocaleTimeString('en-LK', { timeZone: 'Asia/Colombo', hour: '2-digit', minute: '2-digit', hour12: true });
  if (diff === 1) return 'Yesterday at ' + d.toLocaleTimeString('en-LK', { timeZone: 'Asia/Colombo', hour: '2-digit', minute: '2-digit', hour12: true });
  if (diff < 7) return `${diff} days ago`;
  
  return d.toLocaleDateString('en-LK', { timeZone: 'Asia/Colombo', month: 'short', day: 'numeric', year: 'numeric' });
};

const getProgressWidth = (status) => {
  const progress = {
    'pending': '0%',
    'accepted': '20%',
    'preparing': '40%',
    'ready': '60%',
    'picked_up': '80%',
    'delivered': '100%'
  };
  return progress[status] || '0%';
};

const isStepCompleted = (currentStatus, stepStatus) => {
  const statusOrder = ['pending', 'accepted', 'preparing', 'ready', 'picked_up', 'delivered'];
  const currentIndex = statusOrder.indexOf(currentStatus);
  const stepIndex = statusOrder.indexOf(stepStatus);
  return stepIndex <= currentIndex;
};

const reorder = async (order) => {
  if (confirm(`Reorder from ${order.restaurant_name}?`)) {
    try {
      // Add items to cart
      for (const item of order.items) {
        await api.post('/cart', {
          product_id: item.product_id,
          restaurant_id: order.restaurant_id,
          quantity: item.quantity,
          variations: item.variations,
          addons: item.addons
        });
      }
      alert('Items added to cart!');
      router.push('/cart');
    } catch (error) {
      alert('Failed to reorder');
    }
  }
};

const rateOrder = (order) => {
  ratingModal.value = order;
  selectedRating.value = order.rating || 0;
  ratingComment.value = '';
};

const submitRating = async () => {
  try {
    await api.post(`/orders/${ratingModal.value.id}/rate`, {
      rating: selectedRating.value,
      comment: ratingComment.value
    });
    alert('Thank you for your rating!');
    ratingModal.value = null;
    await loadOrders();
  } catch (error) {
    alert('Failed to submit rating');
  }
};

const showHelpModal = (order) => {
  helpModal.value = order;
  helpMessage.value = '';
};

const submitHelp = async () => {
  try {
    await api.post('/support/message', {
      order_id: helpModal.value.id,
      message: helpMessage.value
    });
    alert('Your message has been sent to support!');
    helpModal.value = null;
  } catch (error) {
    alert('Failed to send message');
  }
};

const showNotification = (message, type = 'success') => {
  toastMessage.value = message;
  toastType.value = type;
  showToast.value = true;
  setTimeout(() => {
    showToast.value = false;
  }, 3000);
};

const openCancelModal = (orderId) => {
  cancelOrderId.value = orderId;
  showCancelModal.value = true;
};

const confirmCancel = () => {
  const reason = cancelReason.value.trim();
  
  if (!reason) {
    showNotification('Please enter a cancellation reason', 'error');
    return;
  }
  
  if (reason.length < 10) {
    showNotification('Cancellation reason must be at least 10 characters', 'error');
    return;
  }
  
  showCancelModal.value = false;
  showConfirmModal.value = true;
};

const cancelOrder = async () => {
  showConfirmModal.value = false;
  cancelling.value = true;
  
  try {
    await api.post(`/orders/${cancelOrderId.value}/cancel`, {
      cancellation_reason: cancelReason.value.trim()
    });
    showNotification('Order cancelled successfully', 'success');
    cancelReason.value = '';
    cancelOrderId.value = null;
    await loadOrders();
  } catch (error) {
    console.error('Cancel error:', error.response?.data);
    const message = error.response?.data?.message || 'Failed to cancel order';
    showNotification(message, 'error');
  } finally {
    cancelling.value = false;
  }
};

const trackOrder = (orderId) => {
  // Removed - track order button removed
};

onMounted(() => {
  loadOrders();
  // Auto-refresh only for today's orders
  const refreshInterval = setInterval(() => {
    if (activeTab.value === 'today') {
      loadOrders();
    }
  }, 10000);
  
  // Cleanup on unmount
  onUnmounted(() => {
    clearInterval(refreshInterval);
  });
});
</script>
