<script setup>
import { ref } from 'vue'
import { useExpenseStore } from '@/stores/expenseStore'
import { useGarageStore } from '@/stores/garageStore'

const emit = defineEmits(['close'])

const expenseStore = useExpenseStore()
const garageStore = useGarageStore()

// Use selected vehicle from garage store, or default to first vehicle
const selectedAssetId = ref(garageStore.selectedVehicle?.id || garageStore.vehicles[0]?.id || '')

const amount = ref('')
const category = ref('fuel')
const date = ref(new Date().toISOString().split('T')[0]) // today
const description = ref('')
const mileage = ref('')
const isLoading = ref(false)
const showDraftLimitModal = ref(false)

const handleSubmit = async () => {
  if (!selectedAssetId.value) {
    alert('Nincs kiválasztott jármű. Kérjük, először adj hozzá egy járművet.')
    return
  }
  if (!amount.value || !date.value) {
    alert('Kérjük, töltsd ki a kötelező mezőket.')
    return
  }

  isLoading.value = true
  try {
    const expenseData = {
      asset_id: selectedAssetId.value,
      cost_type: category.value, // fuel, service, tax, insurance
      amount_local: parseFloat(amount.value),
      currency_local: 'HUF', // default, could be dynamic
      date: new Date(date.value).toISOString(),
      description: description.value,
      mileage_at_cost: mileage.value ? parseInt(mileage.value) : null,
      data: {}
    }
    await expenseStore.createExpense(expenseData)
    
    // Success
    alert('Költség sikeresen mentve!')
    
    // Reset form
    amount.value = ''
    category.value = 'fuel'
    date.value = new Date().toISOString().split('T')[0]
    description.value = ''
    mileage.value = ''
    
    // Close modal
    emit('close')
  } catch (error) {
    console.error('Error saving expense:', error)
    if (error.message === 'DRAFT_LIMIT_REACHED') {
      // Show custom modal for draft limit
      showDraftLimitModal.value = true
    } else {
      alert(`Hiba történt a mentés során: ${expenseStore.error || error.message}`)
    }
  } finally {
    isLoading.value = false
  }
}

const closeModal = () => {
  emit('close')
}

const closeDraftLimitModal = () => {
  showDraftLimitModal.value = false
}

const openEditVehicle = () => {
  // TODO: Implement opening edit vehicle modal
  // For now, just close the draft limit modal and maybe show a message
  alert('Edit vehicle functionality to be implemented')
  closeDraftLimitModal()
}
</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">Költség / Üzemanyag 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">
          <!-- Asset selection (if multiple vehicles) -->
          <div v-if="garageStore.vehicles.length > 0">
            <label class="block text-sm font-medium text-gray-700 mb-2">Jármű</label>
            <select
              v-model="selectedAssetId"
              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"
            >
              <option v-for="vehicle in garageStore.vehicles" :key="vehicle.id" :value="vehicle.id">
                {{ vehicle.name || vehicle.license_plate || vehicle.vin }}
              </option>
            </select>
          </div>
          <div v-else class="text-sm text-amber-600 bg-amber-50 p-3 rounded-lg">
            Nincs még járműved. Először adj hozzá egy járművet a "Jármű Hozzáadása" gombbal.
          </div>

          <!-- Amount -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Összeg (HUF)</label>
            <input
              v-model="amount"
              type="number"
              step="0.01"
              min="0"
              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"
              placeholder="0.00"
            />
          </div>

          <!-- Category -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Kategória</label>
            <select
              v-model="category"
              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"
            >
              <option value="fuel">Üzemanyag</option>
              <option value="service">Szerviz / Karbantartás</option>
              <option value="tax">Adó / Díj</option>
              <option value="insurance">Biztosítás</option>
              <option value="parking">Parkolás</option>
              <option value="toll">Útdíj</option>
              <option value="other">Egyéb</option>
            </select>
          </div>

          <!-- Date -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Dátum</label>
            <input
              v-model="date"
              type="date"
              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"
            />
          </div>

          <!-- Mileage (optional) -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Kilométeróra állása (opcionális)</label>
            <input
              v-model="mileage"
              type="number"
              min="0"
              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"
              placeholder="pl. 123456"
            />
          </div>

          <!-- Description -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">Leírás (opcionális)</label>
            <textarea
              v-model="description"
              rows="3"
              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"
              placeholder="Pl.: Tankolás, olajcsere..."
            ></textarea>
          </div>

          <!-- Buttons -->
          <div class="flex gap-3 pt-4">
            <button
              type="button"
              @click="closeModal"
              class="flex-1 px-4 py-3 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition"
            >
              Mégse
            </button>
            <button
              type="submit"
              :disabled="isLoading || !selectedAssetId"
              class="flex-1 px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <span v-if="isLoading">Mentés...</span>
              <span v-else>Mentés</span>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Draft Limit Modal -->
  <div v-if="showDraftLimitModal" class="fixed inset-0 z-[200] flex items-center justify-center bg-black bg-opacity-70 p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden">
      <div class="p-6">
        <div class="text-center mb-6">
          <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-yellow-100 text-yellow-600 mb-4">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
          </div>
          <h3 class="text-2xl font-bold text-gray-900 mb-2">You have reached the limit for unregistered vehicles! 🔒</h3>
          <p class="text-gray-600 mb-6">
            Please edit this vehicle and provide the VIN (Chassis Number) or exact Catalog ID to unlock full expense tracking.
          </p>
        </div>
        <div class="flex gap-3">
          <button
            @click="closeDraftLimitModal"
            class="flex-1 px-4 py-3 border border-gray-300 text-gray-700 font-medium rounded-lg hover:bg-gray-50 transition"
          >
            Cancel
          </button>
          <button
            @click="openEditVehicle"
            class="flex-1 px-4 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition"
          >
            Edit Vehicle
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

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