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

    <div class="row q-pa-md q-gutter-md">
      <FinancialCard
        title="Saldo Tesouraria"
        icon="mdi-bank-outline"
        :financial-value="0"
      />
      <FinancialCard
        title="Contas Recebidas"
        icon="mdi-check-circle-outline"
        :financial-value="receivedTotal"
        :integer="receivedCount"
        integer-label="títulos recebidos"
      />
      <FinancialCard
        title="Contas a Receber"
        icon="mdi-cash-plus"
        :financial-value="pendingTotal"
        :integer="pendingCount"
        integer-label="títulos pendentes"
      />
    </div>

    <div class="q-px-md">
      <DefaultTable
        v-model:rows="rows"
        no-api-call
        :add-item="canAdd"
        :loading="loading"
        title="Contas a Receber"
        description="contas"
        :female="true"
        :columns="columns"
        @on-add-item="openCreate"
      >
        <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>
        <template #body-cell-actions="{ row }">
          <q-td auto-width>
            <q-btn
              v-if="row.invoice_url"
              round
              dense
              flat
              color="teal-7"
              icon="mdi-open-in-new"
              aria-label="Abrir cobrança"
              @click="openInvoice(row)"
            >
              <q-tooltip>Abrir cobrança no Asaas</q-tooltip>
            </q-btn>
            <q-btn
              v-else-if="
                canEdit &&
                row.unit_id &&
                row.status !== 'paid' &&
                row.status !== 'cancelled'
              "
              round
              dense
              outline
              color="deep-purple-5"
              icon="mdi-cash-fast"
              aria-label="Gerar cobrança"
              :loading="chargingId === row.id"
              @click="onCharge(row)"
            >
              <q-tooltip>Gerar cobrança no Asaas</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </DefaultTable>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { Notify, useQuasar } from "quasar";
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 {
  getFranchiseeReceivables,
  chargeFranchiseeReceivable,
} from "src/api/franchisee_account_receive";
import AddAccountReceivableDialog from "src/components/financial/AddAccountReceivableDialog.vue";
import SettleAccountReceivableDialog from "src/components/financial/SettleAccountReceivableDialog.vue";
import { permissionStore } from "src/stores/permission";

const $q = useQuasar();
const permissions = permissionStore();
const canAdd = permissions.getAccess("franchisor_financial", "add");
const canEdit = permissions.getAccess("franchisor_financial", "edit");
const loading = ref(false);
const items = ref([]);
const chargingId = ref(null);

const columns = [
  { name: "unit", label: "Unidade", field: "unit", align: "left" },
  { name: "description", label: "Descrição", field: "description", align: "left" },
  { name: "category", label: "Categoria", field: "category", 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" },
  { name: "actions", label: "Ações", field: "actions", align: "right" },
];

const formatCurrency = (value) =>
  new Intl.NumberFormat("pt-BR", { style: "currency", currency: "BRL" }).format(value ?? 0);

const formatDate = (value) => {
  if (!value) return "—";
  const [y, m, d] = value.split("-");
  return `${d}/${m}/${y}`;
};

const rows = computed(() =>
  items.value.map((i) => ({
    ...i,
    unit: i.unit_id ? (i.unit_name ?? `Unidade ${i.unit_id}`) : "Conta interna",
    description: i.history,
    category: i.plan_account
      ? `${i.plan_account.code} — ${i.plan_account.description}`
      : i.origin === "tbr" ? "TBR" : "—",
    value: formatCurrency(Number(i.value)),
    due_date: formatDate(i.due_date),
  })),
);

const isSettled = (status) => status === "paid";

const receivedTotal = computed(() =>
  items.value
    .filter((i) => isSettled(i.status))
    .reduce((acc, i) => acc + Number(i.paid_value || 0), 0),
);
const receivedCount = computed(() => items.value.filter((i) => isSettled(i.status)).length);

const pendingTotal = computed(() =>
  items.value
    .filter((i) => !isSettled(i.status) && i.status !== "cancelled")
    .reduce((acc, i) => acc + (Number(i.value || 0) - Number(i.paid_value || 0)), 0),
);
const pendingCount = computed(
  () => items.value.filter((i) => !isSettled(i.status) && i.status !== "cancelled").length,
);

const fetchReceivables = async () => {
  loading.value = true;
  try {
    items.value = await getFranchiseeReceivables();
  } catch {
    Notify.create({ message: "Não foi possível carregar as contas a receber.", type: "negative" });
  } finally {
    loading.value = false;
  }
};

const openCreate = () => {
  $q.dialog({ component: AddAccountReceivableDialog }).onOk(fetchReceivables);
};

const changeStatus = (row) => {
  if (row.status === "paid") return;
  $q.dialog({
    component: SettleAccountReceivableDialog,
    componentProps: { receivable: row },
  }).onOk(fetchReceivables);
};

const onCharge = async (row) => {
  chargingId.value = row.id;
  try {
    await chargeFranchiseeReceivable(row.id);
    await fetchReceivables();
  } finally {
    chargingId.value = null;
  }
};

const openInvoice = (row) => window.open(row.invoice_url, "_blank");

onMounted(fetchReceivables);
</script>
