<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { api } from '@/api'

const { t } = useI18n()
const loading = ref(true)
const vehicles = ref<any[]>([])
const showModal = ref(false)
const form = ref({ license_plate: '', brand: '', model: '', year: 2024, color: '', fuel_type: 'diesel' })

onMounted(async () => { await loadData() })

async function loadData() {
  loading.value = true
  try {
    const res = await api.get<any>('/vehicles')
    vehicles.value = res.data.vehicles || []
  } catch (e) { console.error(e) }
  loading.value = false
}

async function createVehicle() {
  try {
    await api.post('/vehicles', form.value)
    showModal.value = false
    form.value = { license_plate: '', brand: '', model: '', year: 2024, color: '', fuel_type: 'diesel' }
    await loadData()
  } catch (e: any) { alert(t('messages.error') + ': ' + e.message) }
}

function statusBadge(s: string): { text: string, class: string, icon: string } {
  const map: Record<string, any> = {
    available: { text: t('vehicles.statuses.available'), class: 'bg-green-100 text-green-700', icon: '✅' },
    in_use: { text: t('vehicles.statuses.inUse'), class: 'bg-blue-100 text-blue-700', icon: '🚗' },
    maintenance: { text: t('vehicles.statuses.maintenance'), class: 'bg-yellow-100 text-yellow-700', icon: '🔧' },
    retired: { text: t('vehicles.statuses.outOfService'), class: 'bg-gray-100 text-gray-700', icon: '⛔' }
  }
  return map[s] || { text: s, class: 'bg-gray-100', icon: '' }
}
</script>

<template>
  <div class="p-6">
    <div class="flex justify-between items-center mb-6">
      <div>
        <h1 class="text-2xl font-bold">🚗 {{ t('vehicles.title') }}</h1>
        <p class="text-gray-500">{{ t('app.title') }}</p>
      </div>
      <button @click="showModal = true" class="btn btn-primary">+ {{ t('vehicles.new') }}</button>
    </div>

    <div v-if="loading" class="text-center py-12">{{ t('app.loading') }}</div>

    <div v-else-if="vehicles.length === 0" class="bg-gray-50 rounded-lg p-12 text-center text-gray-500">
      <p class="text-4xl mb-4">🚗</p>
      <p>{{ t('messages.noData') }}</p>
    </div>

    <div v-else class="grid md:grid-cols-2 lg:grid-cols-3 gap-4">
      <div v-for="v in vehicles" :key="v.id" class="bg-white rounded-lg shadow p-4">
        <div class="flex justify-between items-start">
          <div>
            <h3 class="font-semibold text-lg">{{ v.license_plate }}</h3>
            <p class="text-gray-600">{{ v.brand }} {{ v.model }}</p>
            <p v-if="v.year" class="text-sm text-gray-400">{{ t('vehicles.year') }} {{ v.year }}</p>
          </div>
          <span :class="['px-2 py-1 text-xs rounded', statusBadge(v.status).class]">
            {{ statusBadge(v.status).icon }} {{ statusBadge(v.status).text }}
          </span>
        </div>
        <div class="mt-4 grid grid-cols-2 gap-2 text-sm">
          <div><span class="text-gray-500">{{ t('vehicles.mileage') }}:</span> {{ v.current_mileage?.toLocaleString() || '-' }}</div>
          <div><span class="text-gray-500">{{ t('vehicles.fuelLevel') }}:</span> {{ v.fuel_type }}</div>
          <div v-if="v.tuev_expires" :class="['col-span-2', new Date(v.tuev_expires) < new Date() ? 'text-red-600' : '']">
            {{ t('vehicles.nextService') }}: {{ new Date(v.tuev_expires).toLocaleDateString() }}
          </div>
        </div>
      </div>
    </div>

    <!-- Modal -->
    <div v-if="showModal" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div class="bg-white rounded-lg shadow-xl w-full max-w-md p-6">
        <h2 class="text-xl font-bold mb-4">{{ t('vehicles.new') }}</h2>
        <div class="space-y-4">
          <div>
            <label class="block text-sm font-medium mb-1">{{ t('vehicles.licensePlate') }} *</label>
            <input v-model="form.license_plate" class="input" placeholder="B-AB 1234" />
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">{{ t('vehicles.make') }}</label>
              <input v-model="form.brand" class="input" placeholder="VW" />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">{{ t('vehicles.model') }}</label>
              <input v-model="form.model" class="input" placeholder="Passat" />
            </div>
          </div>
          <div class="grid grid-cols-2 gap-4">
            <div>
              <label class="block text-sm font-medium mb-1">{{ t('vehicles.year') }}</label>
              <input v-model.number="form.year" type="number" class="input" />
            </div>
            <div>
              <label class="block text-sm font-medium mb-1">{{ t('vehicles.fuelLevel') }}</label>
              <select v-model="form.fuel_type" class="input">
                <option value="diesel">Diesel</option>
                <option value="petrol">Benzin</option>
                <option value="electric">Elektro</option>
                <option value="hybrid">Hybrid</option>
              </select>
            </div>
          </div>
        </div>
        <div class="flex justify-end space-x-2 mt-6">
          <button @click="showModal = false" class="btn">{{ t('app.cancel') }}</button>
          <button @click="createVehicle" class="btn btn-primary">{{ t('app.add') }}</button>
        </div>
      </div>
    </div>
  </div>
</template>
