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

export const useGarageStore = defineStore('garage', () => {
  const authStore = useAuthStore()
  
  // Real vehicle data - initially empty, will be fetched from API
  const vehicles = ref([])
  const isLoading = ref(false)
  const error = ref(null)

  // Getters
  const totalVehicles = computed(() => vehicles.value.length)
  const totalMonthlyExpense = computed(() =>
    vehicles.value.reduce((sum, vehicle) => sum + (vehicle.monthlyExpense || 0), 0)
  )
  const vehiclesNeedingService = computed(() =>
    vehicles.value.filter(v => v.status === 'Service Due' || v.status === 'Warning').length
  )

  // Actions
  async function addVehicle(vehicle) {
    // Real API call to POST /assets/vehicles
    const token = authStore.token
    
    if (!token) {
      throw new Error('Not authenticated')
    }
    
    try {
      // Transform frontend vehicle data to API schema
      // For draft vehicles (2-step creation), VIN can be null
      const payload = {
        vin: vehicle.vin || null, // Send null for draft vehicles
        license_plate: vehicle.licensePlate || 'N/A',
        catalog_id: vehicle.catalogId || null,
        organization_id: vehicle.organizationId || 1 // Default org ID
      }
      
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'}/api/v1/assets/vehicles`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: JSON.stringify(payload)
      })
      
      if (!response.ok) {
        const errorText = await response.text()
        throw new Error(`Failed to add vehicle: ${response.status} ${response.statusText} - ${errorText}`)
      }
      
      const data = await response.json()
      console.log('GarageStore: Vehicle created successfully', data)
      
      // After successful save, fetch fresh data from server to ensure consistency
      await fetchVehicles()
      
      return data
    } catch (err) {
      console.error('GarageStore: Error adding vehicle', err)
      throw err
    }
  }

  function removeVehicle(id) {
    // In a real app, this would be an API call to DELETE /assets/{id}
    vehicles.value = vehicles.value.filter(v => v.id !== id)
  }

  function updateVehicle(id, updates) {
    // In a real app, this would be an API call to PATCH /assets/{id}
    const index = vehicles.value.findIndex(v => v.id === id)
    if (index !== -1) {
      vehicles.value[index] = { ...vehicles.value[index], ...updates }
    }
  }

  function getVehicleById(id) {
    return vehicles.value.find(v => v.id === id)
  }

  // Real API fetch - NO MORE MOCK DATA
  async function fetchVehicles() {
    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
      // First try the assets endpoint for user's vehicles
      const response = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'}/api/v1/assets/vehicles`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      })
      
      if (!response.ok) {
        // If 404, try alternative endpoint
        if (response.status === 404) {
          // Try user assets endpoint
          const userResponse = await fetch(`${import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'}/api/v1/users/me/assets`, {
            method: 'GET',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Accept': 'application/json'
            }
          })
          
          if (!userResponse.ok) {
            throw new Error(`Failed to fetch vehicles: ${userResponse.status} ${userResponse.statusText}`)
          }
          
          const data = await userResponse.json()
          console.log('GarageStore: Fetched vehicles from user assets endpoint', data)
          vehicles.value = transformApiResponse(data)
        } else {
          throw new Error(`Failed to fetch vehicles: ${response.status} ${response.statusText}`)
        }
      } else {
        const data = await response.json()
        console.log('GarageStore: Fetched vehicles from assets endpoint', data)
        vehicles.value = transformApiResponse(data)
      }
    } catch (err) {
      console.error('GarageStore: Error fetching vehicles', err)
      error.value = err.message
      // NO MORE MOCK DATA FALLBACK - fail properly
      vehicles.value = []
    } finally {
      isLoading.value = false
    }
    
    return vehicles.value
  }
  
  // Helper function to transform API response to frontend format
  function transformApiResponse(data) {
    if (!Array.isArray(data)) {
      // If single object, wrap in array
      data = [data]
    }
    
    return data.map(item => ({
      id: item.id || item.asset_id || 0,
      make: item.make || item.brand || item.vehicle_make || 'Unknown',
      model: item.model || item.vehicle_model || 'Unknown',
      year: item.year || item.year_of_manufacture || item.manufacture_year || 2023,
      licensePlate: item.license_plate || item.registration_number || 'N/A',
      status: (item.status === 'active' || item.is_active) ? 'OK' : 'Service Due',
      monthlyExpense: item.monthly_expense || item.average_monthly_cost || 0,
      fuelType: item.fuel_type || item.fuel || 'Unknown',
      mileage: item.mileage || item.current_mileage || item.odometer_reading || 0,
      imageUrl: item.image_url || item.photo_url || getDefaultImage(item.make || item.brand)
    }))
  }
  
  // Helper function to get default image based on make
  function getDefaultImage(make) {
    const makeLower = make.toLowerCase()
    if (makeLower.includes('bmw')) {
      return 'https://images.unsplash.com/photo-1555215695-3004980ad54e?w=400&h=300&fit=crop'
    } else if (makeLower.includes('audi')) {
      return 'https://images.unsplash.com/photo-1553440569-bcc63803a83d?w=400&h=300&fit=crop'
    } else if (makeLower.includes('mercedes')) {
      return 'https://images.unsplash.com/photo-1563720223485-8d6d5c5c8c3b?w=400&h=300&fit=crop'
    } else if (makeLower.includes('tesla')) {
      return 'https://images.unsplash.com/photo-1560958089-b8a1929cea89?w=400&h=300&fit=crop'
    }
    return 'https://images.unsplash.com/photo-1549399542-7e3f8b79c341?w=400&h=300&fit=crop'
  }

  return {
    vehicles,
    isLoading,
    error,
    totalVehicles,
    totalMonthlyExpense,
    vehiclesNeedingService,
    addVehicle,
    removeVehicle,
    updateVehicle,
    getVehicleById,
    fetchVehicles
  }
})