import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useAuthStore } from './authStore'

export const useAnalyticsStore = defineStore('analytics', () => {
  const authStore = useAuthStore()
  
  // Real data - initially empty, will be fetched from API
  const monthlyCosts = ref([])
  const fuelEfficiencyTrends = ref([])
  const costPerKmTrends = ref([])
  const funFacts = ref({
    totalKmDriven: 0,
    totalTreesSaved: 0,
    totalCo2Saved: 0,
    totalMoneySaved: 0,
    moonTrips: computed(() => Math.round(funFacts.value.totalKmDriven / 384400)),
    earthCircuits: computed(() => Math.round(funFacts.value.totalKmDriven / 40075)),
  })
  const businessMetrics = ref({
    fleetSize: 0,
    averageVehicleAge: 0,
    totalMonthlyCost: 0,
    averageCostPerKm: 0,
    utilizationRate: 0,
    downtimeHours: 0,
  })
  
  const isLoading = ref(false)
  const error = ref(null)

  // Getters
  const totalCosts = computed(() => {
    return monthlyCosts.value.reduce((sum, month) => sum + month.total, 0)
  })

  const averageMonthlyCost = computed(() => {
    return monthlyCosts.value.length > 0 ? totalCosts.value / monthlyCosts.value.length : 0
  })

  const averageFuelEfficiency = computed(() => {
    const sum = fuelEfficiencyTrends.value.reduce((acc, item) => acc + item.efficiency, 0)
    return fuelEfficiencyTrends.value.length > 0 ? sum / fuelEfficiencyTrends.value.length : 0
  })

  const averageCostPerKm = computed(() => {
    const sum = costPerKmTrends.value.reduce((acc, item) => acc + item.cost, 0)
    return costPerKmTrends.value.length > 0 ? sum / costPerKmTrends.value.length : 0
  })

  // Actions
  function addMonthlyCost(data) {
    monthlyCosts.value.push(data)
  }

  function updateFuelEfficiency(month, efficiency) {
    const index = fuelEfficiencyTrends.value.findIndex(item => item.month === month)
    if (index !== -1) {
      fuelEfficiencyTrends.value[index].efficiency = efficiency
    }
  }

  function updateFunFacts(newFacts) {
    Object.assign(funFacts.value, newFacts)
  }

  // Real API fetch - NO MORE MOCK DATA
  async function fetchDashboardAnalytics() {
    isLoading.value = true
    error.value = null
    
    try {
      // Get auth token
      const token = authStore.token
      
      if (!token) {
        throw new Error('Not authenticated')
      }
      
      // Call real backend API
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'}/analytics/dashboard`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`Failed to fetch analytics: ${response.status} ${response.statusText}`)
      }
      
      const data = await response.json()
      console.log('AnalyticsStore: Fetched dashboard analytics', data)
      
      // Transform API response to frontend format
      monthlyCosts.value = data.monthly_costs || []
      fuelEfficiencyTrends.value = data.fuel_efficiency_trends || []
      costPerKmTrends.value = data.cost_per_km_trends || []
      
      if (data.fun_facts) {
        funFacts.value = {
          totalKmDriven: data.fun_facts.total_km_driven || 0,
          totalTreesSaved: data.fun_facts.total_trees_saved || 0,
          totalCo2Saved: data.fun_facts.total_co2_saved || 0,
          totalMoneySaved: data.fun_facts.total_money_saved || 0,
          moonTrips: computed(() => Math.round((data.fun_facts.total_km_driven || 0) / 384400)),
          earthCircuits: computed(() => Math.round((data.fun_facts.total_km_driven || 0) / 40075)),
        }
      }
      
      if (data.business_metrics) {
        businessMetrics.value = {
          fleetSize: data.business_metrics.fleet_size || 0,
          averageVehicleAge: data.business_metrics.average_vehicle_age || 0,
          totalMonthlyCost: data.business_metrics.total_monthly_cost || 0,
          averageCostPerKm: data.business_metrics.average_cost_per_km || 0,
          utilizationRate: data.business_metrics.utilization_rate || 0,
          downtimeHours: data.business_metrics.downtime_hours || 0,
        }
      }
      
      return data
    } catch (err) {
      console.error('AnalyticsStore: Error fetching analytics', err)
      error.value = err.message
      // Keep empty data (no mock fallback)
    } finally {
      isLoading.value = false
    }
  }

  // Fetch vehicle-specific analytics
  async function fetchVehicleAnalytics(vehicleId) {
    isLoading.value = true
    error.value = null
    
    try {
      const token = authStore.token
      
      if (!token) {
        throw new Error('Not authenticated')
      }
      
      // Call vehicle summary endpoint
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'}/analytics/${vehicleId}/summary`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        throw new Error(`Failed to fetch vehicle analytics: ${response.status} ${response.statusText}`)
      }
      
      const data = await response.json()
      console.log('AnalyticsStore: Fetched vehicle analytics', data)
      
      // For now, just return the data - frontend components can use it directly
      return data
    } catch (err) {
      console.error('AnalyticsStore: Error fetching vehicle analytics', err)
      error.value = err.message
      throw err
    } finally {
      isLoading.value = false
    }
  }

  // Fetch fleet analytics (aggregated)
  async function fetchFleetAnalytics() {
    // For now, use the dashboard endpoint which includes fleet metrics
    return fetchDashboardAnalytics()
  }

  return {
    // State
    monthlyCosts,
    fuelEfficiencyTrends,
    costPerKmTrends,
    funFacts,
    businessMetrics,
    isLoading,
    error,

    // Getters
    totalCosts,
    averageMonthlyCost,
    averageFuelEfficiency,
    averageCostPerKm,

    // Actions
    addMonthlyCost,
    updateFuelEfficiency,
    updateFunFacts,
    fetchDashboardAnalytics,
    fetchVehicleAnalytics,
    fetchFleetAnalytics,
  }
})