<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 mb-3 flex-wrap gap-2">
            <div>
              <h3 class="mb-1">Inventario de animales</h3>
              <p class="text-muted small mb-0">Lista de cabezas · en el expediente puedes subir foto, ver pesajes y costos</p>
            </div>
            <div class="d-flex gap-2">
              <router-link to="/ganaderia/inventario-ubicacion" class="btn btn-outline-secondary btn-sm">Por ubicación</router-link>
              <button class="btn btn-primary btn-sm" @click="openCreate">Registrar animal</button>
            </div>
          </div>

          <AppModal v-model="showForm" title="Nuevo animal" size="lg" :busy="saving">
            <form id="animal-create-form" @submit.prevent="saveAnimal" class="row g-2">
              <div class="col-md-4">
                <label class="form-label">Arete *</label>
                <input v-model="form.ear_tag" class="form-control" required />
              </div>
              <div class="col-md-4">
                <label class="form-label">Tipo arete</label>
                <select v-model="form.ear_tag_type" class="form-select">
                  <option value="internal">Interno</option>
                  <option value="siniiga">SINIIGA</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">Raza</label>
                <input v-model="form.breed" class="form-control" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Género *</label>
                <select v-model="form.gender" class="form-select" required>
                  <option value="male">Macho</option>
                  <option value="female">Hembra</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">Nacimiento</label>
                <input v-model="form.birth_date" type="date" class="form-control" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Potrero / corral</label>
                <select v-model="form.pasture_id" class="form-select">
                  <option :value="null">Sin asignar</option>
                  <option v-for="p in pastures" :key="p.id" :value="p.id">{{ p.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Arete madre (opcional)</label>
                <input v-model="motherEarTag" class="form-control" placeholder="Buscar y vincular" @blur="resolveMother" />
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="animal-create-form" class="btn btn-success" :disabled="saving">
                {{ saving ? 'Guardando…' : 'Guardar' }}
              </button>
            </template>
          </AppModal>

          <div class="row mb-3 g-2">
            <div class="col-md-4">
              <input v-model="search" class="form-control" placeholder="Buscar arete o raza..." @keyup.enter="load" />
            </div>
            <div class="col-md-2">
              <select v-model="statusFilter" class="form-select" @change="load">
                <option value="active">Solo activos</option>
                <option value="">Todos</option>
                <option value="sold">Vendidos</option>
                <option value="dead">Muertos</option>
                <option value="consumed">Consumidos</option>
              </select>
            </div>
            <div class="col-md-2">
              <select v-model="pastureFilter" class="form-select" @change="load">
                <option value="">Todos los potreros</option>
                <option v-for="p in pastures" :key="p.id" :value="p.id">{{ p.name }}</option>
              </select>
            </div>
            <div class="col-md-2">
              <button class="btn btn-secondary w-100" @click="load">Buscar</button>
            </div>
          </div>

          <div class="table-responsive">
            <table class="table table-hover">
              <thead>
                <tr>
                  <th style="width: 56px"></th>
                  <th>Arete</th>
                  <th>Raza</th>
                  <th>Género</th>
                  <th>Estatus</th>
                  <th>Ubicación</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="a in animals" :key="a.id">
                  <td>
                    <img
                      :src="a.photo_url || defaultAnimalImg"
                      :alt="a.ear_tag"
                      class="animal-thumb"
                    />
                  </td>
                  <td>{{ a.display_ear_tag || a.ear_tag || 'Sin arete' }}</td>
                  <td>{{ a.breed || '—' }}</td>
                  <td>{{ a.gender === 'female' ? 'Hembra' : 'Macho' }}</td>
                  <td><span class="badge" :class="statusClass(a.status)">{{ statusLabel(a.status) }}</span></td>
                  <td>{{ locationLabel(a) }}</td>
                  <td>
                    <router-link :to="{ name: 'ranch-animal-detail', params: { id: a.id } }" class="btn btn-sm btn-outline-primary">Expediente</router-link>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import RanchRepository from '@/repositories/RanchRepository';
import Swal from 'sweetalert2';
import defaultAnimalImg from '@/assets/images/user-avtar.svg';
import AppModal from '@/components/ui/AppModal.vue';

const pastures = ref([]);
const animals = ref([]);
const search = ref('');
const statusFilter = ref('active');
const pastureFilter = ref('');
const showForm = ref(false);
const saving = ref(false);
const motherEarTag = ref('');
const form = ref({
  ear_tag: '',
  ear_tag_type: 'internal',
  breed: '',
  gender: 'male',
  birth_date: '',
  pasture_id: null,
  mother_id: null,
});

function openCreate() {
  form.value = {
    ear_tag: '',
    ear_tag_type: 'internal',
    breed: '',
    gender: 'male',
    birth_date: '',
    pasture_id: null,
    mother_id: null,
  };
  motherEarTag.value = '';
  showForm.value = true;
}

function locationLabel(a) {
  if (a.active_fattening_lot_assignment?.fattening_lot?.name) {
    return 'Engorda: ' + a.active_fattening_lot_assignment.fattening_lot.name;
  }
  return a.pasture_location || '—';
}

async function resolveMother() {
  const tag = motherEarTag.value.trim();
  if (!tag) {
    form.value.mother_id = null;
    return;
  }
  try {
    const found = await RanchRepository.searchCattle(tag);
    if (found.gender !== 'female') {
      Swal.fire({ icon: 'warning', title: 'La madre debe ser hembra' });
      form.value.mother_id = null;
      return;
    }
    form.value.mother_id = found.id;
  } catch {
    Swal.fire({ icon: 'warning', title: 'No se encontró la madre con ese arete' });
    form.value.mother_id = null;
  }
}

function statusLabel(s) {
  const map = { active: 'Activo', sold: 'Vendido', dead: 'Muerto', consumed: 'Consumido' };
  return map[s] || s;
}

function statusClass(s) {
  return { active: 'bg-success', sold: 'bg-primary', dead: 'bg-danger', consumed: 'bg-warning' }[s] || 'bg-secondary';
}

async function load() {
  const params = {
    q: search.value || undefined,
    per_page: 50,
    pasture_id: pastureFilter.value || undefined,
  };
  if (statusFilter.value) {
    params.status = statusFilter.value;
    params.active_only = statusFilter.value === 'active';
  } else {
    params.active_only = false;
  }
  const page = await RanchRepository.listCattle(params);
  animals.value = page.data || [];
}

async function saveAnimal() {
  saving.value = true;
  try {
    await RanchRepository.createCattle({ ...form.value, mother_id: form.value.mother_id || null });
    Swal.fire({ icon: 'success', title: 'Animal registrado', timer: 1500, showConfirmButton: false });
    showForm.value = false;
    await load();
  } catch (e) {
    Swal.fire({ icon: 'error', title: 'Error', text: e.response?.data?.message || 'No se pudo guardar' });
  } finally {
    saving.value = false;
  }
}

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

<style scoped>
.animal-thumb {
  width: 44px;
  height: 44px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #e0e6ed;
}
</style>
