<template>
  <div class="order-management-dashboard">
    <!-- Header -->
    <header class="page-header">
      <div>
        <h1>📦 Order Management</h1>
        <p class="subtitle">Manage all orders in the system</p>
      </div>
      <div class="header-actions">
        <button @click="refreshData" class="btn-action">
          <span>🔄</span>
          <span>Refresh</span>
        </button>
        <button @click="exportOrders" class="btn-action">
          <span>📊</span>
          <span>Export</span>
        </button>
        <button @click="showBulkActions = !showBulkActions" class="btn-primary">
          <span>⚡</span>
          <span>Bulk Actions</span>
        </button>
      </div>
    </header>

    <!-- Stats Dashboard -->
    <div class="stats-grid">
      <div class="stat-card" v-for="stat in dashboardStats" :key="stat.label">
        <div class="stat-header">
          <span class="stat-label">{{ stat.label }}</span>
        </div>
        <div class="stat-body">
          <div class="stat-icon" :style="{ background: stat.gradient }">
            {{ stat.icon }}
          </div>
          <div class="stat-details">
            <div class="stat-value-wrapper">
              <span v-if="stat.currency" class="stat-currency">{{ stat.currency }}</span>
              <span class="stat-value">{{ stat.value }}</span>
            </div>
            <div class="stat-trend" :class="stat.trend >= 0 ? 'positive' : 'negative'" v-if="stat.trend !== 0">
              <span class="trend-arrow">{{ stat.trend >= 0 ? '↗' : '↘' }}</span>
              <span class="trend-value">{{ Math.abs(stat.trend) }}%</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Search Bar -->
    <div class="search-section">
      <input v-model="filters.search" type="text" placeholder="🔍 Search orders by order number, customer name, phone..." class="search-input">
    </div>

    <!-- Quick Actions & Filters -->
    <div class="controls-section">
      <div class="filters-panel">
        <div class="filter-group">
          <select v-model="filters.status" class="filter-select">
            <option value="">All Status</option>
            <option value="pending">Pending</option>
            <option value="accepted">Accepted</option>
            <option value="preparing">Preparing</option>
            <option value="ready">Ready</option>
            <option value="picked_up">Picked Up</option>
            <option value="delivered">Delivered</option>
            <option value="cancelled">Cancelled</option>
          </select>
          
          <select v-model="filters.restaurant_id" class="filter-select">
            <option value="">All Restaurants</option>
            <option v-for="restaurant in restaurants" :key="restaurant.id" :value="restaurant.id">
              {{ restaurant.name }}
            </option>
          </select>
          
          <input v-model="filters.date_from" type="date" class="filter-input">
          <input v-model="filters.date_to" type="date" class="filter-input">
          
          <button @click="applyFilters" class="filter-btn">🔍 Filter</button>
          <button @click="clearFilters" class="clear-btn">🗑️ Clear</button>
          
          <button v-if="filters.restaurant_id" @click="openRestaurantOrders(filters.restaurant_id)" class="restaurant-orders-btn">
            📦 View Restaurant Orders
          </button>
        </div>
      </div>

      <!-- Bulk Actions Panel -->
      <div v-if="showBulkActions" class="bulk-actions-panel">
        <div class="bulk-controls">
          <select v-model="bulkStatus" class="bulk-select">
            <option value="">Select Status</option>
            <option value="accepted">Accept Orders</option>
            <option value="preparing">Mark Preparing</option>
            <option value="ready">Mark Ready</option>
            <option value="cancelled">Cancel Orders</option>
          </select>
          <button @click="executeBulkAction" class="bulk-btn" :disabled="!bulkStatus || selectedOrders.length === 0">
            Apply to {{ selectedOrders.length }} orders
          </button>
        </div>
      </div>
    </div>

    <!-- Orders Table -->
    <div class="orders-table-container">
      <div class="table-header">
        <div class="table-title">
          <h3>📋 Orders List ({{ pagination.total || orders.length }})</h3>
        </div>
        <div class="table-actions">
          <select v-model="filters.per_page" @change="applyFilters" class="per-page-select">
            <option :value="10">10 per page</option>
            <option :value="20">20 per page</option>
            <option :value="50">50 per page</option>
            <option :value="100">100 per page</option>
          </select>
          <button @click="selectAll" class="select-all-btn">
            {{ allSelected ? 'Deselect All' : 'Select All' }}
          </button>
        </div>
      </div>

      <div class="orders-table">
        <table>
          <thead>
            <tr>
              <th><input type="checkbox" @change="toggleSelectAll" :checked="allSelected"></th>
              <th>Order #</th>
              <th>Customer</th>
              <th>Restaurant</th>
              <th>Amount</th>
              <th>Status</th>
              <th>Delivery Boy</th>
              <th>Created</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in orders" :key="order.id" :class="{ 'selected': selectedOrders.includes(order.id) }" @click="viewOrder(order)" class="clickable-row">
              <td @click.stop>
                <input type="checkbox" :value="order.id" v-model="selectedOrders">
              </td>
              <td class="order-number">#{{ order.order_number }}</td>
              <td class="customer-info">
                <div class="customer-name">{{ order.user?.name }}</div>
                <div class="customer-phone">{{ order.delivery_phone }}</div>
              </td>
              <td class="restaurant-name">{{ order.restaurant?.name }}</td>
              <td class="order-amount">Rs. {{ parseFloat(order.total).toFixed(2) }}</td>
              <td @click.stop>
                <select v-model="order.status" @change="updateOrderStatus(order)" class="status-select" :class="getStatusClass(order.status)">
                  <option value="pending">Pending</option>
                  <option value="accepted">Accepted</option>
                  <option value="preparing">Preparing</option>
                  <option value="ready">Ready</option>
                  <option value="picked_up">Picked Up</option>
                  <option value="delivered">Delivered</option>
                  <option value="cancelled">Cancelled</option>
                </select>
              </td>
              <td class="delivery-boy" @click.stop>
                <button @click="openAssignModal(order)" class="assign-btn">
                  {{ order.delivery?.delivery_boy_id ? 'Change' : 'Assign' }}
                </button>
                <div v-if="order.delivery?.delivery_boy_id" class="assigned-name">
                  {{ getDeliveryBoyName(order.delivery.delivery_boy_id) }}
                </div>
              </td>
              <td class="order-date">{{ formatDate(order.created_at) }}</td>
              <td class="order-actions" @click.stop>
                <button @click="viewOrder(order)" class="action-btn view">👁️</button>
                <button @click="editOrder(order)" class="action-btn edit">✏️</button>
                <button @click="cancelOrder(order)" class="action-btn cancel" v-if="canCancel(order)">❌</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      <div v-if="pagination.last_page > 1" class="pagination-container">
        <div class="pagination-info">
          Showing {{ pagination.from }} to {{ pagination.to }} of {{ pagination.total }} orders
        </div>
        <div class="pagination-controls">
          <button @click="changePage(1)" :disabled="pagination.current_page === 1" class="page-btn">
            « First
          </button>
          <button @click="changePage(pagination.current_page - 1)" :disabled="pagination.current_page === 1" class="page-btn">
            ‹ Prev
          </button>
          
          <button 
            v-for="page in visiblePages" 
            :key="page" 
            @click="changePage(page)" 
            class="page-btn" 
            :class="{ active: page === pagination.current_page }"
          >
            {{ page }}
          </button>
          
          <button @click="changePage(pagination.current_page + 1)" :disabled="pagination.current_page === pagination.last_page" class="page-btn">
            Next ›
          </button>
          <button @click="changePage(pagination.last_page)" :disabled="pagination.current_page === pagination.last_page" class="page-btn">
            Last »
          </button>
        </div>
      </div>
    </div>

    <!-- Order Detail Modal -->
    <div v-if="selectedOrder" class="modal-overlay" @click="closeModal">
      <div class="order-modal" @click.stop>
        <div class="modal-header">
          <h2>Order Details - #{{ selectedOrder.order_number }}</h2>
          <button @click="closeModal" class="close-btn">×</button>
        </div>
        
        <div class="modal-body">
          <div class="order-info-grid">
            <div class="info-section">
              <h4>Customer Information</h4>
              <p><strong>Name:</strong> {{ selectedOrder.user?.name }}</p>
              <p><strong>Phone:</strong> {{ selectedOrder.delivery_phone }}</p>
              <p><strong>Address:</strong> {{ selectedOrder.delivery_address }}</p>
            </div>
            
            <div class="info-section">
              <h4>Restaurant Information</h4>
              <p><strong>Name:</strong> {{ selectedOrder.restaurant?.name }}</p>
              <p><strong>Address:</strong> {{ selectedOrder.restaurant?.address }}</p>
            </div>
            
            <div class="info-section">
              <h4>Order Status</h4>
              <div class="status-badge" :class="getStatusClass(selectedOrder.status)">
                {{ formatStatus(selectedOrder.status) }}
              </div>
              <p><strong>Created:</strong> {{ formatDate(selectedOrder.created_at) }}</p>
            </div>
          </div>
          
          <div class="order-items">
            <h4>Order Items</h4>
            <div class="items-list">
              <div v-for="item in selectedOrder.items" :key="item.id" class="order-item">
                <span class="item-name">{{ item.product?.name }}</span>
                <span class="item-qty">x{{ item.quantity }}</span>
                <span class="item-price">Rs. {{ parseFloat(item.total_price).toFixed(2) }}</span>
              </div>
            </div>
          </div>
          
          <div class="order-totals">
            <div class="total-row">
              <span>Subtotal:</span>
              <span>Rs. {{ parseFloat(selectedOrder.subtotal).toFixed(2) }}</span>
            </div>
            <div class="total-row">
              <span>Delivery Fee:</span>
              <span>Rs. {{ parseFloat(selectedOrder.delivery_fee).toFixed(2) }}</span>
            </div>
            <div class="total-row">
              <span>Tax:</span>
              <span>Rs. {{ parseFloat(selectedOrder.tax).toFixed(2) }}</span>
            </div>
            <div class="total-row final">
              <span><strong>Total:</strong></span>
              <span><strong>Rs. {{ parseFloat(selectedOrder.total).toFixed(2) }}</strong></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Assign Delivery Boy Modal -->
    <AssignDeliveryModal 
      v-if="showAssignModal" 
      :order="selectedOrderForAssign" 
      @close="closeAssignModal" 
      @assigned="onAssignSuccess"
    />

    <!-- Loading Overlay -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>Loading orders...</p>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue'
import axios from 'axios'
import AssignDeliveryModal from './AssignDeliveryModal.vue'

export default {
  name: 'OrderManagement',
  components: {
    AssignDeliveryModal
  },
  setup() {
    const loading = ref(false)
    const orders = ref([])
    const restaurants = ref([])
    const availableDeliveryBoys = ref([])
    const selectedOrder = ref(null)
    const selectedOrders = ref([])
    const showBulkActions = ref(false)
    const bulkStatus = ref('')
    const stats = ref({})
    const showAssignModal = ref(false)
    const selectedOrderForAssign = ref(null)
    const pagination = ref({
      current_page: 1,
      last_page: 1,
      per_page: 20,
      total: 0,
      from: 0,
      to: 0
    })
    
    const filters = reactive({
      status: '',
      restaurant_id: '',
      date_from: '',
      date_to: '',
      search: '',
      per_page: 20
    })

    const dashboardStats = computed(() => [
      {
        icon: '📦',
        label: 'Total Orders',
        value: stats.value.total_orders?.toLocaleString() || '0',
        trend: stats.value.orders_trend || 0,
        gradient: 'linear-gradient(135deg, #ff6b35 0%, #f7931e 100%)'
      },
      {
        icon: '💰',
        label: 'Total Revenue',
        value: parseFloat(stats.value.total_revenue || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}),
        currency: 'Rs',
        trend: stats.value.revenue_trend || 0,
        gradient: 'linear-gradient(135deg, #ff8a50 0%, #ff6b35 100%)'
      },
      {
        icon: '📅',
        label: "Today's Orders",
        value: stats.value.today_orders?.toLocaleString() || '0',
        trend: stats.value.orders_trend || 0,
        gradient: 'linear-gradient(135deg, #ffa366 0%, #ff8a50 100%)'
      },
      {
        icon: '💵',
        label: "Today's Revenue",
        value: parseFloat(stats.value.today_revenue || 0).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}),
        currency: 'Rs',
        trend: stats.value.revenue_trend || 0,
        gradient: 'linear-gradient(135deg, #ffb380 0%, #ffa366 100%)'
      },
      {
        icon: '⏳',
        label: 'Pending Orders',
        value: stats.value.pending_orders?.toLocaleString() || '0',
        trend: 0,
        gradient: 'linear-gradient(135deg, #ffc299 0%, #ffb380 100%)'
      },
      {
        icon: '🔄',
        label: 'Active Orders',
        value: stats.value.active_orders?.toLocaleString() || '0',
        trend: 0,
        gradient: 'linear-gradient(135deg, #ffd1b3 0%, #ffc299 100%)'
      },
      {
        icon: '✅',
        label: 'Delivered Today',
        value: stats.value.delivered_today?.toLocaleString() || '0',
        trend: 0,
        gradient: 'linear-gradient(135deg, #10b981 0%, #059669 100%)'
      },
      {
        icon: '❌',
        label: 'Cancelled Today',
        value: stats.value.cancelled_today?.toLocaleString() || '0',
        trend: 0,
        gradient: 'linear-gradient(135deg, #ef4444 0%, #dc2626 100%)'
      }
    ])

    const allSelected = computed(() => {
      return orders.value.length > 0 && selectedOrders.value.length === orders.value.length
    })

    const visiblePages = computed(() => {
      const pages = []
      const current = pagination.value.current_page
      const last = pagination.value.last_page
      
      for (let i = Math.max(1, current - 2); i <= Math.min(last, current + 2); i++) {
        pages.push(i)
      }
      return pages
    })

    const loadDashboardData = async () => {
      try {
        loading.value = true
        const params = { ...filters, page: pagination.value.current_page }
        const response = await axios.get('/api/admin/orders', { params })
        
        if (response.data.success) {
          orders.value = response.data.data.data
          pagination.value = {
            current_page: response.data.data.current_page,
            last_page: response.data.data.last_page,
            per_page: response.data.data.per_page,
            total: response.data.data.total,
            from: response.data.data.from,
            to: response.data.data.to
          }
        }
        
        // Load stats separately
        const statsResponse = await axios.get('/api/admin/orders/dashboard-stats')
        if (statsResponse.data.success) {
          stats.value = statsResponse.data.data.stats
          availableDeliveryBoys.value = statsResponse.data.data.available_delivery_boys
        }
      } catch (error) {
        console.error('Error loading dashboard:', error)
      } finally {
        loading.value = false
      }
    }

    const loadRestaurants = async () => {
      try {
        const response = await axios.get('/api/admin/orders/restaurants')
        if (response.data.success) {
          restaurants.value = response.data.data
        }
      } catch (error) {
        console.error('Error loading restaurants:', error)
      }
    }

    const loadDeliveryBoys = async () => {
      try {
        const response = await axios.get('/api/admin/orders/delivery-boys')
        if (response.data.success) {
          availableDeliveryBoys.value = response.data.data
        }
      } catch (error) {
        console.error('Error loading delivery boys:', error)
      }
    }

    const openRestaurantOrders = (restaurantId) => {
      // This will be handled by parent component
      window.dispatchEvent(new CustomEvent('open-restaurant-orders', { detail: { restaurantId } }))
    }

    const applyFilters = async () => {
      try {
        loading.value = true
        const params = { ...filters, page: pagination.value.current_page }
        const response = await axios.get('/api/admin/orders', { params })
        if (response.data.success) {
          orders.value = response.data.data.data
          pagination.value = {
            current_page: response.data.data.current_page,
            last_page: response.data.data.last_page,
            per_page: response.data.data.per_page,
            total: response.data.data.total,
            from: response.data.data.from,
            to: response.data.data.to
          }
        }
      } catch (error) {
        console.error('Error applying filters:', error)
      } finally {
        loading.value = false
      }
    }

    const changePage = (page) => {
      if (page >= 1 && page <= pagination.value.last_page) {
        pagination.value.current_page = page
        applyFilters()
      }
    }

    const clearFilters = () => {
      Object.keys(filters).forEach(key => {
        if (key !== 'per_page') {
          filters[key] = ''
        }
      })
      pagination.value.current_page = 1
      loadDashboardData()
    }

    const updateOrderStatus = async (order) => {
      try {
        const response = await axios.put(`/api/admin/orders/${order.id}/status`, {
          status: order.status
        })
        
        if (response.data.success) {
          console.log('Status updated successfully')
        }
      } catch (error) {
        console.error('Error updating status:', error)
        loadDashboardData()
      }
    }

    const openAssignModal = (order) => {
      selectedOrderForAssign.value = order
      showAssignModal.value = true
    }

    const closeAssignModal = () => {
      showAssignModal.value = false
      selectedOrderForAssign.value = null
    }

    const onAssignSuccess = () => {
      closeAssignModal()
      loadDashboardData()
    }

    const getDeliveryBoyName = (deliveryBoyId) => {
      const boy = availableDeliveryBoys.value.find(b => b.id === deliveryBoyId)
      return boy?.full_name || boy?.user?.name || 'Unknown'
    }

    const cancelOrder = async (order) => {
      if (!confirm('Are you sure you want to cancel this order?')) return
      
      try {
        const response = await axios.post(`/api/admin/orders/${order.id}/cancel`, {
          reason: 'Cancelled by admin'
        })
        
        if (response.data.success) {
          loadDashboardData()
        }
      } catch (error) {
        console.error('Error cancelling order:', error)
      }
    }

    const executeBulkAction = async () => {
      if (!bulkStatus.value || selectedOrders.value.length === 0) return
      
      try {
        const response = await axios.post('/api/admin/orders/bulk-update-status', {
          order_ids: selectedOrders.value,
          status: bulkStatus.value
        })
        
        if (response.data.success) {
          selectedOrders.value = []
          bulkStatus.value = ''
          showBulkActions.value = false
          loadDashboardData()
        }
      } catch (error) {
        console.error('Error executing bulk action:', error)
      }
    }

    const toggleSelectAll = () => {
      if (allSelected.value) {
        selectedOrders.value = []
      } else {
        selectedOrders.value = orders.value.map(order => order.id)
      }
    }

    const selectAll = () => {
      toggleSelectAll()
    }

    const viewOrder = async (order) => {
      try {
        const response = await axios.get(`/api/admin/orders/${order.id}`)
        if (response.data.success) {
          selectedOrder.value = response.data.data
        }
      } catch (error) {
        console.error('Error loading order details:', error)
      }
    }

    const editOrder = (order) => {
      console.log('Edit order:', order.id)
    }

    const closeModal = () => {
      selectedOrder.value = null
    }

    const refreshData = () => {
      loadDashboardData()
    }

    const exportOrders = async () => {
      try {
        let params = new URLSearchParams()
        
        // If orders are selected, export only selected orders
        if (selectedOrders.value.length > 0) {
          params.append('order_ids', selectedOrders.value.join(','))
        } else {
          // Otherwise export with current filters
          Object.keys(filters).forEach(key => {
            if (filters[key]) {
              params.append(key, filters[key])
            }
          })
        }
        
        const token = localStorage.getItem('token')
        
        const response = await axios.get(`/api/admin/orders/export?${params.toString()}`, {
          responseType: 'blob',
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        
        const url = window.URL.createObjectURL(new Blob([response.data]))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `orders_${new Date().toISOString().slice(0,10)}.xls`)
        document.body.appendChild(link)
        link.click()
        link.remove()
        
        if (selectedOrders.value.length > 0) {
          alert(`Exported ${selectedOrders.value.length} selected orders successfully!`)
        }
      } catch (error) {
        console.error('Export failed:', error)
        alert('Failed to export orders')
      }
    }

    const canCancel = (order) => {
      return !['delivered', 'cancelled'].includes(order.status)
    }

    const getStatusClass = (status) => {
      const classes = {
        pending: 'status-pending',
        accepted: 'status-accepted',
        preparing: 'status-preparing',
        ready: 'status-ready',
        picked_up: 'status-picked',
        delivered: 'status-delivered',
        cancelled: 'status-cancelled'
      }
      return classes[status] || 'status-default'
    }

    const formatStatus = (status) => {
      return status.replace('_', ' ').toUpperCase()
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleString()
    }

    onMounted(async () => {
      await loadDashboardData()
      await loadRestaurants()
      await loadDeliveryBoys()
    })

    return {
      loading,
      orders,
      restaurants,
      availableDeliveryBoys,
      selectedOrder,
      selectedOrders,
      showBulkActions,
      bulkStatus,
      filters,
      dashboardStats,
      allSelected,
      visiblePages,
      loadDashboardData,
      applyFilters,
      clearFilters,
      updateOrderStatus,
      openAssignModal,
      closeAssignModal,
      onAssignSuccess,
      getDeliveryBoyName,
      cancelOrder,
      executeBulkAction,
      toggleSelectAll,
      selectAll,
      viewOrder,
      editOrder,
      closeModal,
      refreshData,
      exportOrders,
      canCancel,
      getStatusClass,
      formatStatus,
      formatDate,
      openRestaurantOrders,
      pagination,
      changePage,
      showAssignModal,
      selectedOrderForAssign
    }
  }
}
</script>

<style scoped>
.order-management-dashboard { padding: 2rem; }

.page-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem; }
.page-header h1 { margin: 0; font-size: 1.75rem; font-weight: 700; color: #1f2937; }
.subtitle { margin: 0.5rem 0 0; color: #6b7280; font-size: 0.875rem; }

.header-actions { display: flex; gap: 0.75rem; }

.btn-action, .btn-primary {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 12px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 0.875rem;
}

.btn-action {
  background: white;
  color: #374151;
  border: 1px solid #e5e7eb;
}

.btn-primary {
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
}

.btn-action:hover, .btn-primary:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(0,0,0,0.15); }

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 1.5rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  transition: all 0.3s;
  border: 1px solid #f1f5f9;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}

.stat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-label {
  color: #6b7280;
  font-size: 0.875rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.stat-body {
  display: flex;
  align-items: center;
  gap: 1rem;
  min-width: 0;
  overflow: hidden;
}

.stat-icon {
  width: 56px;
  height: 56px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.75rem;
  color: white;
  flex-shrink: 0;
}

.stat-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
  min-width: 0;
  overflow: hidden;
}

.stat-value-wrapper {
  display: flex;
  align-items: baseline;
  gap: 0.5rem;
  overflow: hidden;
}

.stat-currency {
  font-size: 1rem;
  font-weight: 600;
  color: #6b7280;
  flex-shrink: 0;
}

.stat-value {
  font-size: 1.75rem;
  font-weight: 700;
  color: #1f2937;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.stat-trend {
  display: flex;
  align-items: center;
  gap: 0.25rem;
  font-size: 0.875rem;
  font-weight: 600;
}

.trend-arrow {
  font-size: 1.25rem;
  line-height: 1;
}

.trend-value {
  font-size: 0.875rem;
}

.stat-trend.positive { color: #10b981; }
.stat-trend.negative { color: #ef4444; }

@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 1rem;
  }
  
  .stat-card {
    padding: 1.25rem;
  }
  
  .stat-icon {
    width: 48px;
    height: 48px;
    font-size: 1.5rem;
  }
  
  .stat-value {
    font-size: 1.5rem;
  }
  
  .stat-label {
    font-size: 0.75rem;
  }
}

.search-section {
  margin-bottom: 1.5rem;
}

.search-input {
  width: 100%;
  padding: 0.875rem 1.25rem;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  background: white;
  font-size: 0.9375rem;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
}

.search-input:focus {
  outline: none;
  border-color: #ff6b35;
  box-shadow: 0 4px 12px rgba(255, 107, 53, 0.15);
}

.controls-section {
  background: white;
  border-radius: 16px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  border: 1px solid #f1f5f9;
}

.filter-group {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 1rem;
  align-items: center;
}

.restaurant-orders-btn {
  padding: 0.75rem 1.5rem;
  background: #10b981;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  font-size: 0.875rem;
  cursor: pointer;
  transition: all 0.3s ease;
}

.restaurant-orders-btn:hover {
  background: #059669;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.filter-select, .filter-input {
  padding: 0.75rem;
  border: 2px solid #f3f4f6;
  border-radius: 8px;
  background: #f9fafb;
  transition: all 0.3s ease;
}

.filter-select:focus, .filter-input:focus {
  outline: none;
  border-color: #ff6b35;
  background: white;
}

.filter-btn, .clear-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.filter-btn {
  background: #ff6b35;
  color: white;
}

.clear-btn {
  background: #f3f4f6;
  color: #6b7280;
}

.bulk-actions-panel {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #e5e7eb;
}

.bulk-controls {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.bulk-select {
  padding: 0.75rem;
  border: 2px solid #f3f4f6;
  border-radius: 8px;
  background: white;
}

.bulk-btn {
  padding: 0.75rem 1.5rem;
  background: #ff6b35;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.bulk-btn:disabled {
  background: #d1d5db;
  cursor: not-allowed;
}

.orders-table-container {
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  overflow: hidden;
  border: 1px solid #f1f5f9;
}

.table-header {
  background: #f8fafc;
  padding: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e5e7eb;
}

.table-title h3 {
  margin: 0;
  color: #1f2937;
  font-size: 1.25rem;
}

.select-all-btn {
  padding: 0.5rem 1rem;
  background: #ff6b35;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.875rem;
}

.per-page-select {
  padding: 0.5rem 1rem;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  background: white;
  font-size: 0.875rem;
  cursor: pointer;
  margin-right: 1rem;
}

.table-actions {
  display: flex;
  align-items: center;
}

.orders-table {
  overflow-x: auto;
}

.orders-table table {
  width: 100%;
  border-collapse: collapse;
}

.orders-table th,
.orders-table td {
  padding: 1rem;
  text-align: left;
  border-bottom: 1px solid #f3f4f6;
}

.orders-table th {
  background: #f8fafc;
  font-weight: 600;
  color: #374151;
}

.orders-table tr:hover {
  background: #f9fafb;
  cursor: pointer;
}

.orders-table tr.clickable-row {
  cursor: pointer;
  transition: all 0.2s;
}

.orders-table tr.clickable-row:hover {
  background: #fef3c7;
  transform: scale(1.01);
}

.orders-table tr.selected {
  background: rgba(255, 107, 53, 0.1);
}

.order-number {
  font-weight: 600;
  color: #ff6b35;
}

.customer-info {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.customer-name {
  font-weight: 500;
  color: #1f2937;
}

.customer-phone {
  font-size: 0.875rem;
  color: #6b7280;
}

.restaurant-name {
  font-weight: 500;
  color: #1f2937;
}

.order-amount {
  font-weight: 600;
  color: #059669;
}

.status-select {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 0.875rem;
}

.status-pending { background: #fef3c7; color: #d97706; }
.status-accepted { background: #dbeafe; color: #2563eb; }
.status-preparing { background: #fde68a; color: #d97706; }
.status-ready { background: #d1fae5; color: #059669; }
.status-picked { background: #e0e7ff; color: #5b21b6; }
.status-delivered { background: #dcfce7; color: #16a34a; }
.status-cancelled { background: #fee2e2; color: #dc2626; }

.delivery-select {
  padding: 0.5rem;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 0.875rem;
  max-width: 150px;
}

.order-date {
  font-size: 0.875rem;
  color: #6b7280;
}

.order-actions {
  display: flex;
  gap: 0.5rem;
}

.order-actions .action-btn {
  padding: 0.5rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.875rem;
}

.action-btn.view { background: #3b82f6; color: white; }
.action-btn.edit { background: #f59e0b; color: white; }
.action-btn.cancel { background: #ef4444; color: white; }

/* Pagination Styles */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
}

.pagination-info {
  color: #6b7280;
  font-size: 0.875rem;
}

.pagination-controls {
  display: flex;
  gap: 0.5rem;
}

.page-btn {
  padding: 0.5rem 1rem;
  border: 1px solid #e5e7eb;
  background: white;
  color: #374151;
  border-radius: 6px;
  cursor: pointer;
  font-size: 0.875rem;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  background: #f3f4f6;
  border-color: #ff6b35;
}

.page-btn.active {
  background: linear-gradient(135deg, #ff6b35, #f7931e);
  color: white;
  border-color: #ff6b35;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* Modal Styles */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.order-modal {
  background: white;
  border-radius: 16px;
  max-width: 800px;
  width: 90%;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 25px 60px rgba(0, 0, 0, 0.3);
}

.modal-header {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
  color: white;
  padding: 1.5rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.close-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 0.5rem;
  border-radius: 8px;
}

.modal-body {
  padding: 2rem;
}

.order-info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.info-section h4 {
  margin: 0 0 1rem 0;
  color: #1f2937;
  font-size: 1.1rem;
}

.info-section p {
  margin: 0.5rem 0;
  color: #4b5563;
}

.status-badge {
  display: inline-block;
  padding: 0.5rem 1rem;
  border-radius: 20px;
  font-size: 0.875rem;
  font-weight: 600;
  text-transform: uppercase;
}

.order-items h4 {
  margin: 0 0 1rem 0;
  color: #1f2937;
}

.items-list {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  border-bottom: 1px solid #f3f4f6;
}

.order-item:last-child {
  border-bottom: none;
}

.item-name {
  flex: 1;
  font-weight: 500;
  color: #1f2937;
}

.item-qty {
  color: #6b7280;
  margin: 0 1rem;
}

.item-price {
  font-weight: 600;
  color: #ff6b35;
}

.order-totals {
  margin-top: 2rem;
  padding-top: 1rem;
  border-top: 2px solid #e5e7eb;
}

.total-row {
  display: flex;
  justify-content: space-between;
  margin: 0.5rem 0;
  color: #4b5563;
}

.total-row.final {
  margin-top: 1rem;
  padding-top: 1rem;
  border-top: 1px solid #e5e7eb;
  color: #1f2937;
  font-size: 1.1rem;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f4f6;
  border-top: 4px solid #ff6b35;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .order-management-dashboard {
    padding: 1rem;
  }
  
  .header-content {
    flex-direction: column;
    gap: 1rem;
  }
  
  .filter-group {
    grid-template-columns: 1fr;
  }
  
  .orders-table {
    font-size: 0.875rem;
  }
  
  .order-actions {
    flex-direction: column;
  }
}
</style>


.assign-btn {
  padding: 0.5rem 1rem;
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 0.875rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
}

.assign-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.assigned-name {
  margin-top: 0.25rem;
  font-size: 0.75rem;
  color: #6b7280;
}
