<script setup lang="ts">
definePageMeta({ middleware: 'auth' })

const { clients, search, fetchClients } = useClient()
const q = ref('')
let debounceTimer: ReturnType<typeof setTimeout>

await fetchClients()

const onSearch = () => {
  clearTimeout(debounceTimer)
  debounceTimer = setTimeout(() => search(q.value), 250)
}

const showCreate = ref(false)
const newNumber = ref('')
const newName = ref('')
const creating = ref(false)
const createError = ref('')
const { createClient } = useClient()

const submitCreate = async () => {
  creating.value = true
  createError.value = ''
  try {
    const client = await createClient({ client_number: newNumber.value, name: newName.value })
    showCreate.value = false
    newNumber.value = ''
    newName.value = ''
    await navigateTo(`/clients/${client.id}`)
  } catch (e: any) {
    createError.value = e?.data?.message ?? 'Fehler beim Erstellen.'
  } finally {
    creating.value = false
  }
}
</script>

<template>
  <div class="min-h-screen bg-gray-50">
    <header class="bg-white border-b border-gray-200 px-6 py-3 flex items-center gap-4">
      <h1 class="text-base font-semibold text-gray-800">Mandant CRM</h1>
      <input
        v-model="q"
        @input="onSearch"
        type="search"
        placeholder="Mandant suchen (Name oder Nr.)…"
        class="flex-1 border border-gray-300 px-3 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500 max-w-md"
      />
      <button
        @click="showCreate = true"
        class="bg-blue-600 text-white px-3 py-1.5 text-sm hover:bg-blue-700"
      >
        + Neuer Mandant
      </button>
      <LogoutButton />
    </header>

    <main class="max-w-4xl mx-auto py-4 px-6 space-y-1">
      <p v-if="clients.length === 0" class="text-sm text-gray-500 py-8 text-center">
        Keine Mandanten gefunden.
      </p>
      <ClientCard v-for="client in clients" :key="client.id" :client="client" />
    </main>

    <!-- Create modal -->
    <div v-if="showCreate" class="fixed inset-0 bg-black/30 flex items-center justify-center z-50">
      <div class="bg-white shadow-lg p-6 w-full max-w-sm">
        <h2 class="text-base font-semibold mb-4">Neuer Mandant</h2>
        <form @submit.prevent="submitCreate" class="space-y-3">
          <div>
            <label class="block text-sm font-medium text-gray-700">Mandantennummer</label>
            <input v-model="newNumber" required class="mt-1 block w-full border border-gray-300 px-3 py-2 text-sm" />
          </div>
          <div>
            <label class="block text-sm font-medium text-gray-700">Name</label>
            <input v-model="newName" required class="mt-1 block w-full border border-gray-300 px-3 py-2 text-sm" />
          </div>
          <p v-if="createError" class="text-sm text-red-600">{{ createError }}</p>
          <div class="flex gap-2 justify-end">
            <button type="button" @click="showCreate = false" class="px-3 py-1.5 text-sm border border-gray-300">
              Abbrechen
            </button>
            <button type="submit" :disabled="creating" class="px-3 py-1.5 text-sm bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50">
              Anlegen
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
