<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-center mb-4">
            <div>
              <h3 class="mb-1">Rendimiento de vacas madre</h3>
              <p class="text-muted mb-0">
                Compara crías por peso y GDP; identifica vacas con alta mortalidad en la progenie.
              </p>
            </div>
            <button class="btn btn-outline-primary" :disabled="loading" @click="load">Actualizar</button>
          </div>

          <div v-if="report" class="row g-3 mb-4">
            <div class="col-md-4">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                  <p class="text-muted mb-1">Vacas con crías</p>
                  <h4 class="mb-0">{{ report.mothers_count }}</h4>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                  <p class="text-muted mb-1">Alerta mortalidad progenie</p>
                  <h4 class="mb-0">≥ {{ report.high_mortality_threshold_pct }}%</h4>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                  <p class="text-muted mb-1">Vacas en riesgo</p>
                  <h4 class="mb-0 text-danger">{{ riskCount }}</h4>
                </div>
              </div>
            </div>
          </div>

          <div class="table-responsive" v-if="report?.mothers?.length">
            <table class="table table-hover">
              <thead>
                <tr>
                  <th>Arete madre</th>
                  <th>Raza</th>
                  <th>Crías</th>
                  <th>Activas</th>
                  <th>Muertas</th>
                  <th>Mortalidad %</th>
                  <th>Peso prom. crías (kg)</th>
                  <th>GDP prom.</th>
                  <th>Enf. crías</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in report.mothers" :key="row.mother_id" :class="rowClass(row)">
                  <td>
                    <router-link :to="{ name: 'ranch-animal-detail', params: { id: row.mother_id } }">
                      {{ row.ear_tag }}
                    </router-link>
                  </td>
                  <td>{{ row.breed || '—' }}</td>
                  <td>{{ row.offspring_count }}</td>
                  <td>{{ row.offspring_active }}</td>
                  <td>{{ row.offspring_dead }}</td>
                  <td>
                    <span :class="row.high_mortality_risk ? 'text-danger fw-bold' : ''">
                      {{ row.mortality_rate_pct }}%
                    </span>
                  </td>
                  <td>{{ formatNum(row.avg_offspring_weight_kg) }}</td>
                  <td>{{ formatNum(row.avg_offspring_gdp, 4) }}</td>
                  <td>
                    <span :class="row.health_risk ? 'text-danger fw-bold' : ''">{{ row.offspring_illness_events }}</span>
                  </td>
                  <td>
                    <span v-if="row.top_producer" class="badge bg-success me-1">Mejor peso</span>
                    <span v-if="row.health_risk" class="badge bg-warning text-dark me-1">Salud</span>
                    <span v-if="row.high_mortality_risk" class="badge bg-danger">Mortalidad</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <p v-else-if="!loading" class="text-muted">No hay vacas con crías registradas. Asigne la madre al dar de alta becerros.</p>
        </div>
      </div>
    </div>
  </div>
</template>

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

const loading = ref(false);
const report = ref(null);

const riskCount = computed(() => report.value?.mothers?.filter((m) => m.high_mortality_risk).length ?? 0);

function formatNum(v, digits = 2) {
  if (v === null || v === undefined) return '—';
  return Number(v).toFixed(digits);
}

function rowClass(row) {
  if (row.high_mortality_risk || row.health_risk) return 'table-danger';
  if (row.top_producer) return 'table-success';
  return '';
}

async function load() {
  loading.value = true;
  try {
    report.value = await RanchRepository.motherPerformance();
  } finally {
    loading.value = false;
  }
}

onMounted(load);
</script>
