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

    <div class="row q-pa-md q-gutter-md">
      <FinancialCard
        title="Pago"
        icon="mdi-check-circle-outline"
        :financial-value="totals.paid"
        :integer="totals.paidCount"
        integer-label="pagamentos"
      />
      <FinancialCard
        title="A Pagar"
        icon="mdi-cash-minus"
        :financial-value="totals.pending"
        :integer="totals.pendingCount"
        integer-label="pendentes"
      />
      <FinancialCard
        title="Vencidas"
        icon="mdi-alert-circle-outline"
        :financial-value="totals.overdue"
        :integer="totals.overdueCount"
        integer-label="em atraso"
      />
    </div>

    <div class="q-px-md">
      <DefaultTable
        v-model:rows="rows"
        no-api-call
        :add-item="canAdd"
        title="Contas a Pagar"
        description="contas"
        :female="true"
        :columns="columns"
        @on-add-item="openCreate"
      >
        <template #body-cell-plan_account="{ row }">
          <q-td class="text-left">
            {{ row.plan_account ? `${row.plan_account.code} — ${row.plan_account.description}` : "—" }}
          </q-td>
        </template>

        <template #body-cell-value="{ row }">
          <q-td class="text-left">{{ formatCurrency(row.value) }}</q-td>
        </template>

        <template #body-cell-status="{ row }">
          <q-td class="text-left">
            <q-btn
              :color="row.status === 'paid' ? 'positive' : 'orange-7'"
              :label="row.status === 'paid' ? 'Pago' : 'Não pago'"
              dense
              no-caps
              unelevated
              :disable="!canEdit || row.status === 'paid'"
              @click.prevent.stop="changeStatus(row)"
            >
              <q-tooltip v-if="canEdit && row.status !== 'paid'">Dar baixa</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </DefaultTable>
    </div>

  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import { useQuasar } from "quasar";
import { getCompanyPayables } from "src/api/company_payable";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import FinancialCard from "src/components/financial/FinancialCard.vue";
import AddCompanyPayableDialog from "src/components/financial/AddCompanyPayableDialog.vue";
import SettleCompanyPayableDialog from "src/components/financial/SettleCompanyPayableDialog.vue";
import { permissionStore } from "src/stores/permission";

const $q = useQuasar();
const rows = ref([]);
const permissions = permissionStore();
const canAdd = permissions.getAccess("franchisor_financial", "add");
const canEdit = permissions.getAccess("franchisor_financial", "edit");

const columns = [
  { name: "history", label: "Descrição", field: "history", align: "left" },
  { name: "plan_account", label: "Plano de Contas", field: "plan_account", align: "left" },
  { name: "value", label: "Valor", field: "value", align: "left" },
  { name: "due_date", label: "Vencimento", field: "due_date", align: "left" },
  { name: "status", label: "Status", field: "status", align: "left" },
];

function formatCurrency(value) {
  return new Intl.NumberFormat("pt-BR", {
    style: "currency",
    currency: "BRL",
  }).format(Number(value ?? 0));
}

const totals = computed(() => {
  const acc = {
    paid: 0,
    paidCount: 0,
    pending: 0,
    pendingCount: 0,
    overdue: 0,
    overdueCount: 0,
  };
  for (const r of rows.value) {
    if (r.status === "paid") {
      acc.paid += Number(r.paid_value ?? 0);
      acc.paidCount++;
    } else if (r.status === "overdue") {
      acc.overdue += Number(r.value ?? 0);
      acc.overdueCount++;
    } else if (r.status === "pending") {
      acc.pending += Number(r.value ?? 0);
      acc.pendingCount++;
    }
  }
  return acc;
});

async function loadData() {
  try {
    rows.value = await getCompanyPayables();
  } catch (e) {
    console.error("Erro ao buscar contas a pagar:", e);
  }
}

function openSettle(row) {
  $q.dialog({
    component: SettleCompanyPayableDialog,
    componentProps: { payable: row },
  }).onOk(loadData);
}

function changeStatus(row) {
  if (row.status !== "paid") openSettle(row);
}

function openCreate() {
  $q.dialog({ component: AddCompanyPayableDialog }).onOk(loadData);
}

onMounted(loadData);
</script>
