<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>📊 Dashboard Overview</h1>
      <p class="subtitle">Welcome back! Here's what's happening today.</p>
    </div>

    <!-- Summary Cards -->
    <div v-if="loading" class="stats-grid">
      <SkeletonLoader v-for="i in 6" :key="i" type="card" />
    </div>
    <transition-group v-else name="fade" tag="div" class="stats-grid">
      <Tooltip text="View all shops" position="top" :key="1">
        <div class="stat-card shops hover-lift">
          <div class="card-icon">🏪</div>
          <div class="card-content">
            <p class="card-label">Total Shops</p>
            <h2 class="card-value">{{ stats.total_shops }}</h2>
            <p class="card-change positive">+{{ stats.shops_growth }}% from last month</p>
          </div>
        </div>
      </Tooltip>

      <Tooltip text="View all delivery boys" position="top" :key="2">
        <div class="stat-card delivery-boys hover-lift">
          <div class="card-icon">🚴</div>
          <div class="card-content">
            <p class="card-label">Total Delivery Boys</p>
            <h2 class="card-value">{{ stats.total_delivery_boys }}</h2>
            <p class="card-change positive">+{{ stats.delivery_boys_growth }}% from last month</p>
          </div>
        </div>
      </Tooltip>

      <Tooltip text="Currently active delivery boys" position="top" :key="3">
        <div class="stat-card active-delivery hover-lift">
          <div class="card-icon">✅</div>
          <div class="card-content">
            <p class="card-label">Active Delivery Boys</p>
            <h2 class="card-value">{{ stats.active_delivery_boys }}</h2>
            <p class="card-info">{{ stats.online_percentage }}% online now</p>
          </div>
        </div>
      </Tooltip>

      <Tooltip text="View today's orders" position="top" :key="4">
        <div class="stat-card orders hover-lift">
          <div class="card-icon">📦</div>
          <div class="card-content">
            <p class="card-label">Total Orders Today</p>
            <h2 class="card-value">{{ stats.orders_today }}</h2>
            <p class="card-change" :class="stats.orders_change >= 0 ? 'positive' : 'negative'">
              {{ stats.orders_change >= 0 ? '+' : '' }}{{ stats.orders_change }}% from yesterday
            </p>
          </div>
        </div>
      </Tooltip>

      <Tooltip text="View revenue details" position="top" :key="5">
        <div class="stat-card revenue hover-lift">
          <div class="card-icon">💰</div>
          <div class="card-content">
            <p class="card-label">Total Revenue Today</p>
            <h2 class="card-value">Rs {{ formatNumber(stats.revenue_today) }}</h2>
            <p class="card-change" :class="stats.revenue_change >= 0 ? 'positive' : 'negative'">
              {{ stats.revenue_change >= 0 ? '+' : '' }}{{ stats.revenue_change }}% from yesterday
            </p>
          </div>
        </div>
      </Tooltip>

      <Tooltip text="View commission breakdown" position="top" :key="6">
        <div class="stat-card commission hover-lift">
          <div class="card-icon">💵</div>
          <div class="card-content">
            <p class="card-label">System Commission Today</p>
            <h2 class="card-value">Rs {{ formatNumber(stats.commission_today) }}</h2>
            <p class="card-info">{{ stats.commission_rate }}% avg rate</p>
          </div>
        </div>
      </Tooltip>
    </transition-group>

    <!-- Analytics Charts -->
    <div class="charts-section">
      <h2>📊 Analytics</h2>
      <div v-if="loading" class="charts-grid">
        <SkeletonLoader type="chart" />
        <SkeletonLoader type="chart" />
        <SkeletonLoader type="chart" />
      </div>
      <transition-group v-else name="fade" tag="div" class="charts-grid">
        <div class="chart-card card" :key="1">
          <div class="chart-header">
            <h3>📈 Orders Per Day</h3>
            <p>Last 7 days</p>
          </div>
          <canvas ref="ordersChart"></canvas>
        </div>

        <div class="chart-card card" :key="2">
          <div class="chart-header">
            <h3>💰 Revenue Per Month</h3>
            <p>Last 6 months</p>
          </div>
          <canvas ref="revenueChart"></canvas>
        </div>

        <div class="chart-card doughnut card" :key="3">
          <div class="chart-header">
            <h3>🚴 Delivery Boys Status</h3>
            <p>Current status</p>
          </div>
          <canvas ref="deliveryBoysChart"></canvas>
        </div>
      </transition-group>
    </div>

    <!-- Quick Actions -->
    <div class="quick-actions">
      <h2>⚡ Quick Actions</h2>
      <div class="actions-grid">
        <Tooltip text="Manage all restaurants" position="top">
          <button @click="$router.push('/admin/restaurants')" class="action-btn">
            <span class="action-icon">🏪</span>
            <span class="action-label">Manage Shops</span>
          </button>
        </Tooltip>
        <Tooltip text="Manage delivery personnel" position="top">
          <button @click="$router.push('/admin/delivery-boys')" class="action-btn">
            <span class="action-icon">🚴</span>
            <span class="action-label">Manage Delivery Boys</span>
          </button>
        </Tooltip>
        <Tooltip text="View all orders" position="top">
          <button @click="$router.push('/admin/orders')" class="action-btn">
            <span class="action-icon">📦</span>
            <span class="action-label">View Orders</span>
          </button>
        </Tooltip>
        <Tooltip text="Generate analytics reports" position="top">
          <button @click="$router.push('/admin/reports')" class="action-btn">
            <span class="action-icon">📈</span>
            <span class="action-label">Generate Reports</span>
          </button>
        </Tooltip>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from 'vue'
import { Chart, registerables } from 'chart.js'
import api from '@/services/api'
import SkeletonLoader from '../Common/SkeletonLoader.vue'
import Tooltip from '../Common/Tooltip.vue'

Chart.register(...registerables)

export default {
  components: { SkeletonLoader, Tooltip },
  setup() {
    const loading = ref(true)
    const ordersChart = ref(null)
    const revenueChart = ref(null)
    const deliveryBoysChart = ref(null)
    let ordersChartInstance = null
    let revenueChartInstance = null
    let deliveryBoysChartInstance = null
    const stats = ref({
      total_shops: 0,
      shops_growth: 0,
      total_delivery_boys: 0,
      delivery_boys_growth: 0,
      active_delivery_boys: 0,
      online_percentage: 0,
      orders_today: 0,
      orders_change: 0,
      revenue_today: 0,
      revenue_change: 0,
      commission_today: 0,
      commission_rate: 0,
    })

    const loadStats = async () => {
      loading.value = true
      try {
        const { data } = await api.get('/admin/dashboard')
        
        stats.value = {
          total_shops: data.data.stats.total_restaurants.value || 0,
          shops_growth: 5.2,
          total_delivery_boys: data.data.stats.delivery_boys.total || 0,
          delivery_boys_growth: 3.8,
          active_delivery_boys: data.data.stats.delivery_boys.active_now || 0,
          online_percentage: data.data.stats.delivery_boys.total > 0 
            ? Math.round((data.data.stats.delivery_boys.active_now / data.data.stats.delivery_boys.total) * 100)
            : 0,
          orders_today: data.data.stats.total_orders.today || 0,
          orders_change: data.data.stats.total_orders.growth || 0,
          revenue_today: data.data.stats.total_revenue.today || 0,
          revenue_change: data.data.stats.total_revenue.growth || 0,
          commission_today: (data.data.stats.total_revenue.today || 0) * 0.15,
          commission_rate: 15,
        }
      } catch (error) {
        console.error('Failed to load stats:', error)
      } finally {
        loading.value = false
      }
    }

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

    const initCharts = async () => {
      await nextTick()

      if (ordersChart.value) {
        ordersChartInstance = new Chart(ordersChart.value, {
          type: 'line',
          data: {
            labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
            datasets: [{
              label: 'Orders',
              data: [45, 52, 38, 65, 59, 80, 72],
              borderColor: '#ff6b35',
              backgroundColor: 'rgba(255, 107, 53, 0.1)',
              tension: 0.4,
              fill: true,
              pointRadius: 4,
              pointHoverRadius: 6,
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: { display: false },
              tooltip: {
                backgroundColor: '#1f2937',
                padding: 12,
                cornerRadius: 8,
              }
            },
            scales: {
              y: {
                beginAtZero: true,
                grid: { color: '#f3f4f6' },
                ticks: { color: '#6b7280' }
              },
              x: {
                grid: { display: false },
                ticks: { color: '#6b7280' }
              }
            }
          }
        })
      }

      if (revenueChart.value) {
        revenueChartInstance = new Chart(revenueChart.value, {
          type: 'bar',
          data: {
            labels: ['Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
            datasets: [{
              label: 'Revenue ($)',
              data: [12500, 15200, 18900, 16400, 21300, 19800],
              backgroundColor: [
                'rgba(102, 126, 234, 0.8)',
                'rgba(118, 75, 162, 0.8)',
                'rgba(255, 107, 53, 0.8)',
                'rgba(247, 147, 30, 0.8)',
                'rgba(16, 185, 129, 0.8)',
                'rgba(59, 130, 246, 0.8)',
              ],
              borderRadius: 8,
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: { display: false },
              tooltip: {
                backgroundColor: '#1f2937',
                padding: 12,
                cornerRadius: 8,
                callbacks: {
                  label: (context) => `Revenue: Rs ${context.parsed.y.toLocaleString()}`
                }
              }
            },
            scales: {
              y: {
                beginAtZero: true,
                grid: { color: '#f3f4f6' },
                ticks: {
                  color: '#6b7280',
                  callback: (value) => `Rs ${value / 1000}k`
                }
              },
              x: {
                grid: { display: false },
                ticks: { color: '#6b7280' }
              }
            }
          }
        })
      }

      if (deliveryBoysChart.value) {
        deliveryBoysChartInstance = new Chart(deliveryBoysChart.value, {
          type: 'doughnut',
          data: {
            labels: ['Online', 'Offline', 'On Delivery'],
            datasets: [{
              data: [stats.value.active_delivery_boys, 
                     stats.value.total_delivery_boys - stats.value.active_delivery_boys - 5, 
                     5],
              backgroundColor: [
                'rgba(16, 185, 129, 0.8)',
                'rgba(239, 68, 68, 0.8)',
                'rgba(59, 130, 246, 0.8)',
              ],
              borderWidth: 0,
            }]
          },
          options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
              legend: {
                position: 'bottom',
                labels: {
                  padding: 15,
                  color: '#6b7280',
                  font: { size: 12 }
                }
              },
              tooltip: {
                backgroundColor: '#1f2937',
                padding: 12,
                cornerRadius: 8,
              }
            }
          }
        })
      }
    }

    onMounted(async () => {
      await loadStats()
      await initCharts()
    })

    return { loading, stats, formatNumber, ordersChart, revenueChart, deliveryBoysChart }
  }
}
</script>

<style scoped>
.dashboard { padding: 0; }

.fade-enter-active, .fade-leave-active { transition: opacity 0.3s ease; }
.fade-enter-from, .fade-leave-to { opacity: 0; }

.hover-lift {
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}
.hover-lift:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 28px rgba(0,0,0,0.15);
}

.card {
  transition: box-shadow 0.3s ease, transform 0.2s ease;
}
.card:hover {
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

:global(.dark) .dashboard-header h1 { color: #f9fafb; }
:global(.dark) .subtitle { color: #9ca3af; }
:global(.dark) .stat-card { background: #1f2937; border-color: #374151; }
:global(.dark) .card-label { color: #9ca3af; }
:global(.dark) .card-value { color: #f9fafb; }
:global(.dark) .chart-card { background: #1f2937; border-color: #374151; }
:global(.dark) .chart-header h3 { color: #f9fafb; }
:global(.dark) .action-btn { background: #1f2937; border-color: #374151; }
:global(.dark) .action-btn:hover { background: #374151; border-color: #ff6b35; }
:global(.dark) .action-label { color: #d1d5db; }

.dashboard-header { margin-bottom: 2rem; }
.dashboard-header h1 { margin: 0; font-size: 2rem; font-weight: 700; color: #1f2937; }
.subtitle { margin: 0.5rem 0 0; color: #6b7280; font-size: 1rem; }

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

.stat-card {
  background: white;
  border-radius: 16px;
  padding: 1.5rem;
  display: flex;
  gap: 1.25rem;
  box-shadow: 0 2px 8px rgba(0,0,0,0.06);
  border: 1px solid #f1f5f9;
  cursor: pointer;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  flex-shrink: 0;
}

.stat-card.shops .card-icon { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
.stat-card.delivery-boys .card-icon { background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); }
.stat-card.active-delivery .card-icon { background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); }
.stat-card.orders .card-icon { background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%); }
.stat-card.revenue .card-icon { background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); }
.stat-card.commission .card-icon { background: linear-gradient(135deg, #30cfd0 0%, #330867 100%); }

.card-content { flex: 1; }
.card-label { margin: 0; font-size: 0.875rem; color: #6b7280; font-weight: 500; }
.card-value { margin: 0.5rem 0; font-size: 2rem; font-weight: 700; color: #1f2937; }
.card-change, .card-info { margin: 0; font-size: 0.75rem; font-weight: 600; }
.card-change.positive { color: #10b981; }
.card-change.negative { color: #ef4444; }
.card-info { color: #6b7280; }

.quick-actions { margin-top: 2rem; }
.quick-actions h2 { margin: 0 0 1.5rem; font-size: 1.5rem; font-weight: 700; color: #1f2937; }

.actions-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1rem;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0.75rem;
  padding: 1.5rem;
  background: white;
  border: 2px solid #e5e7eb;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn:hover {
  border-color: #ff6b35;
  background: linear-gradient(135deg, rgba(255,107,53,0.05), rgba(247,147,30,0.05));
  transform: translateY(-2px);
}

.action-icon { font-size: 2.5rem; }
.action-label { font-size: 0.875rem; font-weight: 600; color: #374151; }

.charts-section { margin: 2rem 0; }
.charts-section h2 { margin: 0 0 1.5rem; font-size: 1.5rem; font-weight: 700; color: #1f2937; }

.charts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  gap: 1.5rem;
}

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

.chart-header { margin-bottom: 1.5rem; }
.chart-header h3 { margin: 0; font-size: 1.125rem; font-weight: 600; color: #1f2937; }
.chart-header p { margin: 0.25rem 0 0; font-size: 0.75rem; color: #9ca3af; }

canvas { max-height: 300px; }

@media (max-width: 768px) {
  .stats-grid { grid-template-columns: repeat(2, 1fr); gap: 1rem; }
  .stat-card { padding: 1rem; }
  .card-icon { width: 48px; height: 48px; font-size: 1.5rem; }
  .card-value { font-size: 1.5rem; }
  .actions-grid { grid-template-columns: repeat(2, 1fr); }
  .charts-grid { grid-template-columns: 1fr; }
}
</style>
