<template>
  <div>
    <DefaultHeaderPage title="Financeiro" :show-filter-icon="false" />
    <div class="row justify-end q-px-md q-mb-xs">
      <q-btn
        flat
        round
        :icon="showValues ? 'mdi-eye-outline' : 'mdi-eye-off-outline'"
        color="primary"
        @click="showValues = !showValues"
      >
        <q-tooltip anchor="center left" self="center right" :offset="[8, 0]">
          {{ showValues ? 'Ocultar valores' : 'Exibir valores' }}
        </q-tooltip>
      </q-btn>
    </div>

    <div class="row q-pa-md q-gutter-md">
      <FinancialCard
        title="Fundo de Marketing"
        icon="mdi-cash-multiple"
        :financial-value="overview.marketing_fund.value"
        :percentage="overview.marketing_fund.percentage"
        :description="trend(overview.marketing_fund.percentage)"
        :hide-values="!showValues"
      />
      <FinancialCard
        title="Receita de Mensalidade"
        icon="mdi-cash-multiple"
        :financial-value="overview.monthly_revenue.value"
        :percentage="overview.monthly_revenue.percentage"
        :description="trend(overview.monthly_revenue.percentage)"
        :hide-values="!showValues"
      />
      <FinancialCard
        title="TBR Total"
        icon="mdi-cash-multiple"
        :financial-value="overview.tbr_total.value"
        :percentage="overview.tbr_total.percentage"
        :description="trend(overview.tbr_total.percentage)"
        :hide-values="!showValues"
      />
      <TreasuryCard />
    </div>

    <div class="row q-px-md q-gutter-md">
      <FinancialCard
        title="Contas a Pagar"
        icon="mdi-cash-minus"
        :financial-value="overview.accounts_payable.value"
        :integer="overview.accounts_payable.count"
        integer-label="pagamentos pendentes"
        :hide-values="!showValues"
      />
      <FinancialCard
        title="Contas a Receber"
        icon="mdi-cash-plus"
        :financial-value="overview.accounts_receivable.value"
        :integer="overview.accounts_receivable.count"
        integer-label="pagamentos pendentes"
        :hide-values="!showValues"
      />
      <FinancialCard
        title="Saldo Bancário Total"
        icon="mdi-bank-outline"
        :financial-value="overview.bank_balance_total"
        :hide-values="!showValues"
      />
      <FinancialCard
        title="Valor Total do Estoque"
        icon="mdi-package-variant-closed"
        :financial-value="overview.stock_value"
        :hide-values="!showValues"
      />
    </div>

    <div class="row q-px-md q-gutter-md q-mt-none">
      <LastTransactionsCard :rows="overview.last_transactions" :loading="loading" />
      <FranchisePerformanceCard :rows="overview.franchise_performance" :loading="loading" />
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { Notify } from "quasar";
import DefaultHeaderPage from "src/components/layout/DefaultHeaderPage.vue";
import FinancialCard from "src/components/financial/FinancialCard.vue";
import TreasuryCard from "src/components/financial/TreasuryCard.vue";
import LastTransactionsCard from "src/components/financial/LastTransactionsCard.vue";
import FranchisePerformanceCard from "src/components/financial/FranchisePerformanceCard.vue";
import { getFinancialOverview } from "src/api/financial_dashboard";

const STORAGE_KEY = "financial_show_values";
const showValues = ref(localStorage.getItem(STORAGE_KEY) !== "false");

watch(showValues, (val) => localStorage.setItem(STORAGE_KEY, String(val)));

const loading = ref(false);
const overview = ref(emptyOverview());

function emptyOverview() {
  return {
    marketing_fund: { value: 0, percentage: 0 },
    monthly_revenue: { value: 0, percentage: 0 },
    tbr_total: { value: 0, percentage: 0 },
    accounts_payable: { value: 0, count: 0 },
    accounts_receivable: { value: 0, count: 0 },
    bank_balance_total: 0,
    stock_value: 0,
    last_transactions: [],
    franchise_performance: [],
  };
}

const trend = (percentage) => {
  if (percentage > 0) return "Em alta";
  if (percentage < 0) return "Em queda";
  return "Estável";
};

const fetchOverview = async () => {
  loading.value = true;
  try {
    overview.value = await getFinancialOverview();
  } catch {
    Notify.create({ message: "Não foi possível carregar os dados financeiros.", type: "negative" });
  } finally {
    loading.value = false;
  }
};

onMounted(fetchOverview);
</script>
