<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-origin="{ row }">
          <q-td class="text-left">
            <q-chip
              :color="row.origin === 'tbr' ? 'deep-purple-5' : 'blue-grey-5'"
              text-color="white"
              dense
              square
              :label="row.origin === 'tbr' ? 'TBR' : 'Manual'"
            />
          </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' : 'secondary'"
              :label="row.status === 'paid' ? 'Pago' : 'Não pago'"
              dense
              no-caps
              unelevated
              :disable="!canEdit"
              :loading="reopeningId === row.id"
              @click.stop="changeStatus(row)"
            >
              <q-tooltip v-if="canEdit">Clique para alterar o status</q-tooltip>
            </q-btn>
          </q-td>
        </template>
      </DefaultTable>
    </div>

    <!-- Diálogo de baixa manual -->
    <q-dialog v-model="settleDialog">
      <q-card style="min-width: 360px; max-width: 460px">
        <DefaultDialogHeader title="Dar baixa" @close="settleDialog = false" />

        <q-card-section class="q-gutter-sm">
          <div class="text-body2 text-grey-8">{{ selected?.history }}</div>

          <DefaultInputDatePicker
            v-model="settleForm.payment_date"
            v-model:untreated-date="settleForm.payment_date_iso"
            label="Data do pagamento"
          />

          <div class="row q-col-gutter-sm">
            <DefaultCurrencyInput
              v-model="settleForm.discount"
              label="Desconto"
              class="col-6"
              outlined
            />
            <DefaultCurrencyInput
              v-model="settleForm.fine"
              label="Multa/Juros"
              class="col-6"
              outlined
            />
          </div>

          <div class="text-caption text-grey-7">
            Valor da conta: {{ formatCurrency(selected?.value) }} ·
            <span class="text-weight-medium">
              Pago: {{ formatCurrency(settleNetValue) }}
            </span>
          </div>
        </q-card-section>

        <q-card-actions align="right" class="q-pa-md">
          <q-btn flat label="Cancelar" color="grey-7" @click="settleDialog = false" />
          <q-btn
            color="primary-2"
            label="Confirmar baixa"
            :loading="settling"
            @click="onSettle"
          />
        </q-card-actions>
      </q-card>
    </q-dialog>

    <!-- Diálogo de nova conta manual -->
    <q-dialog v-model="createDialog">
      <q-card style="min-width: 360px; max-width: 460px">
        <DefaultDialogHeader title="Nova conta a pagar" @close="createDialog = false" />

        <q-form ref="createFormRef">
          <q-card-section class="q-gutter-sm">
            <DefaultInput
              v-model="createForm.history"
              label="Descrição"
              outlined
              :rules="[(v) => !!v || 'Informe a descrição']"
            />
            <div class="row q-col-gutter-sm">
              <DefaultCurrencyInput
                v-model="createForm.value"
                label="Valor"
                class="col-6"
                outlined
                :rules="[() => Number(createForm.value) > 0 || 'Informe o valor']"
              />
              <DefaultInputDatePicker
                v-model="createForm.due_date"
                v-model:untreated-date="createForm.due_date_iso"
                label="Vencimento"
                class="col-6"
              />
            </div>
            <DefaultInput
              v-model="createForm.obs"
              label="Observação (opcional)"
              type="textarea"
              outlined
            />
          </q-card-section>

          <q-card-actions align="right" class="q-pa-md">
            <q-btn flat label="Cancelar" color="grey-7" @click="createDialog = false" />
            <q-btn
              color="primary"
              label="Salvar"
              :loading="creating"
              @click="onCreate"
            />
          </q-card-actions>
        </q-form>
      </q-card>
    </q-dialog>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from "vue";
import {
  getPayablesMe,
  createPayableMe,
  settlePayableMe,
  reopenPayableMe,
} from "src/api/unit_payable";

import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import DefaultTable from "src/components/defaults/DefaultTable.vue";
import DefaultInput from "src/components/defaults/DefaultInput.vue";
import DefaultCurrencyInput from "src/components/defaults/DefaultCurrencyInput.vue";
import DefaultInputDatePicker from "src/components/defaults/DefaultInputDatePicker.vue";
import DefaultDialogHeader from "src/components/defaults/DefaultDialogHeader.vue";
import FinancialCard from "src/components/financial/FinancialCard.vue";
import { permissionStore } from "src/stores/permission";

const permissions = permissionStore();
const canAdd = computed(() =>
  permissions.getAccess("franchisee_financial", "add"),
);
const canEdit = computed(() =>
  permissions.getAccess("franchisee_financial", "edit"),
);

const rows = ref([]);

const settleDialog = ref(false);
const selected = ref(null);
const settling = ref(false);
const reopeningId = ref(null);
const settleForm = ref({ payment_date: null, payment_date_iso: null, discount: 0, fine: 0 });

const createDialog = ref(false);
const createFormRef = ref(null);
const creating = ref(false);
const createForm = ref({ history: "", value: 0, due_date: null, due_date_iso: null, obs: "" });

const columns = [
  { name: "origin", label: "Origem", field: "origin", align: "left" },
  { name: "history", label: "Descrição", field: "history", 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 settleNetValue = computed(() => {
  const base = Number(selected.value?.value ?? 0);
  return base - Number(settleForm.value.discount ?? 0) + Number(settleForm.value.fine ?? 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 getPayablesMe();
  } catch (e) {
    console.error("Erro ao buscar contas a pagar:", e);
  }
}

function openSettle(row) {
  const today = new Date();
  selected.value = row;
  settleForm.value = {
    payment_date: today.toLocaleDateString("pt-BR"),
    payment_date_iso: today.toISOString().slice(0, 10),
    discount: Number(row.discount ?? 0),
    fine: Number(row.fine ?? 0),
  };
  settleDialog.value = true;
}

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

async function onSettle() {
  if (!selected.value) return;
  settling.value = true;
  try {
    await settlePayableMe(selected.value.id, {
      payment_date: settleForm.value.payment_date_iso,
      discount: settleForm.value.discount,
      fine: settleForm.value.fine,
    });
    settleDialog.value = false;
    await loadData();
  } catch (e) {
    console.error(e);
  } finally {
    settling.value = false;
  }
}

async function onReopen(row) {
  reopeningId.value = row.id;
  try {
    await reopenPayableMe(row.id);
    await loadData();
  } catch (e) {
    console.error(e);
  } finally {
    reopeningId.value = null;
  }
}

function openCreate() {
  const today = new Date();
  createForm.value = {
    history: "",
    value: 0,
    due_date: today.toLocaleDateString("pt-BR"),
    due_date_iso: today.toISOString().slice(0, 10),
    obs: "",
  };
  createDialog.value = true;
}

async function onCreate() {
  const valid = await createFormRef.value?.validate();
  if (!valid) return;
  creating.value = true;
  try {
    await createPayableMe({
      history: createForm.value.history,
      value: createForm.value.value,
      due_date: createForm.value.due_date_iso,
      obs: createForm.value.obs || null,
    });
    createDialog.value = false;
    await loadData();
  } catch (e) {
    console.error(e);
  } finally {
    creating.value = false;
  }
}

onMounted(loadData);
</script>
