import {
  formatCurrency,
  formatDecimal,
  formatInteger,
  formatPercent,
} from "./utils";

const capitalize = (text) => {
  if (!text) return text;

  return text.charAt(0).toLocaleUpperCase("pt-BR") + text.slice(1);
};

export function buildMetricCards(summary, options = {}) {
  const { isAllPropertiesSelected = false, referenceLabel = "" } = options;

  const manualExpenses =
    summary.expenses_breakdown?.items?.filter(
      (expense) => expense.source === "manual",
    ) ?? [];

  const resolveExpenseType = (expense) => expense.type ?? expense.category;

  const expenseAmount = manualExpenses
    .filter((expense) => resolveExpenseType(expense) === "expense")
    .reduce((total, expense) => total + Number(expense.final_amount ?? 0), 0);

  const maintenanceExpenseAmount = manualExpenses
    .filter((expense) => resolveExpenseType(expense) === "maintenance")
    .reduce((total, expense) => total + Number(expense.final_amount ?? 0), 0);

  const occupancyCaption = isAllPropertiesSelected
    ? "percentual do período"
    : `${formatInteger(summary.occupied_nights_in_month)} de ${formatInteger(summary.days_in_month)} dias`;

  const cards = [
    // INDICADORES

    {
      label: "ocupação",
      value: formatPercent(summary.occupancy_rate, 1),
      caption: occupancyCaption,
    },

    {
      label: "total de reservas",
      value: formatInteger(summary.reservations_count),
      caption: "no período",
    },

    {
      label: "dias por reserva",
      value: formatDecimal(summary.average_nights_per_reservation),
      caption: "média de permanência",
    },

    {
      label: "diária média",
      value: formatCurrency(summary.average_price_per_night),
      caption: "Bruto ÷ diárias",
    },

    {
      label: "limpezas",
      value: formatInteger(summary.cleanings_count),
      caption: "total no período",
    },

    {
      label: "manutenção",
      value: formatCurrency(maintenanceExpenseAmount),
      caption: "no período",
    },

    {
      label: "ticket médio/reserva",
      value: formatCurrency(summary.average_reservation_ticket),
      caption: isAllPropertiesSelected
        ? "Todos apartamentos"
        : "No imóvel selecionado",
    },

    // FINANCEIRO

    {
      label: "faturamento bruto",
      value: formatCurrency(summary.gross_revenue),
      caption: referenceLabel || "Mês selecionado",
    },

    {
      label: "taxa de plataformas",
      value: formatCurrency(summary.ota_amount),
      caption: "taxas plataformas",
    },

    {
      label: "faturamento líquido",
      value: formatCurrency(summary.net_revenue_amount),
      caption: "Bruto - taxas plataformas",
      nowrapCaption: true,
    },

    {
      label: "total limpeza",
      value: formatCurrency(summary.cleaning_total_amount),
      caption: "taxa de limpeza",
    },

    {
      label: "gestão kizzo",
      value: formatCurrency(summary.management_fee_amount),
      caption: "comissão gestão",
    },

    {
      label: "despesas",
      value: formatCurrency(expenseAmount),
      caption: "no período",
    },

    {
      label: "repasse",
      value: formatCurrency(summary.payout_amount),
      caption: isAllPropertiesSelected
        ? "Todos apartamentos"
        : "No imóvel selecionado",
    },
  ];

  return cards.map((card) => ({
    ...card,
    label: capitalize(card.label),
    caption: capitalize(card.caption),
  }));
}
