<template>
  <div class="max-w-md mx-auto bg-white p-8 rounded-2xl shadow-xl border border-gray-100 mt-10">
    <h2 class="text-2xl font-bold text-gray-800 mb-6 flex items-center gap-2">
      <span>💸</span> Add Expense
    </h2>

    <form @submit.prevent="handleSubmit" class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700">Kategória</label>
        <select v-model="form.category" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 p-2.5 border">
          <option value="REFUELING">⛽ Tankolás</option>
          <option value="SERVICE">🔧 Szerviz</option>
          <option value="INSURANCE">🛡️ Biztosítás</option>
          <option value="TOLL">🛣️ Útdíj / Matrica</option>
          <option value="FINE">👮 Büntetés</option>
        </select>
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700">Összeg (Ft)</label>
        <input v-model="form.amount" type="number" required class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 p-2.5 border" placeholder="Pl: 25000">
      </div>

      <div>
        <label class="block text-sm font-medium text-gray-700">Km óra állása</label>
        <input v-model="form.odometer_value" type="number" class="mt-1 block w-full rounded-lg border-gray-300 shadow-sm focus:ring-blue-500 focus:border-blue-500 p-2.5 border" placeholder="Pl: 145200">
      </div>

      <button type="submit" class="w-full bg-blue-600 text-white font-bold py-3 rounded-lg hover:bg-blue-700 transition-colors shadow-lg shadow-blue-200">
        Mentés rögzítése
      </button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import api from '@/services/api'

const form = ref({
  category: 'REFUELING',
  amount: null,
  odometer_value: null,
  vehicle_id: 'auto-uuid-helye', // Ezt majd a routerből kapjuk
  date: new Date().toISOString().split('T')[0]
})

const handleSubmit = async () => {
  try {
    // Map frontend fields to backend schema
    const categoryMap = {
      'REFUELING': 'fuel',
      'SERVICE': 'service',
      'INSURANCE': 'insurance',
      'TOLL': 'toll',
      'FINE': 'fine'
    }
    const payload = {
      cost_type: categoryMap[form.value.category] || form.value.category.toLowerCase(),
      amount_local: form.value.amount,
      currency_local: 'HUF',
      mileage_at_cost: form.value.odometer_value,
      date: new Date(form.value.date).toISOString(),
      asset_id: form.value.vehicle_id,
      description: null,
      data: {}
    }
    await api.post('/expenses/', payload)
    alert("Sikeresen mentve!")
  } catch (err) {
    alert("Hiba történt a mentéskor.")
  }
}
</script>