<template>
  <div>
    <!-- Top Navigation -->
    <nav class="bg-white shadow-md sticky top-0 z-50">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        <div class="flex justify-between items-center h-16">
          <div class="flex items-center space-x-3">
            <span class="text-3xl">👨‍💼</span>
            <h1 class="text-2xl font-bold bg-gradient-to-r from-orange-500 to-red-500 bg-clip-text text-transparent">Admin Dashboard</h1>
          </div>
          <div class="flex items-center space-x-4">
            <router-link to="/admin/products" class="text-gray-700 hover:text-orange-600 font-medium transition">Products</router-link>
            <router-link to="/admin/users" class="text-gray-700 hover:text-orange-600 font-medium transition">Users</router-link>
            <router-link to="/admin/categories" class="text-gray-700 hover:text-orange-600 font-medium transition">Categories</router-link>
            <router-link to="/" class="text-gray-700 hover:text-orange-600 font-medium transition">Home</router-link>
            <button @click="logout" class="bg-red-500 text-white px-4 py-2 rounded-lg hover:bg-red-600 transition">Logout</button>
          </div>
        </div>
      </div>
    </nav>

    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Stats Cards -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
        <div class="bg-gradient-to-br from-orange-500 to-orange-600 rounded-2xl shadow-lg p-6 text-white transform hover:scale-105 transition">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-orange-100 text-sm font-medium">Total Orders</p>
              <h3 class="text-4xl font-bold mt-2">{{ stats.totalOrders }}</h3>
            </div>
            <span class="text-5xl opacity-20">📦</span>
          </div>
          <p class="text-orange-100 text-sm">+12% from last month</p>
        </div>

        <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-2xl shadow-lg p-6 text-white transform hover:scale-105 transition">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-green-100 text-sm font-medium">Total Revenue</p>
              <h3 class="text-4xl font-bold mt-2">Rs {{ stats.totalRevenue }}</h3>
            </div>
            <span class="text-5xl opacity-20">💰</span>
          </div>
          <p class="text-green-100 text-sm">+8% from last month</p>
        </div>

        <div class="bg-gradient-to-br from-red-500 to-red-600 rounded-2xl shadow-lg p-6 text-white transform hover:scale-105 transition">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-red-100 text-sm font-medium">Restaurants</p>
              <h3 class="text-4xl font-bold mt-2">{{ stats.totalRestaurants }}</h3>
            </div>
            <span class="text-5xl opacity-20">🏪</span>
          </div>
          <p class="text-red-100 text-sm">{{ stats.pendingRestaurants }} pending approval</p>
        </div>

        <div class="bg-gradient-to-br from-yellow-500 to-yellow-600 rounded-2xl shadow-lg p-6 text-white transform hover:scale-105 transition">
          <div class="flex justify-between items-start mb-4">
            <div>
              <p class="text-orange-100 text-sm font-medium">Active Users</p>
              <h3 class="text-4xl font-bold mt-2">{{ stats.totalUsers }}</h3>
            </div>
            <span class="text-5xl opacity-20">👥</span>
          </div>
          <p class="text-orange-100 text-sm">{{ stats.onlineUsers }} online now</p>
        </div>
      </div>

      <!-- Quick Actions -->
      <div class="bg-white rounded-2xl shadow-lg p-6 mb-8">
        <h2 class="text-xl font-bold text-gray-900 mb-4">Quick Actions</h2>
        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
          <button @click="activeTab = 'restaurants'" class="flex flex-col items-center p-4 rounded-xl hover:bg-orange-50 transition">
            <span class="text-4xl mb-2">🏪</span>
            <span class="text-sm font-medium text-gray-700">Restaurants</span>
          </button>
          <button @click="activeTab = 'orders'" class="flex flex-col items-center p-4 rounded-xl hover:bg-orange-50 transition">
            <span class="text-4xl mb-2">📦</span>
            <span class="text-sm font-medium text-gray-700">Orders</span>
          </button>
          <button @click="activeTab = 'users'" class="flex flex-col items-center p-4 rounded-xl hover:bg-orange-50 transition">
            <span class="text-4xl mb-2">👥</span>
            <span class="text-sm font-medium text-gray-700">Users</span>
          </button>
          <button @click="activeTab = 'delivery'" class="flex flex-col items-center p-4 rounded-xl hover:bg-orange-50 transition">
            <span class="text-4xl mb-2">🚴</span>
            <span class="text-sm font-medium text-gray-700">Delivery Boys</span>
          </button>
          <button @click="activeTab = 'payments'" class="flex flex-col items-center p-4 rounded-xl hover:bg-yellow-50 transition">
            <span class="text-4xl mb-2">💳</span>
            <span class="text-sm font-medium text-gray-700">Payments</span>
          </button>
          <button @click="activeTab = 'settings'" class="flex flex-col items-center p-4 rounded-xl hover:bg-gray-50 transition">
            <span class="text-4xl mb-2">⚙️</span>
            <span class="text-sm font-medium text-gray-700">Settings</span>
          </button>
        </div>
      </div>

      <!-- Content Tabs -->
      <div class="bg-white rounded-2xl shadow-lg p-6">
        <!-- Restaurants Tab -->
        <div v-if="activeTab === 'restaurants'">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-900">Restaurant Management</h2>
            <div class="flex space-x-3">
              <button @click="fetchRestaurants" class="bg-orange-500 text-white px-4 py-2 rounded-lg hover:bg-orange-600 transition">🔄 Refresh</button>
              <button @click="addRestaurant" class="bg-gradient-to-r from-orange-500 to-red-500 text-white px-4 py-2 rounded-lg hover:shadow-lg transition">➕ Add Restaurant</button>
            </div>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Restaurant</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Owner</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Status</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Rating</th>
                  <th class="text-right py-3 px-4 font-semibold text-gray-700">Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="restaurant in restaurants" :key="restaurant.id" class="border-b hover:bg-gray-50">
                  <td class="py-3 px-4">
                    <div class="font-medium text-gray-900">{{ restaurant.name }}</div>
                    <div class="text-sm text-gray-500">{{ restaurant.address }}</div>
                  </td>
                  <td class="py-3 px-4 text-gray-700">{{ restaurant.user?.name }}</td>
                  <td class="py-3 px-4">
                    <span :class="restaurant.status === 'approved' ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800'" class="px-3 py-1 rounded-full text-sm font-medium">
                      {{ restaurant.status }}
                    </span>
                  </td>
                  <td class="py-3 px-4">
                    <span class="text-yellow-500">⭐</span> {{ restaurant.rating || '4.5' }}
                  </td>
                  <td class="py-3 px-4 text-right">
                    <button v-if="restaurant.status === 'pending'" @click="approveRestaurant(restaurant.id)" class="text-green-600 hover:text-green-800 mr-3">✅ Approve</button>
                    <button @click="editRestaurant(restaurant)" class="text-blue-600 hover:text-blue-800 mr-3">✏️ Edit</button>
                    <button @click="deleteRestaurant(restaurant.id)" class="text-red-600 hover:text-red-800">🗑️ Delete</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Orders Tab -->
        <div v-if="activeTab === 'orders'">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-900">Order Management</h2>
            <button @click="exportOrders" class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition">📥 Export CSV</button>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50">
                <tr>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Order #</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Customer</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Restaurant</th>
                  <th class="text-left py-3 px-4 font-semibold text-gray-700">Status</th>
                  <th class="text-right py-3 px-4 font-semibold text-gray-700">Amount</th>
                  <th class="text-right py-3 px-4 font-semibold text-gray-700">Actions</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="order in orders" :key="order.id" class="border-b hover:bg-gray-50">
                  <td class="py-3 px-4 font-medium text-blue-600">{{ order.order_number }}</td>
                  <td class="py-3 px-4 text-gray-700">{{ order.user?.name }}</td>
                  <td class="py-3 px-4 text-gray-700">{{ order.restaurant?.name }}</td>
                  <td class="py-3 px-4">
                    <span :class="statusClass(order.status)" class="px-3 py-1 rounded-full text-sm font-medium">
                      {{ order.status }}
                    </span>
                  </td>
                  <td class="py-3 px-4 text-right font-semibold text-gray-900">Rs {{ order.total }}</td>
                  <td class="py-3 px-4 text-right">
                    <button class="text-blue-600 hover:text-blue-800 mr-3">👁️ View</button>
                    <button v-if="order.status === 'pending'" class="text-red-600 hover:text-red-800">❌ Cancel</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <!-- Users Tab -->
        <div v-if="activeTab === 'users'">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-900">User Management</h2>
            <button class="bg-gradient-to-r from-orange-500 to-red-500 text-white px-4 py-2 rounded-lg hover:shadow-lg transition">➕ Add User</button>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
            <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-xl p-6">
              <div class="text-4xl mb-3">👥</div>
              <h3 class="text-2xl font-bold text-gray-900">{{ stats.totalUsers }}</h3>
              <p class="text-gray-600">Total Customers</p>
            </div>
            <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl p-6">
              <div class="text-4xl mb-3">🏪</div>
              <h3 class="text-2xl font-bold text-gray-900">{{ stats.totalRestaurants }}</h3>
              <p class="text-gray-600">Restaurant Owners</p>
            </div>
            <div class="bg-gradient-to-br from-orange-50 to-orange-100 rounded-xl p-6">
              <div class="text-4xl mb-3">🚴</div>
              <h3 class="text-2xl font-bold text-gray-900">{{ deliveryBoys.length }}</h3>
              <p class="text-gray-600">Delivery Boys</p>
            </div>
          </div>
        </div>

        <!-- Delivery Boys Tab -->
        <div v-if="activeTab === 'delivery'">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-900">Delivery Boy Management</h2>
            <button class="bg-gradient-to-r from-orange-500 to-red-500 text-white px-4 py-2 rounded-lg hover:shadow-lg transition">➕ Add Delivery Boy</button>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="boy in deliveryBoys" :key="boy.id" class="bg-white border-2 border-gray-200 rounded-xl p-6 hover:shadow-lg transition">
              <div class="flex items-center justify-between mb-4">
                <div class="flex items-center space-x-3">
                  <div class="w-12 h-12 bg-gradient-to-br from-orange-500 to-red-500 rounded-full flex items-center justify-center text-white text-xl font-bold">
                    {{ boy.user?.name?.charAt(0) }}
                  </div>
                  <div>
                    <h3 class="font-bold text-gray-900">{{ boy.user?.name }}</h3>
                    <p class="text-sm text-gray-500">{{ boy.vehicle_type }}</p>
                  </div>
                </div>
                <span :class="boy.status === 'available' ? 'bg-green-500' : 'bg-gray-400'" class="w-3 h-3 rounded-full"></span>
              </div>
              <div class="space-y-2 text-sm">
                <div class="flex justify-between">
                  <span class="text-gray-600">Status:</span>
                  <span class="font-medium">{{ boy.status }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">Deliveries:</span>
                  <span class="font-medium">{{ boy.total_deliveries || 0 }}</span>
                </div>
                <div class="flex justify-between">
                  <span class="text-gray-600">Rating:</span>
                  <span class="font-medium">⭐ {{ boy.rating || '5.0' }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Payments Tab -->
        <div v-if="activeTab === 'payments'">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-2xl font-bold text-gray-900">Payment Management</h2>
            <button class="bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition">📊 Generate Report</button>
          </div>
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <div class="bg-green-50 rounded-xl p-6 border-2 border-green-200">
              <div class="text-3xl mb-2">💰</div>
              <h3 class="text-2xl font-bold text-gray-900">Rs {{ stats.totalRevenue }}</h3>
              <p class="text-gray-600">Total Revenue</p>
            </div>
            <div class="bg-blue-50 rounded-xl p-6 border-2 border-blue-200">
              <div class="text-3xl mb-2">💳</div>
              <h3 class="text-2xl font-bold text-gray-900">Rs 45,000</h3>
              <p class="text-gray-600">Pending Payouts</p>
            </div>
            <div class="bg-purple-50 rounded-xl p-6 border-2 border-purple-200">
              <div class="text-3xl mb-2">📈</div>
              <h3 class="text-2xl font-bold text-gray-900">Rs 12,500</h3>
              <p class="text-gray-600">Commission Earned</p>
            </div>
          </div>
        </div>

        <!-- Settings Tab -->
        <div v-if="activeTab === 'settings'">
          <h2 class="text-2xl font-bold text-gray-900 mb-6">System Settings</h2>
          <div class="space-y-4">
            <div class="bg-gray-50 rounded-xl p-6">
              <h3 class="font-bold text-gray-900 mb-3">Commission Settings</h3>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">Restaurant Commission (%)</label>
                  <input type="number" value="15" class="w-full px-4 py-2 border rounded-lg">
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Boy Commission (%)</label>
                  <input type="number" value="10" class="w-full px-4 py-2 border rounded-lg">
                </div>
              </div>
            </div>
            <div class="bg-gray-50 rounded-xl p-6">
              <h3 class="font-bold text-gray-900 mb-3">Delivery Settings</h3>
              <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">Base Delivery Fee (Rs)</label>
                  <input type="number" value="200" class="w-full px-4 py-2 border rounded-lg">
                </div>
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">Per KM Charge (Rs)</label>
                  <input type="number" value="50" class="w-full px-4 py-2 border rounded-lg">
                </div>
              </div>
            </div>
            <button class="bg-gradient-to-r from-orange-500 to-red-500 text-white px-6 py-3 rounded-lg hover:shadow-lg transition font-semibold">💾 Save Settings</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Add Restaurant Modal -->
    <div v-if="showAddModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="sticky top-0 bg-white border-b px-6 py-4 flex justify-between items-center">
          <h3 class="text-2xl font-bold text-gray-900">Add New Restaurant</h3>
          <button @click="closeAddModal" class="text-gray-500 hover:text-gray-700 text-2xl">&times;</button>
        </div>
        <div class="p-6">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Restaurant Name *</label>
              <input v-model="addForm.name" type="text" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
              <textarea v-model="addForm.description" rows="3" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500"></textarea>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Phone *</label>
                <input v-model="addForm.phone" type="text" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Email</label>
                <input v-model="addForm.email" type="email" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Address *</label>
              <input v-model="addForm.address" type="text" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Latitude *</label>
                <input v-model="addForm.latitude" type="number" step="0.0001" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Longitude *</label>
                <input v-model="addForm.longitude" type="number" step="0.0001" required class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
            </div>
            <div class="grid grid-cols-3 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Radius (km)</label>
                <input v-model="addForm.delivery_radius" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Min Order (Rs)</label>
                <input v-model="addForm.minimum_order" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Fee (Rs)</label>
                <input v-model="addForm.delivery_fee" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Opening Time</label>
                <input v-model="addForm.opening_time" type="time" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Closing Time</label>
                <input v-model="addForm.closing_time" type="time" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-orange-500">
              </div>
            </div>
          </div>
          <div class="flex justify-end space-x-3 mt-6">
            <button @click="closeAddModal" class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition">Cancel</button>
            <button @click="createRestaurant" class="px-6 py-2 bg-gradient-to-r from-orange-500 to-red-500 text-white rounded-lg hover:shadow-lg transition">Create Restaurant</button>
          </div>
        </div>
      </div>
    </div>

    <!-- Edit Restaurant Modal -->
    <div v-if="showEditModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div class="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[90vh] overflow-y-auto">
        <div class="sticky top-0 bg-white border-b px-6 py-4 flex justify-between items-center">
          <h3 class="text-2xl font-bold text-gray-900">Edit Restaurant</h3>
          <button @click="closeEditModal" class="text-gray-500 hover:text-gray-700 text-2xl">&times;</button>
        </div>
        <div class="p-6">
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Restaurant Name</label>
              <input v-model="editForm.name" type="text" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Description</label>
              <textarea v-model="editForm.description" rows="3" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500"></textarea>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Phone</label>
                <input v-model="editForm.phone" type="text" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Email</label>
                <input v-model="editForm.email" type="email" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Address</label>
              <input v-model="editForm.address" type="text" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Latitude</label>
                <input v-model="editForm.latitude" type="number" step="0.0001" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Longitude</label>
                <input v-model="editForm.longitude" type="number" step="0.0001" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
            </div>
            <div class="grid grid-cols-3 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Radius (km)</label>
                <input v-model="editForm.delivery_radius" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Min Order (Rs)</label>
                <input v-model="editForm.minimum_order" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Delivery Fee (Rs)</label>
                <input v-model="editForm.delivery_fee" type="number" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Opening Time</label>
                <input v-model="editForm.opening_time" type="time" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
              <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">Closing Time</label>
                <input v-model="editForm.closing_time" type="time" class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500">
              </div>
            </div>
          </div>
          <div class="flex justify-end space-x-3 mt-6">
            <button @click="closeEditModal" class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition">Cancel</button>
            <button @click="updateRestaurant" class="px-6 py-2 bg-gradient-to-r from-orange-500 to-red-500 text-white rounded-lg hover:shadow-lg transition">Update Restaurant</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useAuthStore } from '../../stores/auth';
import api from '../../services/api';

const router = useRouter();
const authStore = useAuthStore();

const activeTab = ref('restaurants');
const showNotifications = ref(false);
const showEditModal = ref(false);
const showAddModal = ref(false);
const editingRestaurant = ref(null);
const editForm = ref({
  name: '',
  description: '',
  address: '',
  phone: '',
  email: '',
  latitude: 0,
  longitude: 0,
  delivery_radius: 10,
  minimum_order: 500,
  delivery_fee: 200,
  opening_time: '09:00',
  closing_time: '22:00',
});
const addForm = ref({
  name: '',
  description: '',
  address: '',
  phone: '',
  email: '',
  latitude: 6.9271,
  longitude: 79.8612,
  delivery_radius: 10,
  minimum_order: 500,
  delivery_fee: 200,
  opening_time: '09:00',
  closing_time: '22:00',
});

const stats = ref({
  totalOrders: 0,
  totalRevenue: 0,
  totalRestaurants: 0,
  totalUsers: 0,
  pendingRestaurants: 0,
  onlineUsers: 0,
});

const restaurants = ref([]);
const orders = ref([]);
const deliveryBoys = ref([]);

const fetchDashboard = async () => {
  try {
    const response = await api.get('/admin/dashboard');
    stats.value = {
      totalOrders: response.data.stats?.total_orders || 0,
      totalRevenue: response.data.stats?.total_revenue || 0,
      totalRestaurants: response.data.stats?.total_restaurants || 0,
      totalUsers: response.data.stats?.total_users || 0,
      pendingRestaurants: response.data.stats?.pending_restaurants || 0,
      onlineUsers: response.data.stats?.online_users || 0,
    };
    orders.value = response.data.recent_orders || [];
  } catch (error) {
    console.error('Error:', error);
  }
};

const fetchRestaurants = async () => {
  try {
    const response = await api.get('/restaurants');
    restaurants.value = response.data.data || response.data;
  } catch (error) {
    console.error('Error:', error);
    alert('Failed to fetch restaurants');
  }
};

const deleteRestaurant = async (id) => {
  if (!confirm('Are you sure you want to delete this restaurant?')) return;
  try {
    await api.delete(`/restaurants/${id}`);
    alert('Restaurant deleted successfully!');
    fetchRestaurants();
  } catch (error) {
    alert('Failed to delete restaurant');
  }
};

const editRestaurant = (restaurant) => {
  editingRestaurant.value = restaurant;
  editForm.value = {
    name: restaurant.name,
    description: restaurant.description,
    address: restaurant.address,
    phone: restaurant.phone,
    email: restaurant.email,
    latitude: restaurant.latitude,
    longitude: restaurant.longitude,
    delivery_radius: restaurant.delivery_radius,
    minimum_order: restaurant.minimum_order,
    delivery_fee: restaurant.delivery_fee,
    opening_time: restaurant.opening_time,
    closing_time: restaurant.closing_time,
  };
  showEditModal.value = true;
};

const updateRestaurant = async () => {
  try {
    const response = await api.put(`/restaurants/${editingRestaurant.value.id}`, editForm.value);
    alert('Restaurant updated successfully!');
    showEditModal.value = false;
    fetchRestaurants();
  } catch (error) {
    console.error('Update error:', error.response?.data);
    alert('Failed to update restaurant: ' + (error.response?.data?.message || error.message));
  }
};

const closeEditModal = () => {
  showEditModal.value = false;
  editingRestaurant.value = null;
};

const addRestaurant = () => {
  showAddModal.value = true;
};

const createRestaurant = async () => {
  try {
    await api.post('/restaurants', addForm.value);
    alert('Restaurant created successfully!');
    showAddModal.value = false;
    addForm.value = {
      name: '',
      description: '',
      address: '',
      phone: '',
      email: '',
      latitude: 6.9271,
      longitude: 79.8612,
      delivery_radius: 10,
      minimum_order: 500,
      delivery_fee: 200,
      opening_time: '09:00',
      closing_time: '22:00',
    };
    fetchRestaurants();
  } catch (error) {
    console.error('Create error:', error.response?.data);
    alert('Failed to create restaurant: ' + (error.response?.data?.message || error.message));
  }
};

const closeAddModal = () => {
  showAddModal.value = false;
};

const fetchDeliveryBoys = async () => {
  try {
    const response = await api.get('/delivery-boy/available');
    deliveryBoys.value = response.data.data || [];
  } catch (error) {
    console.error('Error:', error);
  }
};

const approveRestaurant = async (id) => {
  try {
    await api.post(`/admin/restaurants/${id}/approve`);
    alert('Restaurant approved!');
    fetchRestaurants();
  } catch (error) {
    alert('Failed to approve restaurant');
  }
};

const exportOrders = async () => {
  try {
    const response = await api.get('/admin/orders/export', { responseType: 'blob' });
    const url = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', 'orders.csv');
    document.body.appendChild(link);
    link.click();
    link.remove();
  } catch (error) {
    alert('Export failed');
  }
};

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



onMounted(() => {
  fetchDashboard();
  fetchRestaurants();
  fetchDeliveryBoys();
});
</script>
