<template>
  <main class="container">
    <h1>{{ t('nav.objets') }}</h1>
    <p v-if="errorMessage">{{ errorMessage }}</p>

    <section class="card" style="margin-bottom: 16px;">
      <h2>{{ t('filters.name') }}</h2>
      <div style="display: grid; gap: 8px;">
        <input v-model="filterNom" :placeholder="t('placeholders.name')" />
        <select v-model="filterStatut">
          <option value="">{{ t('filters.status') }}</option>
          <option value="en_stock">en_stock</option>
          <option value="pret">pret</option>
          <option value="hors_service">hors_service</option>
          <option value="archive">archive</option>
        </select>
        <label>
          {{ t('filters.limit') }}
          <select v-model.number="limit">
            <option :value="10">10</option>
            <option :value="25">25</option>
            <option :value="50">50</option>
          </select>
        </label>
        <div style="display: flex; gap: 8px;">
          <button class="card" type="button" @click="resetFilters">
            {{ t('filters.reset') }}
          </button>
        </div>
      </div>
    </section>

    <ObjetForm
      v-model="form"
      :saving="saving"
      :message="message"
      :mode="editingId ? 'edit' : 'create'"
      @save="saveObjet"
      @cancel="resetForm"
    />

    <p v-if="pending">{{ t('states.loading') }}</p>
    <p v-else-if="items.length === 0">{{ t('states.empty') }}</p>
    <section v-else class="grid">
      <article v-for="item in items" :key="item.id" class="card">
        <h3>{{ item.nom }}</h3>
        <p v-if="item.description">{{ item.description }}</p>
        <small>{{ t('form.statut') }}: {{ item.statut }}</small>
        <div style="margin-top: 8px; display: flex; gap: 8px;">
          <NuxtLink class="card" :to="`/objets/${item.id}`">{{ t('actions.open') }}</NuxtLink>
          <button class="card" type="button" @click="editObjet(item)">{{ t('actions.edit') }}</button>
          <button class="card" type="button" @click="confirmDelete(item.id)">
            {{ t('actions.delete') }}
          </button>
        </div>
      </article>
    </section>

    <section class="card" style="margin-top: 16px;">
      <p>{{ t('pagination.page') }} {{ page }} / {{ totalPages }}</p>
      <div style="display: flex; gap: 8px;">
        <button class="card" type="button" :disabled="page <= 1" @click="page--">
          {{ t('pagination.prev') }}
        </button>
        <button class="card" type="button" :disabled="page >= totalPages" @click="page++">
          {{ t('pagination.next') }}
        </button>
      </div>
    </section>

    <ConfirmDialog
      :open="confirmOpen"
      :title="t('confirm.deleteObjetTitle')"
      :message="t('confirm.deleteObjetMessage')"
      @confirm="runConfirm"
      @cancel="closeConfirm"
    />
  </main>
</template>

<script setup lang="ts">
type Objet = {
  id: string
  nom: string
  description?: string | null
  quantite: number
  statut: string
}

const { apiBase, getErrorMessage } = useApi()
const { t } = useI18n()

const page = ref(1)
const limit = ref(50)
const filterNom = ref('')
const filterStatut = ref('')

const { data, pending, error, refresh } = await useFetch<{
  items: Objet[]
  meta?: { total: number; page: number; limit: number }
}>(`${apiBase}/objets`, {
  query: {
    page,
    limit,
    nom: filterNom,
    statut: filterStatut
  },
  watch: [page, limit, filterNom, filterStatut]
})

const items = computed(() => data.value?.items ?? [])
const total = computed(() => data.value?.meta?.total ?? items.value.length)
const totalPages = computed(() => Math.max(1, Math.ceil(total.value / limit.value)))
const errorMessage = computed(() =>
  error.value ? getErrorMessage(error.value, t('messages.loadError')) : ""
)

const saving = ref(false)
const message = ref("")
const editingId = ref<string | null>(null)
const confirmOpen = ref(false)
const confirmAction = ref<null | (() => Promise<void>)>(null)
const form = ref({
  nom: "",
  description: "",
  quantite: 0,
  statut: "en_stock"
})

watch([filterNom, filterStatut, limit], () => {
  page.value = 1
})

const resetFilters = () => {
  filterNom.value = ''
  filterStatut.value = ''
  limit.value = 50
}

const resetForm = () => {
  editingId.value = null
  form.value = { nom: "", description: "", quantite: 0, statut: "en_stock" }
}

const editObjet = (item: Objet) => {
  editingId.value = item.id
  form.value = {
    nom: item.nom,
    description: item.description || "",
    quantite: item.quantite,
    statut: item.statut
  }
}

const saveObjet = async () => {
  message.value = ""
  if (!form.value.nom) {
    message.value = t('messages.requiredName')
    return
  }
  saving.value = true
  try {
    if (editingId.value) {
      await $fetch(`${apiBase}/objets/${editingId.value}`, {
        method: "PUT",
        body: form.value
      })
      message.value = t('messages.updated')
    } else {
      await $fetch(`${apiBase}/objets`, {
        method: "POST",
        body: form.value
      })
      message.value = t('messages.created')
    }
    resetForm()
    await refresh()
  } catch (err) {
    message.value = getErrorMessage(err, t('messages.saveError'))
  } finally {
    saving.value = false
  }
}

const deleteObjet = async (id: string) => {
  message.value = ""
  try {
    await $fetch(`${apiBase}/objets/${id}`, { method: "DELETE" })
    message.value = t('messages.deleted')
    await refresh()
  } catch (err) {
    message.value = getErrorMessage(err, t('messages.deleteError'))
  }
}

const confirmDelete = (id: string) => {
  confirmAction.value = () => deleteObjet(id)
  confirmOpen.value = true
}

const closeConfirm = () => {
  confirmOpen.value = false
  confirmAction.value = null
}

const runConfirm = async () => {
  if (confirmAction.value) {
    await confirmAction.value()
  }
  closeConfirm()
}
</script>
