<script setup>
import { computed, onMounted, ref } from "vue";
import { api, ensureCsrf } from "../../../services/api.js";
import BaseButton from "../../../components/base/BaseButton.vue";
import BaseColumn from "../../../components/base/BaseColumn.vue";
import BaseDataTable from "../../../components/base/BaseDataTable.vue";
import BaseIndex from "../../../components/base/BaseIndex.vue";
import BaseInputNumber from "../../../components/base/BaseInputNumber.vue";
import BaseInputText from "../../../components/base/BaseInputText.vue";
import BaseModal from "../../../components/base/BaseModal.vue";
import BaseSelect from "../../../components/base/BaseSelect.vue";
import BaseTextarea from "../../../components/base/BaseTextarea.vue";
import BaseToggleSwitch from "../../../components/base/BaseToggleSwitch.vue";
import { fetchInvoiceMeta } from "../../invoices/composables/useInvoices.js";
import { useBaseToast } from "../../../composables/useBaseToast.js";

const toast = useBaseToast();
const rows = ref([]);
const vatOptions = ref([]);
const loading = ref(false);
const dialog = ref(false);
const draft = ref({
  name: "",
  description: "",
  default_unit_price_ex_vat: 0,
  default_vat_rate_id: null,
  is_active: true,
  sort_order: 0,
});
const editingId = ref(null);

const vatDropdown = computed(() =>
  vatOptions.value.map((r) => ({
    label: `${r.label} (${r.rate_percent}%)`,
    value: r.id,
  })),
);

async function load() {
  loading.value = true;
  try {
    await ensureCsrf();
    const meta = await fetchInvoiceMeta();
    vatOptions.value = meta.vat_rates ?? [];
    const { data } = await api.get("/api/items", {
      params: { include_inactive: true },
    });
    rows.value = data.data ?? data;
  } catch (e) {
    toast.error(e?.response?.data?.message ?? "Laden mislukt.");
  } finally {
    loading.value = false;
  }
}

function openCreate() {
  editingId.value = null;
  draft.value = {
    name: "",
    description: "",
    default_unit_price_ex_vat: 0,
    default_vat_rate_id: vatOptions.value[0]?.id ?? null,
    is_active: true,
    sort_order: 0,
  };
  dialog.value = true;
}

function openEdit(row) {
  editingId.value = row.id;
  draft.value = {
    name: row.name,
    description: row.description ?? "",
    default_unit_price_ex_vat: row.default_unit_price_ex_vat,
    default_vat_rate_id: row.default_vat_rate_id,
    is_active: row.is_active,
    sort_order: row.sort_order,
  };
  dialog.value = true;
}

async function save() {
  try {
    await ensureCsrf();
    if (editingId.value) {
      await api.patch(`/api/items/${editingId.value}`, draft.value);
    } else {
      await api.post("/api/items", draft.value);
    }
    dialog.value = false;
    await load();
    toast.success("Opgeslagen");
  } catch (e) {
    toast.error(e?.response?.data?.message ?? "Opslaan mislukt.");
  }
}

async function remove(row) {
  if (!confirm(`Artikel "${row.name}" verwijderen?`)) return;
  try {
    await ensureCsrf();
    await api.delete(`/api/items/${row.id}`);
    await load();
    toast.success("Verwijderd");
  } catch (e) {
    toast.error(e?.response?.data?.message ?? "Niet verwijderd.");
  }
}

onMounted(load);
</script>

<template>
  <BaseIndex flush hide-header>
    <div class="p-4 md:p-6 max-w-5xl mx-auto flex flex-col gap-6">
      <div class="flex flex-wrap items-center justify-between gap-3">
        <h1 class="text-2xl font-semibold m-0">Artikelen</h1>
        <BaseButton variant="primary" icon="plus" label="Toevoegen" @click="openCreate" />
      </div>

      <BaseDataTable :value="rows" :loading="loading" data-key="id" class="text-sm">
        <BaseColumn field="name" header="Naam" />
        <BaseColumn field="default_unit_price_ex_vat" header="Standaardprijs ex btw" />
        <BaseColumn header="Actief">
          <template #body="{ data }">
            {{ data.is_active ? "Ja" : "Nee" }}
          </template>
        </BaseColumn>
        <BaseColumn header="">
          <template #body="{ data }">
            <div class="flex flex-wrap gap-2 justify-end">
              <BaseButton
                variant="secondary"
                label="Bewerken"
                size="small"
                text
                @click="openEdit(data)"
              />
              <BaseButton
                variant="danger"
                label="Verwijderen"
                size="small"
                text
                @click="remove(data)"
              />
            </div>
          </template>
        </BaseColumn>
      </BaseDataTable>
    </div>

    <BaseModal v-model:visible="dialog" title="Artikel" width="32rem">
      <div class="flex flex-col gap-4">
        <BaseInputText v-model="draft.name" label="Naam" required />
        <BaseTextarea v-model="draft.description" label="Omschrijving" :rows="2" />
        <BaseInputNumber
          v-model="draft.default_unit_price_ex_vat"
          label="Standaardprijs ex btw"
          mode="decimal"
          :min="0"
          :min-fraction-digits="2"
          :use-grouping="false"
        />
        <BaseSelect
          v-model="draft.default_vat_rate_id"
          label="Standaard btw"
          :options="vatDropdown"
          option-label="label"
          option-value="value"
          placeholder="—"
          show-clear
        />
        <BaseToggleSwitch v-model="draft.is_active" label="Actief" />
        <BaseInputNumber v-model="draft.sort_order" label="Sorteer" :min="0" />
        <BaseButton variant="primary" label="Opslaan" class="mt-2" @click="save" />
      </div>
    </BaseModal>
  </BaseIndex>
</template>
