<script setup>
import { ref, onMounted, watch } from 'vue'
import { useGarageStore } from '../../stores/garageStore'
import { useAuthStore } from '../../stores/authStore'

const emit = defineEmits(['close'])
const garageStore = useGarageStore()
const authStore = useAuthStore()

// Form fields
const make = ref('')
const model = ref('')
const generation = ref('')
const engine = ref('')
const engineId = ref(null) // NEW: Store the engine/catalog ID
const licensePlate = ref('')
const year = ref('')
const fuelType = ref('petrol')
const isLoading = ref(false)
const error = ref(null)

// Catalog data
const makes = ref([])
const models = ref([])
const generations = ref([])
const engines = ref([])

// Loading states
const loadingMakes = ref(false)
const loadingModels = ref(false)
const loadingGenerations = ref(false)
const loadingEngines = ref(false)

// Search filters
const makeSearch = ref('')
const modelSearch = ref('')
const generationSearch = ref('')
const engineSearch = ref('')

// Filtered lists based on search
const filteredMakes = ref([])
const filteredModels = ref([])
const filteredGenerations = ref([])
const filteredEngines = ref([])

// Fetch makes on component mount
onMounted(async () => {
  await fetchMakes()
})

// Watch for search changes
watch(makeSearch, (val) => {
  filteredMakes.value = makes.value.filter(m =>
    m.toLowerCase().includes(val.toLowerCase())
  )
})

watch(modelSearch, (val) => {
  filteredModels.value = models.value.filter(m =>
    m.toLowerCase().includes(val.toLowerCase())
  )
})

watch(generationSearch, (val) => {
  filteredGenerations.value = generations.value.filter(g =>
    g.toLowerCase().includes(val.toLowerCase())
  )
})

watch(engineSearch, (val) => {
  filteredEngines.value = engines.value.filter(e =>
    e.variant.toLowerCase().includes(val.toLowerCase())
  )
})

// Watch for make selection to fetch models
watch(make, async (newMake) => {
  if (newMake) {
    await fetchModels(newMake)
    model.value = ''
    generation.value = ''
    engine.value = ''
    engineId.value = null
    generations.value = []
    engines.value = []
  } else {
    models.value = []
    generations.value = []
    engines.value = []
  }
})

// Watch for model selection to fetch generations
watch(model, async (newModel) => {
  if (newModel && make.value) {
    await fetchGenerations(make.value, newModel)
    generation.value = ''
    engine.value = ''
    engineId.value = null
    engines.value = []
  } else {
    generations.value = []
    engines.value = []
  }
})

// Watch for generation selection to fetch engines
watch(generation, async (newGen) => {
  if (newGen && make.value && model.value) {
    await fetchEngines(make.value, model.value, newGen)
    engine.value = ''
    engineId.value = null
  } else {
    engines.value = []
  }
})

// Watch for engine selection to auto-fill fuel type and capture ID
watch(engine, (newEngine) => {
  if (newEngine) {
    const selectedEngine = engines.value.find(e => e.variant === newEngine)
    if (selectedEngine) {
      // Store the engine ID for API call
      engineId.value = selectedEngine.id
      // Auto-fill fuel type if available
      if (selectedEngine.fuel_type) {
        fuelType.value = selectedEngine.fuel_type.toLowerCase()
      }
    }
  } else {
    engineId.value = null
  }
})

// API calls
async function fetchMakes() {
  loadingMakes.value = true
  try {
    const token = authStore.token
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'
    const response = await fetch(`${apiBaseUrl}/catalog/makes`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })
    if (!response.ok) throw new Error(`Failed to fetch makes: ${response.status}`)
    makes.value = await response.json()
    filteredMakes.value = makes.value
  } catch (err) {
    console.error('Error fetching makes:', err)
    error.value = 'Could not load makes. Please try again.'
  } finally {
    loadingMakes.value = false
  }
}

async function fetchModels(makeName) {
  loadingModels.value = true
  try {
    const token = authStore.token
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'
    const response = await fetch(`${apiBaseUrl}/catalog/models?make=${encodeURIComponent(makeName)}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })
    if (!response.ok) throw new Error(`Failed to fetch models: ${response.status}`)
    models.value = await response.json()
    filteredModels.value = models.value
  } catch (err) {
    console.error('Error fetching models:', err)
    error.value = 'Could not load models for this make.'
  } finally {
    loadingModels.value = false
  }
}

async function fetchGenerations(makeName, modelName) {
  loadingGenerations.value = true
  try {
    const token = authStore.token
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'
    const response = await fetch(`${apiBaseUrl}/catalog/generations?make=${encodeURIComponent(makeName)}&model=${encodeURIComponent(modelName)}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })
    if (!response.ok) throw new Error(`Failed to fetch generations: ${response.status}`)
    generations.value = await response.json()
    filteredGenerations.value = generations.value
  } catch (err) {
    console.error('Error fetching generations:', err)
    error.value = 'Could not load generations for this model.'
  } finally {
    loadingGenerations.value = false
  }
}

async function fetchEngines(makeName, modelName, genName) {
  loadingEngines.value = true
  try {
    const token = authStore.token
    const apiBaseUrl = import.meta.env.VITE_API_BASE_URL || 'https://dev.servicefinder.hu'
    const response = await fetch(`${apiBaseUrl}/catalog/engines?make=${encodeURIComponent(makeName)}&model=${encodeURIComponent(modelName)}&gen=${encodeURIComponent(genName)}`, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Accept': 'application/json'
      }
    })
    if (!response.ok) throw new Error(`Failed to fetch engines: ${response.status}`)
    const engineData = await response.json()
    engines.value = engineData.map(e => ({
      variant: e.variant,
      fuel_type: e.fuel_type,
      id: e.id
    }))
    filteredEngines.value = engines.value
  } catch (err) {
    console.error('Error fetching engines:', err)
    error.value = 'Could not load engines for this generation.'
  } finally {
    loadingEngines.value = false
  }
}

const handleSubmit = async () => {
  error.value = null
  isLoading.value = true
  
  try {
    // Prepare vehicle data for the API
    const vehicleData = {
      make: make.value,
      model: model.value,
      licensePlate: licensePlate.value,
      year: parseInt(year.value) || new Date().getFullYear(),
      fuelType: fuelType.value,
      generation: generation.value,
      engine: engine.value,
      // Include the catalog ID (engine ID) for API
      catalogId: engineId.value,
      // Include organization ID (use active organization ID)
      organizationId: authStore.activeOrgId
    }
    
    // Call the garage store to add vehicle
    await garageStore.addVehicle(vehicleData)
    
    // Show success message
    alert('Sikeres mentés! Jármű hozzáadva.')
    
    // Reset form
    make.value = ''
    model.value = ''
    generation.value = ''
    engine.value = ''
    engineId.value = null
    licensePlate.value = ''
    year.value = ''
    fuelType.value = 'petrol'
    makes.value = []
    models.value = []
    generations.value = []
    engines.value = []
    
    // Close modal
    emit('close')
  } catch (err) {
    console.error('Error adding vehicle:', err)
    error.value = err.message || 'Ismeretlen hiba történt'
    alert(`Hiba: ${error.value}`)
  } finally {
    isLoading.value = false
  }
}

const closeModal = () => {
  emit('close')
}
</script>

<template>
  <!-- Modal Backdrop -->
  <div class="fixed inset-0 z-[100] flex items-center justify-center bg-black bg-opacity-50 p-4" @click.self="closeModal">
    <!-- Modal Container -->
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden">
      <!-- Modal Header -->
      <div class="flex items-center justify-between p-6 border-b border-gray-200">
        <h2 class="text-xl font-bold text-gray-900">Jármű hozzáadása</h2>
        <button @click="closeModal" class="text-gray-500 hover:text-gray-700 transition-colors">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- Modal Body -->
      <div class="p-6">
        <form @submit.prevent="handleSubmit" class="space-y-5">
          <!-- Make -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Gyártó</label>
            <input
              v-model="make"
              type="text"
              required
              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-blue-900 placeholder-blue-700"
              placeholder="Pl.: Toyota"
            />
          </div>

          <!-- Model -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Modell</label>
            <input
              v-model="model"
              type="text"
              required
              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-blue-900 placeholder-blue-700"
              placeholder="Pl.: Corolla"
            />
          </div>

          <!-- License Plate -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Rendszám</label>
            <input
              v-model="licensePlate"
              type="text"
              required
              class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-blue-900 placeholder-blue-700"
              placeholder="Pl.: ABC-123"
            />
          </div>

          <!-- Year and Fuel Type in a grid -->
          <div class="grid grid-cols-2 gap-4">
            <!-- Year -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Évjárat</label>
              <input
                v-model="year"
                type="number"
                min="1900"
                :max="new Date().getFullYear() + 1"
                required
                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-blue-900 placeholder-blue-700"
                placeholder="2023"
              />
            </div>

            <!-- Fuel Type -->
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-2">Üzemanyag típus</label>
              <select
                v-model="fuelType"
                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition text-blue-900"
              >
                <option value="petrol">Benzin</option>
                <option value="diesel">Dízel</option>
                <option value="electric">Elektromos</option>
                <option value="hybrid">Hibrid</option>
                <option value="lpg">LPG</option>
                <option value="other">Egyéb</option>
              </select>
            </div>
          </div>

          <!-- Error Message -->
          <div v-if="error" class="p-3 bg-red-50 border border-red-200 text-red-700 rounded-lg">
            {{ error }}
          </div>

          <!-- Buttons -->
          <div class="flex gap-3 pt-4">
            <button
              type="button"
              @click="closeModal"
              :disabled="isLoading"
              class="flex-1 px-4 py-3 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              Mégse
            </button>
            <button
              type="submit"
              :disabled="isLoading"
              class="flex-1 px-4 py-3 bg-purple-600 hover:bg-purple-700 text-white font-medium rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center"
            >
              <span v-if="isLoading" class="inline-block h-4 w-4 animate-spin rounded-full border-2 border-solid border-white border-r-transparent mr-2"></span>
              {{ isLoading ? 'Feldolgozás...' : 'Jármű hozzáadása' }}
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* Additional custom styles if needed */
</style>