<template>
  <div class="min-h-screen bg-gray-50 p-4">
    <!-- Header -->
    <div class="mb-6">
      <h1 class="text-3xl font-bold text-gray-900">Admin Dashboard</h1>
      <p class="text-gray-600">Monitor and manage your food delivery platform</p>
    </div>

    <!-- System Health Alert -->
    <div v-if="systemHealth?.status !== 'healthy'" class="mb-6">
      <div class="bg-yellow-50 border-l-4 border-yellow-400 p-4 rounded-lg">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-yellow-400" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <h3 class="text-sm font-medium text-yellow-800">System Health Warning</h3>
            <div class="mt-2 text-sm text-yellow-700">
              <ul class="list-disc pl-5 space-y-1">
                <li v-for="issue in systemHealth.issues" :key="issue">{{ issue }}</li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Stats Grid -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">Total Orders</p>
            <p class="text-2xl font-bold text-gray-900">{{ formatNumber(stats.total_orders) }}</p>
            <div class="flex items-center mt-2">
              <span class="text-sm text-gray-500">Today: {{ stats.today_orders }}</span>
              <span v-if="stats.orders_trend !== 0" 
                    :class="stats.orders_trend > 0 ? 'text-green-600' : 'text-red-600'"
                    class="ml-2 text-xs font-medium">
                {{ stats.orders_trend > 0 ? '+' : '' }}{{ stats.orders_trend }}%
              </span>
            </div>
          </div>
          <div class="p-3 bg-blue-50 rounded-lg">
            <svg class="w-6 h-6 text-blue-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 2v10a2 2 0 002 2h8a2 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>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">Total Revenue</p>
            <p class="text-2xl font-bold text-gray-900">${{ formatCurrency(stats.total_revenue) }}</p>
            <div class="flex items-center mt-2">
              <span class="text-sm text-gray-500">Today: ${{ formatCurrency(stats.today_revenue) }}</span>
              <span v-if="stats.revenue_trend !== 0" 
                    :class="stats.revenue_trend > 0 ? 'text-green-600' : 'text-red-600'"
                    class="ml-2 text-xs font-medium">
                {{ stats.revenue_trend > 0 ? '+' : '' }}{{ stats.revenue_trend }}%
              </span>
            </div>
          </div>
          <div class="p-3 bg-green-50 rounded-lg">
            <svg class="w-6 h-6 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1" />
            </svg>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">Restaurants</p>
            <p class="text-2xl font-bold text-gray-900">{{ stats.total_restaurants }}</p>
            <div class="flex items-center mt-2">
              <span class="text-sm text-green-600">{{ stats.active_restaurants }} Active</span>
              <span v-if="stats.pending_restaurants > 0" class="ml-2 text-sm text-yellow-600">
                {{ stats.pending_restaurants }} Pending
              </span>
            </div>
          </div>
          <div class="p-3 bg-purple-50 rounded-lg">
            <svg class="w-6 h-6 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
            </svg>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm font-medium text-gray-600">Delivery Boys</p>
            <p class="text-2xl font-bold text-gray-900">{{ stats.total_delivery_boys }}</p>
            <div class="flex items-center mt-2">
              <span class="text-sm text-green-600">{{ stats.active_delivery_boys }} Online</span>
              <span class="ml-2 text-sm text-gray-500">
                {{ stats.total_delivery_boys - stats.active_delivery_boys }} Offline
              </span>
            </div>
          </div>
          <div class="p-3 bg-orange-50 rounded-lg">
            <svg class="w-6 h-6 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
          </div>
        </div>
      </div>
    </div>

    <!-- Charts and Analytics -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
      <!-- Daily Orders Chart -->
      <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">Daily Orders (Last 7 Days)</h3>
        <canvas ref="ordersChart" class="w-full h-64"></canvas>
      </div>

      <!-- Order Status Distribution -->
      <div class="bg-white rounded-xl shadow-sm p-6 border border-gray-100">
        <h3 class="text-lg font-semibold text-gray-900 mb-4">Order Status Distribution</h3>
        <canvas ref="statusChart" class="w-full h-64"></canvas>
      </div>
    </div>

    <!-- Recent Orders and Top Restaurants -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
      <!-- Recent Orders -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-100">
        <div class="p-6 border-b border-gray-100">
          <h3 class="text-lg font-semibold text-gray-900">Recent Orders</h3>
        </div>
        <div class="divide-y divide-gray-100">
          <div v-for="order in recentOrders" :key="order.id" class="p-4 hover:bg-gray-50">
            <div class="flex items-center justify-between">
              <div>
                <p class="font-medium text-gray-900">#{{ order.order_number }}</p>
                <p class="text-sm text-gray-600">{{ order.user?.name }} • {{ order.restaurant?.name }}</p>
              </div>
              <div class="text-right">
                <p class="font-medium text-gray-900">${{ formatCurrency(order.total) }}</p>
                <span :class="getStatusColor(order.status)" class="inline-flex px-2 py-1 text-xs font-medium rounded-full">
                  {{ formatStatus(order.status) }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Top Restaurants -->
      <div class="bg-white rounded-xl shadow-sm border border-gray-100">
        <div class="p-6 border-b border-gray-100">
          <h3 class="text-lg font-semibold text-gray-900">Top Restaurants Today</h3>
        </div>
        <div class="divide-y divide-gray-100">
          <div v-for="restaurant in topRestaurants" :key="restaurant.id" class="p-4 hover:bg-gray-50">
            <div class="flex items-center justify-between">
              <div class="flex items-center">
                <img v-if="restaurant.image" :src="restaurant.image" :alt="restaurant.name" 
                     class="w-10 h-10 rounded-lg object-cover mr-3">
                <div v-else class="w-10 h-10 bg-gray-200 rounded-lg mr-3 flex items-center justify-center">
                  <svg class="w-5 h-5 text-gray-400" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd" />
                  </svg>
                </div>
                <div>
                  <p class="font-medium text-gray-900">{{ restaurant.name }}</p>
                  <p class="text-sm text-gray-600">{{ restaurant.orders_count }} orders</p>
                </div>
              </div>
              <div class="text-right">
                <p class="font-medium text-gray-900">${{ formatCurrency(restaurant.orders_sum_total || 0) }}</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { Chart, registerables } from 'chart.js'
import axios from 'axios'

Chart.register(...registerables)

export default {
  name: 'EnhancedAdminDashboard',
  setup() {
    const stats = ref({})
    const recentOrders = ref([])
    const topRestaurants = ref([])
    const ordersByStatus = ref({})
    const systemHealth = ref(null)
    const analytics = ref(null)
    const ordersChart = ref(null)
    const statusChart = ref(null)
    const loading = ref(true)

    const loadDashboard = async () => {
      try {
        const [dashboardRes, healthRes, analyticsRes] = await Promise.all([
          axios.get('/api/admin/dashboard'),
          axios.get('/api/admin/system-health'),
          axios.get('/api/admin/analytics?days=7')
        ])

        if (dashboardRes.data.success) {
          const data = dashboardRes.data.data
          stats.value = data.stats
          recentOrders.value = data.recent_orders
          topRestaurants.value = data.top_restaurants
          ordersByStatus.value = data.orders_by_status
        }

        if (healthRes.data.success) {
          systemHealth.value = healthRes.data.data
        }

        if (analyticsRes.data.success) {
          analytics.value = analyticsRes.data.data
          await nextTick()
          createCharts()
        }
      } catch (error) {
        console.error('Failed to load dashboard:', error)
      } finally {
        loading.value = false
      }
    }

    const createCharts = () => {
      if (analytics.value && ordersChart.value && statusChart.value) {
        // Orders Chart
        new Chart(ordersChart.value, {
          type: 'line',
          data: {
            labels: analytics.value.daily_orders.map(d => new Date(d.date).toLocaleDateString()),
            datasets: [{
              label: 'Orders',
              data: analytics.value.daily_orders.map(d => d.orders),
              borderColor: '#3b82f6',
              backgroundColor: 'rgba(59, 130, 246, 0.1)',
              tension: 0.4
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
              y: { beginAtZero: true }
            }
          }
        })

        // Status Chart
        const statusData = analytics.value.status_distribution
        new Chart(statusChart.value, {
          type: 'doughnut',
          data: {
            labels: statusData.map(s => formatStatus(s.status)),
            datasets: [{
              data: statusData.map(s => s.count),
              backgroundColor: [
                '#f59e0b', '#10b981', '#3b82f6', '#ef4444', '#8b5cf6'
              ]
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { position: 'bottom' } }
          }
        })
      }
    }

    const formatNumber = (num) => {
      return new Intl.NumberFormat().format(num || 0)
    }

    const formatCurrency = (amount) => {
      return new Intl.NumberFormat('en-US', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount || 0)
    }

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

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

    onMounted(() => {
      loadDashboard()
    })

    return {
      stats,
      recentOrders,
      topRestaurants,
      ordersByStatus,
      systemHealth,
      analytics,
      ordersChart,
      statusChart,
      loading,
      formatNumber,
      formatCurrency,
      formatStatus,
      getStatusColor,
      loadDashboard
    }
  }
}
</script>