<template>
  <div class="max-w-2xl mx-auto bg-white p-8 rounded-2xl shadow-lg mt-6">
    <h2 class="text-2xl font-bold mb-6 flex items-center gap-2">
      <span class="text-3xl">➕</span> Új jármű hozzáadása
    </h2>

    <div class="space-y-6">
      <div>
        <label class="block text-sm font-medium text-gray-700">Márka keresése</label>
        <input v-model="searchQuery" @input="searchBrands" type="text" placeholder="Pl: Audi, Toyota..." class="mt-1 block w-full p-3 border rounded-lg shadow-sm" />
        
        <div v-if="brands.length > 0" class="mt-2 border rounded-lg divide-y bg-gray-50">
          <div v-for="brand in brands" :key="brand.id" @click="selectBrand(brand)" class="p-3 hover:bg-blue-100 cursor-pointer flex justify-between">
            <span class="font-bold">{{ brand.name }}</span>
            <span class="text-xs text-gray-400 italic">{{ brand.country_of_origin }}</span>
          </div>
        </div>
      </div>

      <div v-if="selectedBrand" class="p-4 bg-blue-50 rounded-lg border border-blue-200 animate-fade-in">
        <p class="font-bold text-blue-800">Kiválasztott márka: {{ selectedBrand.name }}</p>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-4">
          <input v-model="form.model_name" type="text" placeholder="Modell (Pl: A4, Corolla)" class="p-2 border rounded" />
          <input v-model="form.plate" type="text" placeholder="Rendszám" class="p-2 border rounded uppercase" />
          <input v-model="form.vin" type="text" placeholder="Alvázszám (opcionális)" class="p-2 border rounded uppercase" />
          <input v-model="form.current_odo" type="number" placeholder="Aktuális km állás" class="p-2 border rounded" />
        </div>
        <button @click="saveVehicle" class="w-full mt-6 bg-blue-700 text-white py-3 rounded-lg font-bold shadow-lg">Jármű mentése a Széfbe</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const searchQuery = ref('')
const brands = ref([])
const selectedBrand = ref(null)
const form = ref({ model_name: '', plate: '', vin: '', current_odo: 0 })

const searchBrands = async () => {
  if (searchQuery.value.length < 2) { brands.value = []; return; }
  const res = await axios.get(`http://192.168.100.43:8000/api/v1/vehicles/search/brands?q=${searchQuery.value}`)
  brands.value = res.data.data
}

const selectBrand = (brand) => {
  selectedBrand.value = brand
  brands.value = []
}

const saveVehicle = async () => {
  const token = localStorage.getItem('token')
  try {
    await axios.post('http://192.168.100.43:8000/api/v1/vehicles/register', {
      brand_id: selectedBrand.value.id,
      ...form.value
    }, { headers: { Authorization: `Bearer ${token}` }})
    router.push('/')
  } catch (err) {
    alert("Hiba a mentés során.")
  }
}
</script>   