<template>
  <div>
    <DefaultHeaderPage title="Plano de Contas" :show-filter-icon="false" />

    <div class="q-px-md">
      <DefaultTable
        v-model:rows="rows"
        no-api-call
        add-item
        add-item-label="Nova Conta"
        dense-add
        :loading="loading"
        title="Plano de Contas"
        description="contas"
        :female="true"
        :columns="columns"
        @on-add-item="handleAddItem"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useQuasar } from "quasar";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import AddFinancialPlanAccountDialog from "src/components/financial/AddFinancialPlanAccountDialog.vue";
import { getFinancialPlanAccounts } from "src/api/financial_plan_account";

const $q = useQuasar();

const accounts = ref([]);
const loading = ref(false);

const rows = computed(() =>
  accounts.value.map((account) => ({
    id: account.id,
    code: account.code,
    name: account.description,
    type: account.chart_type,
  })),
);

const columns = [
  { name: "code", label: "Código", field: "code", align: "left" },
  { name: "name", label: "Nome da Conta", field: "name", align: "left" },
  { name: "type", label: "Tipo", field: "type", align: "left" },
];

const fetchAccounts = async () => {
  loading.value = true;
  try {
    accounts.value = await getFinancialPlanAccounts();
  } catch {
    $q.notify({ type: "negative", message: "Erro ao carregar o plano de contas." });
  } finally {
    loading.value = false;
  }
};

const handleAddItem = () => {
  $q.dialog({ component: AddFinancialPlanAccountDialog }).onOk(() => {
    $q.notify({ type: "positive", message: "Conta cadastrada com sucesso." });
    fetchAccounts();
  });
};

onMounted(fetchAccounts);
</script>
