<template>
  <Panel :header="$t('categories')">
    <template #icons>
      <Button
        icon="pi pi-plus"
        :label="$t('add')"
        severity="success"
        @click="create()"
      />
    </template>
    <DataTable :value="categories">
      <Column field="name" :header="$t('name')" />
      <Column field="id" :header="$t('id')" />
      <Column
        :field="({ createdAt }) => jDate(createdAt)"
        :header="$t('createdAt')"
      />

      <Column headerClass="w-32" :header="$t('options')">
        <template #body="{ data }">
          <div class="flex justify-start">
            <Button
              icon="pi pi-trash"
              rounded
              text
              severity="danger"
              @click="remove(data)"
            />
          </div>
        </template>
      </Column>
    </DataTable>
  </Panel>
</template>

<script setup>
import { jDate } from "@/utils/jDate";
import {
  inject,
  defineAsyncComponent,
  watchEffect,
  ref,
  watch
} from "vue";
import { useCategoriesStore } from "@/stores/categoreis";
const categories = ref();
const CategoryForm = defineAsyncComponent(() =>
  import("../components/CategoryForm.vue")
);
const { dialog, confirm, toast, t } = inject("service");
const store = useCategoriesStore();

const create = async() => {
  dialog.open(CategoryForm, {
    props: { modal: true, closable: false, header: t("createNewCategory") },
    data: { categories: "store.items" },
  });
  await store.index(1,100)
};
const remove = (data) => {
  confirm.require({
    message: t("Are you sure you want to proceed?"),
    header: t("Danger Zone"),
    icon: "pi pi-info-circle",
    acceptClass: "p-button-danger p-button-sm",
    rejectClass: "p-button-secondary p-button-outlined p-button-sm",
    rejectLabel: t("cancel"),
    acceptLabel: t("beOmitted"),
    defaultFocus: "reject",
    accept: async () => {
      const deleted = await store.remove(data.id);
      if (deleted.status === 200 || deleted.status === 201) {
        toast.add({
          severity: "success",
          summary: t("successful"),
          detail: t("دسته بندی حذف شد"),
          life: 3000,
        });
       
      } else
        toast.add({
          severity: "error",
          summary: t("error"),
          detail: t("خطا، مجدد تلاش کنید"),
          life: 3000,
        });

    },
    
  });
};

watchEffect(async () => {
  categories.value = await store.index(1, 100);
});
watch(categories ,async () => {
  categories.value = await store.index(1, 100);
});
</script>

