<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">Inventario por ubicación</h3>
              <p class="text-muted mb-0">
                Cabezas agrupadas por corral, pasto o lote de engorda. Incluye último peso y GDP.
              </p>
            </div>
            <button v-if="report" type="button" class="btn btn-outline-primary btn-sm" :disabled="loading" @click="exportCsv">
              Exportar CSV
            </button>
          </div>

          <form class="row g-2 mb-4" @submit.prevent="load">
            <div class="col-md-2">
              <label class="form-label">Estatus</label>
              <select v-model="status" class="form-select">
                <option value="active">Activos</option>
                <option value="all">Todos</option>
                <option value="sold">Vendidos</option>
                <option value="dead">Muertos</option>
                <option value="consumed">Consumidos</option>
              </select>
            </div>
            <div class="col-md-2">
              <label class="form-label">Tipo ubicación</label>
              <select v-model="locationType" class="form-select">
                <option value="">Todas</option>
                <option value="fattening">Engorda</option>
                <option value="pasture">Corral/pasto</option>
                <option value="unassigned">Sin ubicación</option>
              </select>
            </div>
            <div class="col-md-2">
              <label class="form-label">Potrero</label>
              <select v-model="pastureId" class="form-select">
                <option value="">Todos</option>
                <option v-for="p in pastures" :key="p.id" :value="p.id">{{ p.name }}</option>
              </select>
            </div>
            <div class="col-md-2">
              <label class="form-label">Raza</label>
              <input v-model="breed" class="form-control" placeholder="Opcional" />
            </div>
            <div class="col-md-2">
              <label class="form-label">Género</label>
              <select v-model="gender" class="form-select">
                <option value="">Todos</option>
                <option value="male">Macho</option>
                <option value="female">Hembra</option>
              </select>
            </div>
            <div class="col-md-2 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-3">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">Total cabezas</p>
                  <h4 class="mb-0">{{ report.totals.head_count }}</h4>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">En engorda</p>
                  <h4 class="mb-0">{{ report.totals.in_fattening }}</h4>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">En corral/pasto</p>
                  <h4 class="mb-0">{{ report.totals.in_pasture }}</h4>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">Sin ubicación</p>
                  <h4 class="mb-0 text-warning">{{ report.totals.unassigned }}</h4>
                </div>
              </div>
            </div>
          </div>

          <div v-if="report?.by_location?.length" class="row mb-4">
            <div class="col-lg-5">
              <h6>Por ubicación</h6>
              <table class="table table-sm">
                <thead>
                  <tr>
                    <th>Ubicación</th>
                    <th class="text-end">Cabezas</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="loc in report.by_location" :key="loc.location_key">
                    <td>
                      <span class="badge bg-secondary me-1">{{ loc.location_type_label }}</span>
                      {{ loc.location_label }}
                    </td>
                    <td class="text-end fw-semibold">{{ loc.head_count }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="col-lg-7">
              <h6>Detalle de animales</h6>
              <div class="table-responsive" style="max-height: 420px">
                <table class="table table-hover table-sm">
                  <thead>
                    <tr>
                      <th>Arete</th>
                      <th>Raza</th>
                      <th>Ubicación</th>
                      <th class="text-end">Peso</th>
                      <th class="text-end">GDP</th>
                      <th></th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="a in report.animals" :key="a.cattle_id">
                      <td>{{ a.ear_tag }}</td>
                      <td>{{ a.breed || '—' }}</td>
                      <td>
                        <span class="badge bg-light text-dark">{{ a.location_type_label }}</span>
                        {{ a.location_label }}
                      </td>
                      <td class="text-end">{{ a.last_weight_kg ?? '—' }}</td>
                      <td class="text-end">{{ a.daily_weight_gain ?? '—' }}</td>
                      <td>
                        <router-link :to="{ name: 'ranch-animal-detail', params: { id: a.cattle_id } }" class="btn btn-link btn-sm p-0">
                          Ver
                        </router-link>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <p v-else-if="report && !report.totals.head_count" class="text-muted">No hay animales con los filtros seleccionados.</p>
        </div>
      </div>
    </div>
  </div>
</template>

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

const loading = ref(false);
const report = ref(null);
const status = ref('active');
const locationType = ref('');
const pastures = ref([]);
const pastureId = ref('');
const breed = ref('');
const gender = ref('');

function params() {
  return {
    status: status.value,
    location_type: locationType.value || undefined,
    pasture_id: pastureId.value || undefined,
    breed: breed.value || undefined,
    gender: gender.value || undefined,
  };
}

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

async function exportCsv() {
  const blob = await RanchRepository.downloadInventoryReportCsv(params());
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `inventario-${status.value}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

onMounted(async () => {
  const catalog = await RanchRepository.catalog();
  pastures.value = catalog.pastures || [];
  await load();
});
</script>
