<template>
  <div class="advanced-dashboard">
    <!-- Dashboard Header -->
    <div class="dashboard-header">
      <div class="header-content">
        <h1 class="dashboard-title">📊 Super Admin Dashboard</h1>
        <div class="last-updated">
          <span class="update-indicator"></span>
          Last updated: {{ lastUpdated }}
        </div>
      </div>
      <div class="header-actions">
        <button @click="refreshData" class="refresh-btn" :class="{ loading: isRefreshing }">
          <span class="refresh-icon">🔄</span>
          Refresh
        </button>
      </div>
    </div>

    <!-- Advanced Summary Cards Grid -->
    <div class="summary-grid">
      <!-- Total Orders Card -->
      <div class="summary-card orders-card" @click="navigateToOrders">
        <div class="card-header">
          <div class="card-icon orders-icon">📦</div>
          <div class="card-menu">⋯</div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value">{{ animatedValues.totalOrders }}</div>
            <div class="metric-label">Total Orders</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Today</span>
              <span class="sub-value">{{ dashboardData.todayOrders }}</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">Month</span>
              <span class="sub-value">{{ dashboardData.monthOrders }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="trend-indicator" :class="dashboardData.ordersTrend.direction">
            <span class="trend-icon">{{ getTrendIcon(dashboardData.ordersTrend.direction) }}</span>
            <span class="trend-value">{{ dashboardData.ordersTrend.percentage }}%</span>
            <span class="trend-period">vs last month</span>
          </div>
        </div>
      </div>

      <!-- Active Orders Card -->
      <div class="summary-card active-card">
        <div class="card-header">
          <div class="card-icon active-icon">⚡</div>
          <div class="pulse-indicator"></div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value">{{ animatedValues.activeOrders }}</div>
            <div class="metric-label">Active Orders</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Preparing</span>
              <span class="sub-value">{{ dashboardData.preparingOrders }}</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">On the Way</span>
              <span class="sub-value">{{ dashboardData.onTheWayOrders }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="status-bar">
            <div class="status-segment preparing" :style="{ width: preparingPercentage + '%' }"></div>
            <div class="status-segment on-way" :style="{ width: onWayPercentage + '%' }"></div>
          </div>
        </div>
      </div>

      <!-- Late Orders Card -->
      <div class="summary-card late-card" :class="{ critical: dashboardData.lateOrders > 10 }">
        <div class="card-header">
          <div class="card-icon late-icon">⏰</div>
          <div class="alert-badge" v-if="dashboardData.lateOrders > 5">!</div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value critical">{{ animatedValues.lateOrders }}</div>
            <div class="metric-label">Late Orders</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Avg Delay</span>
              <span class="sub-value">{{ dashboardData.avgDelay }}min</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">Critical</span>
              <span class="sub-value critical">{{ dashboardData.criticalLate }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="trend-indicator" :class="dashboardData.lateTrend.direction">
            <span class="trend-icon">{{ getTrendIcon(dashboardData.lateTrend.direction) }}</span>
            <span class="trend-value">{{ dashboardData.lateTrend.percentage }}%</span>
            <span class="trend-period">vs yesterday</span>
          </div>
        </div>
      </div>

      <!-- Cancelled Orders Card -->
      <div class="summary-card cancelled-card">
        <div class="card-header">
          <div class="card-icon cancelled-icon">❌</div>
          <div class="percentage-badge">{{ cancelledPercentage }}%</div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value">{{ animatedValues.cancelledOrders }}</div>
            <div class="metric-label">Cancelled Orders</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Rate</span>
              <span class="sub-value">{{ cancelledPercentage }}%</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">Today</span>
              <span class="sub-value">{{ dashboardData.todayCancelled }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="trend-indicator" :class="dashboardData.cancelledTrend.direction">
            <span class="trend-icon">{{ getTrendIcon(dashboardData.cancelledTrend.direction) }}</span>
            <span class="trend-value">{{ dashboardData.cancelledTrend.percentage }}%</span>
            <span class="trend-period">cancellation rate</span>
          </div>
        </div>
      </div>

      <!-- Total Revenue Card -->
      <div class="summary-card revenue-card">
        <div class="card-header">
          <div class="card-icon revenue-icon">💰</div>
          <div class="currency-badge">LKR</div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value">Rs. {{ formatCurrency(animatedValues.totalRevenue) }}</div>
            <div class="metric-label">Total Revenue</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Today</span>
              <span class="sub-value">Rs. {{ formatCurrency(dashboardData.todayRevenue) }}</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">Month</span>
              <span class="sub-value">Rs. {{ formatCurrency(dashboardData.monthRevenue) }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="trend-indicator" :class="dashboardData.revenueTrend.direction">
            <span class="trend-icon">{{ getTrendIcon(dashboardData.revenueTrend.direction) }}</span>
            <span class="trend-value">{{ dashboardData.revenueTrend.percentage }}%</span>
            <span class="trend-period">vs last month</span>
          </div>
        </div>
      </div>

      <!-- Platform Commission Card -->
      <div class="summary-card commission-card">
        <div class="card-header">
          <div class="card-icon commission-icon">🏦</div>
          <div class="commission-rate">15%</div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value">Rs. {{ formatCurrency(animatedValues.platformCommission) }}</div>
            <div class="metric-label">Platform Commission</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Today</span>
              <span class="sub-value">Rs. {{ formatCurrency(dashboardData.todayCommission) }}</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">Margin</span>
              <span class="sub-value">{{ dashboardData.commissionMargin }}%</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="trend-indicator" :class="dashboardData.commissionTrend.direction">
            <span class="trend-icon">{{ getTrendIcon(dashboardData.commissionTrend.direction) }}</span>
            <span class="trend-value">{{ dashboardData.commissionTrend.percentage }}%</span>
            <span class="trend-period">commission growth</span>
          </div>
        </div>
      </div>

      <!-- Pending Settlements Card -->
      <div class="summary-card settlements-card">
        <div class="card-header">
          <div class="card-icon settlements-icon">⏳</div>
          <div class="pending-count">{{ dashboardData.pendingCount }}</div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value">Rs. {{ formatCurrency(animatedValues.pendingSettlements) }}</div>
            <div class="metric-label">Pending Settlements</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Restaurants</span>
              <span class="sub-value">{{ dashboardData.pendingRestaurants }}</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">Avg Days</span>
              <span class="sub-value">{{ dashboardData.avgSettlementDays }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="settlement-progress">
            <div class="progress-bar">
              <div class="progress-fill" :style="{ width: settlementProgress + '%' }"></div>
            </div>
            <span class="progress-text">{{ settlementProgress }}% processed</span>
          </div>
        </div>
      </div>

      <!-- Refund Amount Card -->
      <div class="summary-card refund-card">
        <div class="card-header">
          <div class="card-icon refund-icon">💸</div>
          <div class="refund-status" :class="refundStatusClass">{{ refundStatus }}</div>
        </div>
        <div class="card-content">
          <div class="primary-metric">
            <div class="metric-value">Rs. {{ formatCurrency(animatedValues.refundAmount) }}</div>
            <div class="metric-label">Refund Amount</div>
          </div>
          <div class="secondary-metrics">
            <div class="sub-metric">
              <span class="sub-label">Today</span>
              <span class="sub-value">Rs. {{ formatCurrency(dashboardData.todayRefunds) }}</span>
            </div>
            <div class="sub-metric">
              <span class="sub-label">Month</span>
              <span class="sub-value">Rs. {{ formatCurrency(dashboardData.monthRefunds) }}</span>
            </div>
          </div>
        </div>
        <div class="card-footer">
          <div class="trend-indicator" :class="dashboardData.refundTrend.direction">
            <span class="trend-icon">{{ getTrendIcon(dashboardData.refundTrend.direction) }}</span>
            <span class="trend-value">{{ dashboardData.refundTrend.percentage }}%</span>
            <span class="trend-period">refund rate</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive } from 'vue'

export default {
  name: 'AdvancedOrderDashboard',
  setup() {
    const isRefreshing = ref(false)
    const lastUpdated = ref(new Date().toLocaleTimeString())
    
    const dashboardData = reactive({
      totalOrders: 1247,
      todayOrders: 89,
      monthOrders: 1247,
      ordersTrend: { direction: 'up', percentage: 12.5 },
      
      activeOrders: 34,
      preparingOrders: 18,
      onTheWayOrders: 16,
      
      lateOrders: 7,
      avgDelay: 23,
      criticalLate: 3,
      lateTrend: { direction: 'down', percentage: 8.2 },
      
      cancelledOrders: 156,
      todayCancelled: 12,
      cancelledTrend: { direction: 'up', percentage: 3.1 },
      
      totalRevenue: 2847650.75,
      todayRevenue: 125430.50,
      monthRevenue: 2847650.75,
      revenueTrend: { direction: 'up', percentage: 18.7 },
      
      platformCommission: 427147.61,
      todayCommission: 18814.58,
      commissionMargin: 15.0,
      commissionTrend: { direction: 'up', percentage: 22.3 },
      
      pendingSettlements: 156780.25,
      pendingCount: 23,
      pendingRestaurants: 15,
      avgSettlementDays: 3.2,
      
      refundAmount: 45230.80,
      todayRefunds: 2150.00,
      monthRefunds: 45230.80,
      refundTrend: { direction: 'down', percentage: 5.4 }
    })

    const animatedValues = reactive({
      totalOrders: 0,
      activeOrders: 0,
      lateOrders: 0,
      cancelledOrders: 0,
      totalRevenue: 0,
      platformCommission: 0,
      pendingSettlements: 0,
      refundAmount: 0
    })

    const cancelledPercentage = computed(() => {
      return ((dashboardData.cancelledOrders / dashboardData.totalOrders) * 100).toFixed(1)
    })

    const preparingPercentage = computed(() => {
      return (dashboardData.preparingOrders / dashboardData.activeOrders) * 100
    })

    const onWayPercentage = computed(() => {
      return (dashboardData.onTheWayOrders / dashboardData.activeOrders) * 100
    })

    const settlementProgress = computed(() => {
      return Math.round(((dashboardData.totalRevenue - dashboardData.pendingSettlements) / dashboardData.totalRevenue) * 100)
    })

    const refundStatus = computed(() => {
      const rate = (dashboardData.refundAmount / dashboardData.totalRevenue) * 100
      if (rate < 2) return 'LOW'
      if (rate < 5) return 'NORMAL'
      return 'HIGH'
    })

    const refundStatusClass = computed(() => {
      const status = refundStatus.value
      return {
        'status-low': status === 'LOW',
        'status-normal': status === 'NORMAL',
        'status-high': status === 'HIGH'
      }
    })

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

    const getTrendIcon = (direction) => {
      return direction === 'up' ? '↗️' : '↘️'
    }

    const animateValue = (key, target, duration = 2000) => {
      const start = animatedValues[key]
      const increment = (target - start) / (duration / 16)
      
      const animate = () => {
        animatedValues[key] += increment
        if ((increment > 0 && animatedValues[key] < target) || 
            (increment < 0 && animatedValues[key] > target)) {
          requestAnimationFrame(animate)
        } else {
          animatedValues[key] = target
        }
      }
      animate()
    }

    const refreshData = async () => {
      isRefreshing.value = true
      
      // Simulate API call
      await new Promise(resolve => setTimeout(resolve, 1500))
      
      lastUpdated.value = new Date().toLocaleTimeString()
      isRefreshing.value = false
    }

    const navigateToOrders = () => {
      console.log('Navigate to orders page')
    }

    onMounted(() => {
      // Animate all values on mount
      setTimeout(() => {
        animateValue('totalOrders', dashboardData.totalOrders)
        animateValue('activeOrders', dashboardData.activeOrders)
        animateValue('lateOrders', dashboardData.lateOrders)
        animateValue('cancelledOrders', dashboardData.cancelledOrders)
        animateValue('totalRevenue', dashboardData.totalRevenue)
        animateValue('platformCommission', dashboardData.platformCommission)
        animateValue('pendingSettlements', dashboardData.pendingSettlements)
        animateValue('refundAmount', dashboardData.refundAmount)
      }, 500)
    })

    return {
      isRefreshing,
      lastUpdated,
      dashboardData,
      animatedValues,
      cancelledPercentage,
      preparingPercentage,
      onWayPercentage,
      settlementProgress,
      refundStatus,
      refundStatusClass,
      formatCurrency,
      getTrendIcon,
      refreshData,
      navigateToOrders
    }
  }
}
</script>

<style scoped>
.advanced-dashboard {
  min-height: 100vh;
  background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
  padding: 2rem;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 3rem;
  padding: 2rem;
  background: rgba(15, 23, 42, 0.8);
  border-radius: 20px;
  border: 1px solid rgba(59, 130, 246, 0.2);
  backdrop-filter: blur(20px);
}

.header-content {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.dashboard-title {
  font-size: 2.5rem;
  font-weight: 800;
  background: linear-gradient(135deg, #3b82f6, #8b5cf6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  margin: 0;
}

.last-updated {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #94a3b8;
  font-size: 0.875rem;
}

.update-indicator {
  width: 8px;
  height: 8px;
  background: #10b981;
  border-radius: 50%;
  animation: pulse 2s infinite;
}

.refresh-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 1rem 2rem;
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
  border: none;
  border-radius: 12px;
  color: white;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px rgba(59, 130, 246, 0.3);
}

.refresh-btn.loading .refresh-icon {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

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

.summary-card {
  background: rgba(15, 23, 42, 0.9);
  border-radius: 24px;
  border: 1px solid rgba(59, 130, 246, 0.2);
  backdrop-filter: blur(20px);
  overflow: hidden;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  cursor: pointer;
  position: relative;
}

.summary-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.05), transparent);
  transition: left 0.6s;
}

.summary-card:hover {
  transform: translateY(-8px) scale(1.02);
  border-color: rgba(59, 130, 246, 0.4);
  box-shadow: 0 25px 50px rgba(0,0,0,0.3);
}

.summary-card:hover::before {
  left: 100%;
}

.summary-card.critical {
  border-color: rgba(239, 68, 68, 0.5);
  animation: criticalPulse 2s infinite;
}

@keyframes criticalPulse {
  0%, 100% { box-shadow: 0 0 0 0 rgba(239, 68, 68, 0.4); }
  50% { box-shadow: 0 0 0 10px rgba(239, 68, 68, 0); }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 2rem 2rem 1rem;
}

.card-icon {
  width: 60px;
  height: 60px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 2rem;
  position: relative;
  overflow: hidden;
}

.orders-icon {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
}

.active-icon {
  background: linear-gradient(135deg, #10b981, #059669);
}

.late-icon {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.cancelled-icon {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.revenue-icon {
  background: linear-gradient(135deg, #10b981, #047857);
}

.commission-icon {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
}

.settlements-icon {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.refund-icon {
  background: linear-gradient(135deg, #ef4444, #b91c1c);
}

.pulse-indicator {
  width: 12px;
  height: 12px;
  background: #10b981;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

.alert-badge {
  width: 24px;
  height: 24px;
  background: #ef4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 700;
  font-size: 0.875rem;
  animation: bounce 1s infinite;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% { transform: translateY(0); }
  40% { transform: translateY(-10px); }
  60% { transform: translateY(-5px); }
}

.percentage-badge, .currency-badge, .commission-rate, .pending-count {
  padding: 0.5rem 1rem;
  background: rgba(59, 130, 246, 0.2);
  border: 1px solid rgba(59, 130, 246, 0.3);
  border-radius: 8px;
  color: #3b82f6;
  font-size: 0.875rem;
  font-weight: 600;
}

.refund-status {
  padding: 0.5rem 1rem;
  border-radius: 8px;
  font-size: 0.75rem;
  font-weight: 700;
}

.status-low {
  background: rgba(16, 185, 129, 0.2);
  color: #10b981;
}

.status-normal {
  background: rgba(245, 158, 11, 0.2);
  color: #f59e0b;
}

.status-high {
  background: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.card-content {
  padding: 0 2rem 1rem;
}

.primary-metric {
  margin-bottom: 1.5rem;
}

.metric-value {
  font-size: 2.5rem;
  font-weight: 800;
  color: #f8fafc;
  margin-bottom: 0.5rem;
  line-height: 1;
}

.metric-value.critical {
  color: #ef4444;
}

.metric-label {
  color: #94a3b8;
  font-size: 1rem;
  font-weight: 500;
}

.secondary-metrics {
  display: flex;
  justify-content: space-between;
  gap: 1rem;
}

.sub-metric {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.sub-label {
  color: #64748b;
  font-size: 0.75rem;
  text-transform: uppercase;
  font-weight: 600;
}

.sub-value {
  color: #f8fafc;
  font-weight: 700;
  font-size: 0.875rem;
}

.sub-value.critical {
  color: #ef4444;
}

.card-footer {
  padding: 1rem 2rem 2rem;
}

.trend-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border-radius: 12px;
  font-size: 0.875rem;
  font-weight: 600;
}

.trend-indicator.up {
  background: rgba(16, 185, 129, 0.1);
  border: 1px solid rgba(16, 185, 129, 0.2);
  color: #10b981;
}

.trend-indicator.down {
  background: rgba(239, 68, 68, 0.1);
  border: 1px solid rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

.trend-icon {
  font-size: 1rem;
}

.trend-period {
  color: #94a3b8;
  font-weight: 400;
}

.status-bar {
  display: flex;
  height: 6px;
  background: rgba(30, 41, 59, 0.6);
  border-radius: 3px;
  overflow: hidden;
}

.status-segment {
  transition: width 1s ease-in-out;
}

.status-segment.preparing {
  background: linear-gradient(90deg, #f59e0b, #d97706);
}

.status-segment.on-way {
  background: linear-gradient(90deg, #10b981, #059669);
}

.settlement-progress {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.progress-bar {
  height: 6px;
  background: rgba(30, 41, 59, 0.6);
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #3b82f6, #1d4ed8);
  border-radius: 3px;
  transition: width 1.5s ease-in-out;
}

.progress-text {
  color: #94a3b8;
  font-size: 0.875rem;
  font-weight: 500;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

/* Responsive Design */
@media (max-width: 1200px) {
  .summary-grid {
    grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  }
}

@media (max-width: 768px) {
  .advanced-dashboard {
    padding: 1rem;
  }
  
  .dashboard-header {
    flex-direction: column;
    gap: 1rem;
    text-align: center;
  }
  
  .dashboard-title {
    font-size: 2rem;
  }
  
  .summary-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  
  .card-header {
    padding: 1.5rem 1.5rem 1rem;
  }
  
  .card-content {
    padding: 0 1.5rem 1rem;
  }
  
  .card-footer {
    padding: 1rem 1.5rem 1.5rem;
  }
  
  .metric-value {
    font-size: 2rem;
  }
  
  .secondary-metrics {
    flex-direction: column;
    gap: 0.75rem;
  }
}

@media (max-width: 480px) {
  .card-icon {
    width: 50px;
    height: 50px;
    font-size: 1.5rem;
  }
  
  .metric-value {
    font-size: 1.75rem;
  }
}
</style>