<template>
  <div class="reports-charts">
    <div class="charts-header">
      <h3>📊 Analytics & Reports</h3>
      <div class="date-filter">
        <select v-model="selectedPeriod" @change="updateCharts" class="period-select">
          <option value="7d">Last 7 Days</option>
          <option value="30d">Last 30 Days</option>
          <option value="90d">Last 90 Days</option>
        </select>
      </div>
    </div>

    <div class="charts-grid">
      <!-- Orders Over Time -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>📈 Orders Over Time</h4>
          <span class="chart-subtitle">Daily order volume trends</span>
        </div>
        <div class="chart-container">
          <canvas ref="ordersChart"></canvas>
        </div>
      </div>

      <!-- Revenue vs Commission -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>💰 Revenue vs Commission</h4>
          <span class="chart-subtitle">Revenue breakdown analysis</span>
        </div>
        <div class="chart-container">
          <canvas ref="revenueChart"></canvas>
        </div>
      </div>

      <!-- Cancellation Reasons -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>❌ Cancellation Reasons</h4>
          <span class="chart-subtitle">Why orders get cancelled</span>
        </div>
        <div class="chart-container">
          <canvas ref="cancellationChart"></canvas>
        </div>
      </div>

      <!-- Restaurant Performance -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>🏪 Restaurant Performance</h4>
          <span class="chart-subtitle">Top performing restaurants</span>
        </div>
        <div class="chart-container">
          <canvas ref="restaurantChart"></canvas>
        </div>
      </div>

      <!-- Delivery Performance -->
      <div class="chart-card">
        <div class="chart-header">
          <h4>🚴 Delivery Performance</h4>
          <span class="chart-subtitle">Average delivery times</span>
        </div>
        <div class="chart-container">
          <canvas ref="deliveryChart"></canvas>
        </div>
      </div>
    </div>
  </div>
</template>

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

Chart.register(...registerables)

export default {
  name: 'ReportsCharts',
  setup() {
    const selectedPeriod = ref('30d')
    const ordersChart = ref(null)
    const revenueChart = ref(null)
    const cancellationChart = ref(null)
    const restaurantChart = ref(null)
    const deliveryChart = ref(null)

    let chartInstances = {}

    const chartOptions = {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: {
          labels: {
            color: '#e2e8f0',
            font: { size: 12 }
          }
        },
        tooltip: {
          backgroundColor: 'rgba(15, 23, 42, 0.9)',
          titleColor: '#f8fafc',
          bodyColor: '#e2e8f0',
          borderColor: 'rgba(59, 130, 246, 0.3)',
          borderWidth: 1
        }
      },
      scales: {
        x: {
          ticks: { color: '#94a3b8' },
          grid: { color: 'rgba(59, 130, 246, 0.1)' }
        },
        y: {
          ticks: { color: '#94a3b8' },
          grid: { color: 'rgba(59, 130, 246, 0.1)' }
        }
      }
    }

    const initOrdersChart = () => {
      if (!ordersChart.value) return
      
      chartInstances.orders = new Chart(ordersChart.value, {
        type: 'line',
        data: {
          labels: ['Jan 1', 'Jan 2', 'Jan 3', 'Jan 4', 'Jan 5', 'Jan 6', 'Jan 7'],
          datasets: [{
            label: 'Orders',
            data: [45, 52, 38, 65, 59, 80, 72],
            borderColor: '#3b82f6',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            tension: 0.4,
            fill: true
          }]
        },
        options: chartOptions
      })
    }

    const initRevenueChart = () => {
      if (!revenueChart.value) return
      
      chartInstances.revenue = new Chart(revenueChart.value, {
        type: 'bar',
        data: {
          labels: ['Week 1', 'Week 2', 'Week 3', 'Week 4'],
          datasets: [
            {
              label: 'Total Revenue',
              data: [125000, 145000, 132000, 158000],
              backgroundColor: 'rgba(16, 185, 129, 0.8)',
              borderRadius: 8
            },
            {
              label: 'Platform Commission',
              data: [18750, 21750, 19800, 23700],
              backgroundColor: 'rgba(139, 92, 246, 0.8)',
              borderRadius: 8
            }
          ]
        },
        options: {
          ...chartOptions,
          scales: {
            ...chartOptions.scales,
            y: {
              ...chartOptions.scales.y,
              ticks: {
                ...chartOptions.scales.y.ticks,
                callback: (value) => `Rs ${(value / 1000)}k`
              }
            }
          }
        }
      })
    }

    const initCancellationChart = () => {
      if (!cancellationChart.value) return
      
      chartInstances.cancellation = new Chart(cancellationChart.value, {
        type: 'doughnut',
        data: {
          labels: ['Customer Request', 'Restaurant Issue', 'Delivery Issue', 'Payment Failed', 'Other'],
          datasets: [{
            data: [35, 25, 20, 15, 5],
            backgroundColor: [
              'rgba(59, 130, 246, 0.8)',
              'rgba(245, 158, 11, 0.8)',
              'rgba(239, 68, 68, 0.8)',
              'rgba(139, 92, 246, 0.8)',
              'rgba(107, 114, 128, 0.8)'
            ],
            borderWidth: 0
          }]
        },
        options: {
          ...chartOptions,
          scales: undefined
        }
      })
    }

    const initRestaurantChart = () => {
      if (!restaurantChart.value) return
      
      chartInstances.restaurant = new Chart(restaurantChart.value, {
        type: 'horizontalBar',
        data: {
          labels: ['Pizza Palace', 'Burger King', 'Sushi Express', 'Taco Bell', 'KFC'],
          datasets: [{
            label: 'Orders',
            data: [245, 198, 167, 134, 112],
            backgroundColor: [
              'rgba(16, 185, 129, 0.8)',
              'rgba(59, 130, 246, 0.8)',
              'rgba(245, 158, 11, 0.8)',
              'rgba(139, 92, 246, 0.8)',
              'rgba(239, 68, 68, 0.8)'
            ],
            borderRadius: 8
          }]
        },
        options: chartOptions
      })
    }

    const initDeliveryChart = () => {
      if (!deliveryChart.value) return
      
      chartInstances.delivery = new Chart(deliveryChart.value, {
        type: 'radar',
        data: {
          labels: ['Speed', 'Accuracy', 'Customer Rating', 'On-Time %', 'Completion Rate'],
          datasets: [{
            label: 'Average Performance',
            data: [85, 92, 88, 78, 95],
            borderColor: 'rgba(16, 185, 129, 0.8)',
            backgroundColor: 'rgba(16, 185, 129, 0.2)',
            pointBackgroundColor: 'rgba(16, 185, 129, 1)',
            pointBorderColor: '#fff',
            pointHoverBackgroundColor: '#fff',
            pointHoverBorderColor: 'rgba(16, 185, 129, 1)'
          }]
        },
        options: {
          ...chartOptions,
          scales: {
            r: {
              angleLines: { color: 'rgba(59, 130, 246, 0.2)' },
              grid: { color: 'rgba(59, 130, 246, 0.2)' },
              pointLabels: { color: '#94a3b8' },
              ticks: { 
                color: '#94a3b8',
                backdropColor: 'transparent'
              }
            }
          }
        }
      })
    }

    const updateCharts = () => {
      // Mock data update based on selected period
      console.log('Updating charts for period:', selectedPeriod.value)
      // In real implementation, fetch new data from API
    }

    const initAllCharts = async () => {
      await nextTick()
      initOrdersChart()
      initRevenueChart()
      initCancellationChart()
      initRestaurantChart()
      initDeliveryChart()
    }

    onMounted(() => {
      setTimeout(initAllCharts, 100)
    })

    return {
      selectedPeriod,
      ordersChart,
      revenueChart,
      cancellationChart,
      restaurantChart,
      deliveryChart,
      updateCharts
    }
  }
}
</script>

<style scoped>
.reports-charts {
  background: rgba(15, 23, 42, 0.8);
  border-radius: 20px;
  border: 1px solid rgba(59, 130, 246, 0.2);
  backdrop-filter: blur(20px);
  padding: 2rem;
}

.charts-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.charts-header h3 {
  margin: 0;
  color: #f8fafc;
  font-size: 1.5rem;
  font-weight: 700;
}

.period-select {
  padding: 0.75rem 1rem;
  background: rgba(30, 41, 59, 0.8);
  border: 1px solid rgba(59, 130, 246, 0.3);
  border-radius: 12px;
  color: #f8fafc;
  font-weight: 600;
  cursor: pointer;
}

.period-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

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

.chart-card {
  background: rgba(30, 41, 59, 0.6);
  border-radius: 16px;
  padding: 1.5rem;
  border: 1px solid rgba(59, 130, 246, 0.2);
  transition: all 0.3s ease;
}

.chart-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 12px 28px rgba(0, 0, 0, 0.2);
  border-color: rgba(59, 130, 246, 0.4);
}

.chart-header {
  margin-bottom: 1.5rem;
}

.chart-header h4 {
  margin: 0 0 0.25rem 0;
  color: #f8fafc;
  font-size: 1.125rem;
  font-weight: 600;
}

.chart-subtitle {
  color: #94a3b8;
  font-size: 0.875rem;
}

.chart-container {
  position: relative;
  height: 300px;
  width: 100%;
}

.chart-container canvas {
  max-height: 300px;
}

@media (max-width: 1200px) {
  .charts-grid {
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
  }
}

@media (max-width: 768px) {
  .reports-charts {
    padding: 1.5rem;
  }
  
  .charts-header {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }
  
  .charts-grid {
    grid-template-columns: 1fr;
    gap: 1.5rem;
  }
  
  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .chart-card {
    padding: 1rem;
  }
  
  .chart-container {
    height: 200px;
  }
}
</style>