<template>
  <div class="business-bi">
    <h2 class="text-2xl font-bold text-gray-800 mb-6">📊 Business Intelligence Dashboard</h2>
    
    <!-- Key Metrics Cards -->
    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">Fleet Size</p>
            <p class="text-3xl font-bold text-gray-800">{{ businessMetrics.fleetSize }}</p>
          </div>
          <div class="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
            <span class="text-2xl text-blue-600">🚗</span>
          </div>
        </div>
        <p class="text-sm text-gray-500 mt-2">Active vehicles</p>
      </div>

      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">Total Monthly Cost</p>
            <p class="text-3xl font-bold text-gray-800">€{{ formatNumber(businessMetrics.totalMonthlyCost) }}</p>
          </div>
          <div class="w-12 h-12 bg-green-100 rounded-lg flex items-center justify-center">
            <span class="text-2xl text-green-600">💰</span>
          </div>
        </div>
        <p class="text-sm text-gray-500 mt-2">All expenses combined</p>
      </div>

      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">Avg Cost per Km</p>
            <p class="text-3xl font-bold text-gray-800">€{{ businessMetrics.averageCostPerKm.toFixed(2) }}</p>
          </div>
          <div class="w-12 h-12 bg-purple-100 rounded-lg flex items-center justify-center">
            <span class="text-2xl text-purple-600">📈</span>
          </div>
        </div>
        <p class="text-sm text-gray-500 mt-2">Operating efficiency</p>
      </div>

      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <div class="flex items-center justify-between">
          <div>
            <p class="text-sm text-gray-500">Utilization Rate</p>
            <p class="text-3xl font-bold text-gray-800">{{ businessMetrics.utilizationRate }}%</p>
          </div>
          <div class="w-12 h-12 bg-amber-100 rounded-lg flex items-center justify-center">
            <span class="text-2xl text-amber-600">⚡</span>
          </div>
        </div>
        <p class="text-sm text-gray-500 mt-2">Fleet activity</p>
      </div>
    </div>

    <!-- Charts Section -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
      <!-- Monthly Costs Chart -->
      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Monthly Cost Breakdown (Last 6 Months)</h3>
        <div class="h-80">
          <canvas ref="monthlyCostsChart"></canvas>
        </div>
        <div class="mt-4 text-sm text-gray-500">
          <div class="flex items-center space-x-4">
            <div class="flex items-center">
              <div class="w-3 h-3 bg-blue-500 rounded-full mr-2"></div>
              <span>Maintenance</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-green-500 rounded-full mr-2"></div>
              <span>Fuel</span>
            </div>
            <div class="flex items-center">
              <div class="w-3 h-3 bg-amber-500 rounded-full mr-2"></div>
              <span>Insurance</span>
            </div>
          </div>
        </div>
      </div>

      <!-- Fuel Efficiency Trend Chart -->
      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Fuel Efficiency Trend (km per liter)</h3>
        <div class="h-80">
          <canvas ref="fuelEfficiencyChart"></canvas>
        </div>
        <div class="mt-4 text-sm text-gray-500">
          <p>Average: <span class="font-semibold">{{ averageFuelEfficiency.toFixed(1) }} km/L</span></p>
          <p class="text-green-600">↑ {{ ((averageFuelEfficiency - 12) / 12 * 100).toFixed(1) }}% improvement vs industry average</p>
        </div>
      </div>
    </div>

    <!-- Cost per Km and TCO Analysis -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
      <!-- Cost per Km Chart -->
      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Cost per Kilometer Trend</h3>
        <div class="h-64">
          <canvas ref="costPerKmChart"></canvas>
        </div>
        <div class="mt-4 text-sm text-gray-500">
          <p>Average cost: <span class="font-semibold">€{{ averageCostPerKm.toFixed(2) }}/km</span></p>
          <p>Target: <span class="font-semibold">€0.38/km</span></p>
        </div>
      </div>

      <!-- TCO Breakdown -->
      <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
        <h3 class="text-lg font-semibold text-gray-800 mb-4">Total Cost of Ownership (TCO) Breakdown</h3>
        <div class="h-64">
          <canvas ref="tcoChart"></canvas>
        </div>
        <div class="mt-4 text-sm text-gray-500">
          <p>Annual TCO: <span class="font-semibold">€{{ formatNumber(businessMetrics.totalMonthlyCost * 12) }}</span></p>
          <p>Per vehicle: <span class="font-semibold">€{{ formatNumber(Math.round(businessMetrics.totalMonthlyCost * 12 / businessMetrics.fleetSize)) }}/year</span></p>
        </div>
      </div>
    </div>

    <!-- Data Table -->
    <div class="bg-white rounded-xl p-6 shadow border border-gray-200">
      <h3 class="text-lg font-semibold text-gray-800 mb-4">Monthly Performance Details</h3>
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead>
            <tr class="bg-gray-50">
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Month</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Maintenance</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Fuel</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Insurance</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Total</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Cost/km</th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Efficiency</th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="(month, index) in monthlyCosts" :key="month.month">
              <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">{{ month.month }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">€{{ month.maintenance }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">€{{ month.fuel }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">€{{ month.insurance }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-gray-900">€{{ month.total }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">€{{ costPerKmTrends[index]?.cost.toFixed(2) || '0.00' }}</td>
              <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{ fuelEfficiencyTrends[index]?.efficiency.toFixed(1) || '0.0' }} km/L</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Insights Panel -->
    <div class="mt-8 bg-gradient-to-r from-gray-800 to-gray-900 rounded-2xl p-6 text-white shadow-lg">
      <div class="flex items-center mb-4">
        <div class="w-10 h-10 bg-white/20 rounded-full flex items-center justify-center mr-4">
          <span class="text-xl">💡</span>
        </div>
        <div>
          <h3 class="text-xl font-bold">Business Insights</h3>
          <p class="text-gray-300">AI-powered recommendations</p>
        </div>
      </div>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mt-6">
        <div class="bg-white/10 p-4 rounded-xl">
          <h4 class="font-semibold mb-2">💰 Cost Optimization</h4>
          <p class="text-sm text-gray-200">Maintenance costs are {{ getCostComparison() }} than industry average. Consider preventive maintenance scheduling to reduce unexpected repairs.</p>
        </div>
        <div class="bg-white/10 p-4 rounded-xl">
          <h4 class="font-semibold mb-2">⛽ Fuel Efficiency</h4>
          <p class="text-sm text-gray-200">Your fleet is {{ getEfficiencyComparison() }} efficient than benchmark. Continue driver training programs for optimal performance.</p>
        </div>
        <div class="bg-white/10 p-4 rounded-xl">
          <h4 class="font-semibold mb-2">📅 Utilization Rate</h4>
          <p class="text-sm text-gray-200">{{ businessMetrics.utilizationRate }}% utilization is good. Consider dynamic routing to increase to 85% target.</p>
        </div>
        <div class="bg-white/10 p-4 rounded-xl">
          <h4 class="font-semibold mb-2">🔧 Downtime Management</h4>
          <p class="text-sm text-gray-200">{{ businessMetrics.downtimeHours }} hours/month downtime. Predictive maintenance could reduce this by 30%.</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useAnalyticsStore } from '@/stores/analyticsStore'
import { storeToRefs } from 'pinia'
import { Chart, registerables } from 'chart.js'

Chart.register(...registerables)

const analyticsStore = useAnalyticsStore()
const { monthlyCosts, fuelEfficiencyTrends, costPerKmTrends, businessMetrics, averageFuelEfficiency, averageCostPerKm } = storeToRefs(analyticsStore)

const monthlyCostsChart = ref(null)
const fuelEfficiencyChart = ref(null)
const costPerKmChart = ref(null)
const tcoChart = ref(null)

let chartInstances = []

const formatNumber = (num) => {
  return new Intl.NumberFormat('en-US').format(num)
}

const getCostComparison = () => {
  const avgMaintenance = monthlyCosts.value.reduce((sum, month) => sum + month.maintenance, 0) / monthlyCosts.value.length
  return avgMaintenance > 500 ? 'higher' : avgMaintenance < 400 ? 'lower' : 'similar'
}

const getEfficiencyComparison = () => {
  return averageFuelEfficiency.value > 13 ? 'more' : averageFuelEfficiency.value < 12 ? 'less' : 'equally'
}

onMounted(() => {
  // Monthly Costs Chart (Stacked Bar)
  if (monthlyCostsChart.value) {
    const ctx = monthlyCostsChart.value.getContext('2d')
    const chart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: monthlyCosts.value.map(m => m.month),
        datasets: [
          {
            label: 'Maintenance',
            data: monthlyCosts.value.map(m => m.maintenance),
            backgroundColor: '#3b82f6',
            stack: 'Stack 0',
          },
          {
            label: 'Fuel',
            data: monthlyCosts.value.map(m => m.fuel),
            backgroundColor: '#10b981',
            stack: 'Stack 0',
          },
          {
            label: 'Insurance',
            data: monthlyCosts.value.map(m => m.insurance),
            backgroundColor: '#f59e0b',
            stack: 'Stack 0',
          },
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          x: {
            stacked: true,
          },
          y: {
            stacked: true,
            beginAtZero: true,
            title: {
              display: true,
              text: 'Cost (€)'
            }
          }
        }
      }
    })
    chartInstances.push(chart)
  }

  // Fuel Efficiency Chart (Line)
  if (fuelEfficiencyChart.value) {
    const ctx = fuelEfficiencyChart.value.getContext('2d')
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: fuelEfficiencyTrends.value.map(m => m.month),
        datasets: [
          {
            label: 'Fuel Efficiency (km/L)',
            data: fuelEfficiencyTrends.value.map(m => m.efficiency),
            borderColor: '#8b5cf6',
            backgroundColor: 'rgba(139, 92, 246, 0.1)',
            fill: true,
            tension: 0.4,
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: false,
            title: {
              display: true,
              text: 'km per liter'
            }
          }
        }
      }
    })
    chartInstances.push(chart)
  }

  // Cost per Km Chart (Line)
  if (costPerKmChart.value) {
    const ctx = costPerKmChart.value.getContext('2d')
    const chart = new Chart(ctx, {
      type: 'line',
      data: {
        labels: costPerKmTrends.value.map(m => m.month),
        datasets: [
          {
            label: 'Cost per Kilometer (€)',
            data: costPerKmTrends.value.map(m => m.cost),
            borderColor: '#ef4444',
            backgroundColor: 'rgba(239, 68, 68, 0.1)',
            fill: true,
            tension: 0.4,
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          y: {
            beginAtZero: false,
            title: {
              display: true,
              text: '€ per km'
            }
          }
        }
      }
    })
    chartInstances.push(chart)
  }

  // TCO Chart (Doughnut)
  if (tcoChart.value) {
    const ctx = tcoChart.value.getContext('2d')
    const totalMaintenance = monthlyCosts.value.reduce((sum, month) => sum + month.maintenance, 0)
    const totalFuel = monthlyCosts.value.reduce((sum, month) => sum + month.fuel, 0)
    const totalInsurance = monthlyCosts.value.reduce((sum, month) => sum + month.insurance, 0)
    
    const chart = new Chart(ctx, {
      type: 'doughnut',
      data: {
        labels: ['Maintenance', 'Fuel', 'Insurance'],
        datasets: [
          {
            data: [totalMaintenance, totalFuel, totalInsurance],
            backgroundColor: ['#3b82f6', '#10b981', '#f59e0b'],
            borderWidth: 2,
            borderColor: '#ffffff',
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            position: 'bottom',
          }
        }
      }
    })
    chartInstances.push(chart)
  }
})

onUnmounted(() => {
  chartInstances.forEach(chart => chart.destroy())
  chartInstances = []
})
</script>

<style scoped>
.business-bi {
  font-family: 'Inter', sans-serif;
}
</style>