<template>
  <div class="layout-px-spacing">
    <div class="row layout-top-spacing">
      <div class="col-lg-9 mx-auto layout-spacing">
        <div class="panel p-4">
          <div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-2">
            <div>
              <h3 class="mb-1">Balance por periodo</h3>
              <p class="text-muted mb-0">Cruza gastos por materiales con ingresos por ventas de ganado en el rango de fechas.</p>
            </div>
            <div class="d-flex gap-2">
              <router-link to="/ganaderia/rentabilidad" class="btn btn-outline-secondary btn-sm">
                Rentabilidad por animal
              </router-link>
              <router-link to="/ganaderia/rendimiento-peso" class="btn btn-outline-secondary btn-sm">
                Rendimiento GDP
              </router-link>
            </div>
          </div>

          <form class="row g-2 mb-4" @submit.prevent="generate">
            <div class="col-md-4">
              <label class="form-label">Desde</label>
              <input v-model="from" type="date" class="form-control" required />
            </div>
            <div class="col-md-4">
              <label class="form-label">Hasta</label>
              <input v-model="to" type="date" class="form-control" required />
            </div>
            <div class="col-md-4 d-flex align-items-end">
              <button class="btn btn-primary w-100" :disabled="loading">
                {{ loading ? 'Calculando...' : 'Generar reporte' }}
              </button>
            </div>
          </form>

          <div v-if="report" class="card border-success">
            <div class="card-body">
              <div class="d-flex flex-wrap justify-content-between align-items-start gap-2 mb-3">
                <h5 class="mb-0">Del {{ report.from }} al {{ report.to }}</h5>
                <div class="d-flex gap-2">
                  <button type="button" class="btn btn-outline-secondary btn-sm" @click="exportCsv">
                    Exportar CSV
                  </button>
                  <button type="button" class="btn btn-outline-primary btn-sm" @click="exportPdf">
                    Exportar PDF
                  </button>
                </div>
              </div>

              <ul class="list-group list-group-flush mb-3">
                <li class="list-group-item d-flex justify-content-between">
                  <span>Total gastos (materiales)</span>
                  <strong>{{ money(report.total_expenses) }}</strong>
                </li>
                <li class="list-group-item d-flex justify-content-between">
                  <span>Total ingresos (ventas)</span>
                  <strong>{{ money(report.total_income) }}</strong>
                </li>
                <li
                  class="list-group-item d-flex justify-content-between fs-5"
                  :class="report.net_profit >= 0 ? 'text-success' : 'text-danger'"
                >
                  <span>Utilidad neta</span>
                  <strong>{{ money(report.net_profit) }}</strong>
                </li>
                <li class="list-group-item">Ventas registradas: {{ report.sales_count }}</li>
                <li class="list-group-item">
                  Bajas en periodo: {{ report.deactivations_count ?? '—' }}
                  · Muertes: {{ report.mortality_count }}
                  <span v-if="report.mortality_rate_pct != null">
                    ({{ report.mortality_rate_pct }}% mortalidad)
                  </span>
                </li>
              </ul>

              <h6 v-if="report.expenses_by_category_detail?.length">Gastos por categoría</h6>
              <table v-if="report.expenses_by_category_detail?.length" class="table table-sm">
                <thead>
                  <tr><th>Categoría</th><th class="text-end">Monto</th></tr>
                </thead>
                <tbody>
                  <tr v-for="row in report.expenses_by_category_detail" :key="row.key">
                    <td>{{ row.label }}</td>
                    <td class="text-end">{{ money(row.amount) }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import RanchRepository from '@/repositories/RanchRepository';
import Swal from 'sweetalert2';

const from = ref('');
const to = ref('');
const report = ref(null);
const loading = ref(false);

function money(n) {
  return new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n || 0);
}

function defaultDates() {
  const now = new Date();
  const start = new Date(now.getFullYear(), now.getMonth(), 1);
  from.value = start.toISOString().slice(0, 10);
  to.value = now.toISOString().slice(0, 10);
}

async function generate() {
  loading.value = true;
  try {
    report.value = await RanchRepository.periodBalance(from.value, to.value);
  } catch {
    Swal.fire({ icon: 'error', title: 'No se pudo generar el reporte' });
  } finally {
    loading.value = false;
  }
}

function triggerBlobDownload(blob, filename) {
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', filename);
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(url);
}

async function exportCsv() {
  try {
    const blob = await RanchRepository.downloadPeriodBalanceCsv(from.value, to.value);
    triggerBlobDownload(blob, `balance-${from.value}_${to.value}.csv`);
  } catch {
    Swal.fire({ icon: 'error', title: 'Error al exportar CSV' });
  }
}

async function exportPdf() {
  try {
    const blob = await RanchRepository.downloadPeriodBalancePdf(from.value, to.value);
    triggerBlobDownload(blob, `balance-${from.value}_${to.value}.pdf`);
  } catch {
    Swal.fire({ icon: 'error', title: 'Error al exportar PDF' });
  }
}

onMounted(defaultDates);
</script>
