<template>
  <div class="layout-px-spacing">
    <div class="row layout-top-spacing">
      <div class="col-12 layout-spacing">
        <div class="panel p-4">
          <div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-3">
            <div>
              <h3 class="mb-1">Rentabilidad por animal</h3>
              <p class="text-muted mb-0">
                Ingreso − alimento − salud. Incluye costo y utilidad por kg de peso ganado.
              </p>
            </div>
            <div v-if="report" class="d-flex gap-2">
              <button type="button" class="btn btn-outline-primary btn-sm" :disabled="exporting" @click="exportCsv">
                CSV
              </button>
              <button type="button" class="btn btn-outline-primary btn-sm" :disabled="exporting" @click="exportPdf">
                PDF
              </button>
            </div>
          </div>

          <form class="row g-2 mb-4" @submit.prevent="load">
            <div class="col-md-3">
              <label class="form-label">Desde (venta)</label>
              <input v-model="from" type="date" class="form-control" />
            </div>
            <div class="col-md-3">
              <label class="form-label">Hasta</label>
              <input v-model="to" type="date" class="form-control" />
            </div>
            <div class="col-md-3">
              <label class="form-label">Estatus</label>
              <select v-model="status" class="form-select">
                <option value="sold">Vendidos</option>
                <option value="active">Activos (solo costos)</option>
                <option value="all">Todos</option>
              </select>
            </div>
            <div class="col-md-3 d-flex align-items-end">
              <button class="btn btn-primary w-100" :disabled="loading">Generar</button>
            </div>
          </form>

          <div v-if="report" class="row g-3 mb-4">
            <div class="col-md-4 col-lg" v-for="t in totalCards" :key="t.label">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">{{ t.label }}</p>
                  <h5 class="mb-0" :class="t.class">{{ t.value }}</h5>
                </div>
              </div>
            </div>
          </div>

          <h5 v-if="report">Por animal ({{ report.animals_count }})</h5>
          <div class="table-responsive mb-4" v-if="report?.animals?.length">
            <table class="table table-hover table-sm">
              <thead>
                <tr>
                  <th>Arete</th>
                  <th>Venta</th>
                  <th class="text-end">Kg ganados</th>
                  <th class="text-end">Ingreso</th>
                  <th class="text-end">Costos</th>
                  <th class="text-end">Utilidad</th>
                  <th class="text-end">$/kg ganado</th>
                  <th class="text-end">Util./kg</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="a in report.animals" :key="a.cattle_id" :class="rowClass(a)">
                  <td>
                    <router-link :to="{ name: 'ranch-animal-detail', params: { id: a.cattle_id } }">
                      {{ a.ear_tag }}
                    </router-link>
                  </td>
                  <td>{{ a.sale_date || '—' }}</td>
                  <td class="text-end">{{ a.weight_gain_kg ?? '—' }}</td>
                  <td class="text-end">{{ money(a.income) }}</td>
                  <td class="text-end" :title="'Alimento ' + money(a.feed_cost) + ' + Salud ' + money(a.health_cost)">
                    {{ money(a.total_cost) }}
                  </td>
                  <td class="text-end fw-semibold">{{ money(a.net_profit) }}</td>
                  <td class="text-end">{{ a.cost_per_kg_gained != null ? money(a.cost_per_kg_gained) : '—' }}</td>
                  <td class="text-end" :class="profitKgClass(a)">
                    {{ a.profit_per_kg_gained != null ? money(a.profit_per_kg_gained) : '—' }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <h5 v-if="report?.fattening_lots?.length">Por lote de engorda</h5>
          <table v-if="report?.fattening_lots?.length" class="table table-sm">
            <thead>
              <tr>
                <th>Lote</th>
                <th>Animales</th>
                <th class="text-end">Ingresos</th>
                <th class="text-end">Alimento (lote)</th>
                <th class="text-end">Salud</th>
                <th class="text-end">Utilidad</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="lot in report.fattening_lots" :key="lot.lot_id">
                <td>{{ lot.lot_name }}</td>
                <td>{{ lot.animals_count }}</td>
                <td class="text-end">{{ money(lot.income) }}</td>
                <td class="text-end">{{ money(lot.feed_cost) }}</td>
                <td class="text-end">{{ money(lot.health_cost) }}</td>
                <td class="text-end" :class="lot.net_profit >= 0 ? 'text-success' : 'text-danger'">{{ money(lot.net_profit) }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

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

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

const totalCards = computed(() => {
  if (!report.value?.totals) return [];
  const t = report.value.totals;
  return [
    { label: 'Ingresos', value: money(t.income) },
    { label: 'Utilidad neta', value: money(t.net_profit), class: t.net_profit >= 0 ? 'text-success' : 'text-danger' },
    { label: 'Costo / kg ganado', value: t.cost_per_kg_gained != null ? money(t.cost_per_kg_gained) : '—' },
    { label: 'Utilidad / kg ganado', value: t.profit_per_kg_gained != null ? money(t.profit_per_kg_gained) : '—', class: (t.profit_per_kg_gained ?? 0) >= 0 ? 'text-success' : 'text-danger' },
    { label: 'Kg ganados (total)', value: t.weight_gain_kg ?? 0 },
  ];
});

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

function rowClass(a) {
  if (a.status !== 'sold') return '';
  return a.profitable ? 'table-success' : 'table-danger';
}

function profitKgClass(a) {
  if (a.profit_per_kg_gained == null) return '';
  return a.profit_per_kg_gained >= 0 ? 'text-success' : 'text-danger';
}

async function load() {
  loading.value = true;
  try {
    report.value = await RanchRepository.animalProfitability({
      from: from.value || undefined,
      to: to.value || undefined,
      status: status.value,
    });
  } finally {
    loading.value = false;
  }
}

function exportParams() {
  return {
    from: from.value || undefined,
    to: to.value || undefined,
    status: status.value,
  };
}

function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}

async function exportCsv() {
  exporting.value = true;
  try {
    const blob = await RanchRepository.downloadAnimalProfitabilityCsv(exportParams());
    downloadBlob(blob, `rentabilidad-${from.value || 'completo'}.csv`);
  } finally {
    exporting.value = false;
  }
}

async function exportPdf() {
  exporting.value = true;
  try {
    const blob = await RanchRepository.downloadAnimalProfitabilityPdf(exportParams());
    downloadBlob(blob, `rentabilidad-${from.value || 'completo'}.pdf`);
  } finally {
    exporting.value = false;
  }
}

onMounted(load);
</script>
