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 /api/v1/assets (Thick Asset endpoint)
    const token = authStore.token
    
    if (!token) {
      throw new Error('Not authenticated')
    }
    
    try {
      // Transform frontend vehicle data to Thick Asset API schema
      // Include all required fields for thick asset creation
      const payload = {
        // Core identification
        vin: vehicle.vin || null, // Send null for draft vehicles
        license_plate: vehicle.licensePlate || 'N/A',
        catalog_id: vehicle.catalogId || null,
        organization_id: vehicle.organizationId || authStore.activeOrgId,
        
        // Ownership fields (required by AssetCreate schema)
        owner_org_id: vehicle.owner_org_id || null,
        operator_org_id: vehicle.operator_org_id || null,
        
        // Thick Asset fields - send even if catalog_id is provided for completeness
        brand: vehicle.brand || vehicle.make || null,
        model: vehicle.model || null,
        vehicle_class: vehicle.vehicleClass || vehicle.class || null,
        fuel_type: vehicle.fuelType || vehicle.fuel || null,
        year_of_manufacture: vehicle.year || vehicle.yearOfManufacture || null,
        engine_capacity: vehicle.engineCapacity || null,
        power_kw: vehicle.powerKw || null,
        transmission: vehicle.transmission || null,
        body_type: vehicle.bodyType || null,
        color: vehicle.color || null,
        current_mileage: vehicle.currentMileage || vehicle.mileage || 0,
        
        // Metadata
        status: vehicle.status || 'draft', // Default to draft for 2-step creation
        data_status: 'incomplete', // Will be updated by backend snapshot sync
        profile_completion_percentage: 0 // Will be calculated by backend
      }
      
      // Remove null values to keep payload clean
      Object.keys(payload).forEach(key => {
        if (payload[key] === null || payload[key] === undefined) {
          delete payload[key]
        }
      })
      
      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()
        let errorMessage = `Failed to add vehicle: ${response.status} ${response.statusText}`
        
        // Handle specific error cases
        if (response.status === 409) {
          errorMessage = 'Duplicate VIN or license plate detected. Please check your input.'
        } else if (response.status === 429) {
          errorMessage = 'Rate limit exceeded. Please try again later.'
        } else if (response.status === 400) {
          errorMessage = `Invalid input: ${errorText}`
        } else if (response.status === 403) {
          errorMessage = 'Permission denied. You may have reached your vehicle limit.'
        }
        
        throw new Error(errorMessage)
      }
      
      const data = await response.json()
      console.log('GarageStore: Thick Asset 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) {
        console.error('GarageStore: No authentication token available')
        throw new Error('Not authenticated')
      }
      
      console.log('GarageStore: Starting vehicle fetch with token', token.substring(0, 20) + '...')
      
      // Call real backend API
      // First try the assets endpoint for user's vehicles
      const apiUrl = `${import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'}/assets/vehicles`
      console.log('GarageStore: Fetching from primary endpoint:', apiUrl)
      
      const response = await fetch(apiUrl, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      })
      
      console.log('GarageStore: Primary endpoint response status:', response.status, response.statusText)
      
      if (!response.ok) {
        // If 404, try alternative endpoint
        if (response.status === 404) {
          console.log('GarageStore: Primary endpoint returned 404, trying user assets endpoint')
          // Try user assets endpoint
          const userApiUrl = `${import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'}/users/me/assets`
          const userResponse = await fetch(userApiUrl, {
            method: 'GET',
            headers: {
              'Authorization': `Bearer ${token}`,
              'Accept': 'application/json'
            }
          })
          
          console.log('GarageStore: User assets endpoint response status:', userResponse.status, userResponse.statusText)
          
          if (!userResponse.ok) {
            let errorBody = ''
            try {
              errorBody = await userResponse.text()
            } catch (e) {
              errorBody = 'Could not read error response'
            }
            console.error('GarageStore: User assets endpoint failed:', {
              status: userResponse.status,
              statusText: userResponse.statusText,
              body: errorBody
            })
            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 {
          let errorBody = ''
          try {
            errorBody = await response.text()
          } catch (e) {
            errorBody = 'Could not read error response'
          }
          console.error('GarageStore: Primary endpoint failed:', {
            status: response.status,
            statusText: response.statusText,
            body: errorBody
          })
          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)
      console.error('GarageStore: Full error stack:', err.stack)
      error.value = err.message
      // NO MORE MOCK DATA FALLBACK - fail properly
      vehicles.value = []
    } finally {
      isLoading.value = false
    }
    
    console.log('GarageStore: Fetch completed, vehicles count:', vehicles.value.length)
    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 => {
      // Safely extract catalog properties with optional chaining
      const catalog = item.catalog || {}
      const catalogMake = catalog?.make || catalog?.brand || null
      const catalogModel = catalog?.model || null
      const catalogFuelType = catalog?.fuel_type || catalog?.fuel || null
      const catalogYear = catalog?.year || catalog?.year_of_manufacture || null
      
      // Safely extract profile completion percentage
      const profileCompletion = item.profile_completion_percentage ||
                               item.profile_completion ||
                               (item.profile_status === 'complete' ? 100 : 0) || 0
      
      // Extract data_status from API (new field for vehicle data completeness)
      const dataStatus = item.data_status || item.status || (item.is_active ? 'active' : 'draft')
      
      return {
        id: item.id || item.asset_id || 0,
        make: item.make || item.brand || item.vehicle_make || catalogMake || 'Unknown',
        model: item.model || item.vehicle_model || catalogModel || 'Unknown',
        year: item.year || item.year_of_manufacture || item.manufacture_year || catalogYear || 2023,
        licensePlate: item.license_plate || item.registration_number || 'N/A',
        status: item.status || (item.is_active ? 'active' : 'draft'),
        data_status: dataStatus,
        profile_completion_percentage: profileCompletion,
        monthlyExpense: item.monthly_expense || item.average_monthly_cost || 0,
        fuelType: item.fuel_type || item.fuel || catalogFuelType || 'Unknown',
        mileage: item.mileage || item.current_mileage || item.odometer_reading || 0,
        imageUrl: item.image_url || item.photo_url || getDefaultImage(item.make || item.brand || catalogMake),
        // Include catalog object for template access with null safety
        catalog: catalog || null
      }
    })
  }
  
  // Helper function to get default image based on make
  function getDefaultImage(make) {
    // Handle null/undefined make with optional chaining and fallback
    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
  }
})