<script setup>
import { 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 BaseToggleSwitch from "../../../components/base/BaseToggleSwitch.vue";
import { useBaseToast } from "../../../composables/useBaseToast.js";

const toast = useBaseToast();
const rows = ref([]);
const loading = ref(false);
const dialog = ref(false);
const draft = ref({
  label: "",
  rate_percent: 21,
  is_active: true,
  sort_order: 0,
});
const editingId = ref(null);

async function load() {
  loading.value = true;
  try {
    await ensureCsrf();
    const { data } = await api.get("/api/invoices/vat-rates");
    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 = { label: "", rate_percent: 21, is_active: true, sort_order: 0 };
  dialog.value = true;
}

function openEdit(row) {
  editingId.value = row.id;
  draft.value = {
    label: row.label,
    rate_percent: row.rate_percent,
    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/invoices/vat-rates/${editingId.value}`, draft.value);
    } else {
      await api.post("/api/invoices/vat-rates", 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(`BTW-tarief "${row.label}" verwijderen?`)) return;
  try {
    await ensureCsrf();
    await api.delete(`/api/invoices/vat-rates/${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-4xl 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">BTW-tarieven</h1>
        <BaseButton variant="primary" icon="plus" label="Toevoegen" @click="openCreate" />
      </div>

      <BaseDataTable :value="rows" :loading="loading" data-key="id" class="text-sm">
        <BaseColumn field="label" header="Label" />
        <BaseColumn field="rate_percent" header="%" />
        <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="BTW-tarief" width="28rem">
      <div class="flex flex-col gap-4">
        <BaseInputText v-model="draft.label" label="Label" required />
        <BaseInputNumber
          v-model="draft.rate_percent"
          label="Percentage"
          :min="0"
          :max="100"
          :step="0.01"
          :use-grouping="false"
        />
        <BaseToggleSwitch v-model="draft.is_active" label="Actief" />
        <BaseInputNumber
          v-model="draft.sort_order"
          label="Sorteer"
          :min="0"
          :step="1"
        />
        <BaseButton variant="primary" label="Opslaan" class="mt-2" @click="save" />
      </div>
    </BaseModal>
  </BaseIndex>
</template>
