<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">Pesajes</h3>
              <p class="text-muted small mb-0">Registro de peso, ganancia y GDP</p>
            </div>
            <button
              v-if="activeTab === 'historial'"
              class="btn btn-primary btn-sm"
              type="button"
              @click="openCreate()"
            >
              Registrar pesaje
            </button>
          </div>

          <nav class="ranch-tabs mb-3" aria-label="Tipo de pesaje">
            <button
              type="button"
              class="ranch-tab"
              :class="{ 'is-active': activeTab === 'becerros' }"
              @click="setTab('becerros')"
            >
              Becerros activos
            </button>
            <button
              type="button"
              class="ranch-tab"
              :class="{ 'is-active': activeTab === 'historial' }"
              @click="setTab('historial')"
            >
              Historial reciente
            </button>
          </nav>

          <!-- Becerros -->
          <template v-if="activeTab === 'becerros'">
            <p class="text-muted small mb-3">
              Becerros activos con madre registrada (últimos {{ maxAgeMonths }} meses).
              Puedes pesarlos aunque aún no tengan arete.
            </p>

            <div class="table-responsive">
              <table class="table table-sm table-hover align-middle">
                <thead>
                  <tr>
                    <th>Becerro</th>
                    <th>Madre</th>
                    <th>Edad</th>
                    <th>Último peso</th>
                    <th>GDP</th>
                    <th class="text-end">Acción</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="loadingCalves">
                    <td colspan="6" class="text-muted">Cargando becerros…</td>
                  </tr>
                  <tr v-else-if="!calves.length">
                    <td colspan="6" class="text-muted">No hay becerros activos para pesar.</td>
                  </tr>
                  <tr v-for="calf in calves" :key="calf.id">
                    <td>
                      <router-link :to="{ name: 'ranch-animal-detail', params: { id: calf.id } }">
                        {{ calf.display_ear_tag || calf.ear_tag || `#${calf.id}` }}
                      </router-link>
                      <span class="text-muted small ms-1">{{ calf.gender === 'female' ? 'H' : 'M' }}</span>
                    </td>
                    <td>{{ calf.mother?.ear_tag || '—' }}</td>
                    <td>{{ calf.age_months != null ? `${calf.age_months} m` : '—' }}</td>
                    <td>
                      <template v-if="calf.last_weight">
                        {{ calf.last_weight.weight_kg }} kg
                        <span class="text-muted small d-block">{{ calf.last_weight.weighed_at }}</span>
                      </template>
                      <span v-else class="text-muted">Sin pesaje</span>
                    </td>
                    <td>{{ calf.last_weight?.daily_weight_gain ?? '—' }}</td>
                    <td class="text-end">
                      <button
                        type="button"
                        class="btn btn-primary btn-sm"
                        @click="openCreate(calf)"
                      >
                        Pesaje
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </template>

          <!-- Historial -->
          <template v-else>
            <div class="table-responsive">
              <table class="table table-sm table-hover">
                <thead>
                  <tr><th>Arete</th><th>Fecha</th><th>Kg</th><th>GDP</th></tr>
                </thead>
                <tbody>
                  <tr v-for="r in records" :key="r.id">
                    <td>{{ r.cattle?.ear_tag || r.cattle?.display_ear_tag || '—' }}</td>
                    <td>{{ r.weighed_at }}</td>
                    <td>{{ r.weight_kg }}</td>
                    <td>{{ r.daily_weight_gain ?? '—' }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </template>

          <AppModal v-model="showForm" :title="formTitle" size="md" :busy="saving">
            <form id="weighing-form" class="row g-2" @submit.prevent="submit">
              <div v-if="selectedCalf" class="col-12">
                <div class="alert alert-light border mb-0 py-2">
                  <strong>Becerro:</strong> {{ selectedCalf.display_ear_tag || selectedCalf.ear_tag || `#${selectedCalf.id}` }}<br />
                  <span v-if="selectedCalf.mother?.ear_tag" class="text-muted small">Madre: {{ selectedCalf.mother.ear_tag }}</span>
                </div>
              </div>
              <div v-else class="col-12">
                <label class="form-label">Número de arete</label>
                <input v-model="form.ear_tag" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Peso (kg)</label>
                <input v-model.number="form.weight_kg" type="number" step="0.01" min="0.01" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha</label>
                <input v-model="form.weighed_at" type="date" class="form-control" required />
              </div>
              <div class="col-12">
                <label class="form-label">Notas (opcional)</label>
                <input v-model="form.notes" class="form-control" maxlength="500" placeholder="Ej. pesaje mensual becerros" />
              </div>
              <div v-if="lastResult" class="col-12">
                <div class="alert alert-info mb-0">
                  <strong>Ganancia:</strong> {{ lastResult.weight_gain_kg ?? 'Primer pesaje' }} kg<br />
                  <strong>GDP:</strong> {{ lastResult.daily_weight_gain ?? '—' }} kg/día
                </div>
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="weighing-form" class="btn btn-primary" :disabled="saving">
                {{ saving ? 'Guardando…' : 'Guardar pesaje' }}
              </button>
            </template>
          </AppModal>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import RanchRepository from '@/repositories/RanchRepository';
import Swal from 'sweetalert2';
import AppModal from '@/components/ui/AppModal.vue';

const route = useRoute();
const router = useRouter();

const activeTab = ref(route.query.tab === 'becerros' ? 'becerros' : 'historial');
const maxAgeMonths = 12;
const form = ref({
  cattle_id: null,
  ear_tag: '',
  weight_kg: null,
  weighed_at: new Date().toISOString().slice(0, 10),
  notes: '',
});
const records = ref([]);
const calves = ref([]);
const selectedCalf = ref(null);
const showForm = ref(false);
const saving = ref(false);
const loadingCalves = ref(false);
const lastResult = ref(null);

const formTitle = computed(() =>
  selectedCalf.value ? 'Pesaje de becerro' : 'Registrar pesaje',
);

function setTab(tab) {
  activeTab.value = tab;
  router.replace({ query: tab === 'becerros' ? { tab: 'becerros' } : {} });
  if (tab === 'becerros' && !calves.value.length) {
    loadCalves();
  }
}

function resetForm() {
  form.value = {
    cattle_id: null,
    ear_tag: '',
    weight_kg: null,
    weighed_at: new Date().toISOString().slice(0, 10),
    notes: '',
  };
  selectedCalf.value = null;
  lastResult.value = null;
}

function openCreate(calf = null) {
  resetForm();
  if (calf) {
    selectedCalf.value = calf;
    form.value.cattle_id = calf.id;
    if (calf.last_weight?.weight_kg) {
      form.value.weight_kg = Number(calf.last_weight.weight_kg);
    }
  }
  showForm.value = true;
}

async function loadRecords() {
  const page = await RanchRepository.listWeightRecords({ per_page: 30 });
  records.value = page.data || [];
}

async function loadCalves() {
  loadingCalves.value = true;
  try {
    calves.value = await RanchRepository.listCalvesForWeighing({ max_age_months: maxAgeMonths });
  } catch (e) {
    Swal.fire({ icon: 'error', title: 'Error', text: e.response?.data?.message || 'No se cargaron los becerros' });
  } finally {
    loadingCalves.value = false;
  }
}

async function submit() {
  saving.value = true;
  try {
    const payload = {
      weight_kg: form.value.weight_kg,
      weighed_at: form.value.weighed_at,
      notes: form.value.notes || undefined,
    };
    if (form.value.cattle_id) {
      payload.cattle_id = form.value.cattle_id;
    } else {
      payload.ear_tag = form.value.ear_tag.trim();
    }

    lastResult.value = await RanchRepository.createWeightRecord(payload);
    Swal.fire({ icon: 'success', title: 'Pesaje registrado', timer: 1200, showConfirmButton: false });
    showForm.value = false;
    await Promise.all([loadRecords(), loadCalves()]);
  } catch (e) {
    Swal.fire({ icon: 'error', title: 'Error', text: e.response?.data?.message || 'No se registró' });
  } finally {
    saving.value = false;
  }
}

watch(
  () => route.query.tab,
  (tab) => {
    activeTab.value = tab === 'becerros' ? 'becerros' : 'historial';
    if (activeTab.value === 'becerros') loadCalves();
  },
);

onMounted(async () => {
  await loadRecords();
  if (activeTab.value === 'becerros') {
    await loadCalves();
    openCalfFromQuery();
  }
});

function openCalfFromQuery() {
  const calfId = Number(route.query.calf_id);
  if (!calfId) return;
  const calf = calves.value.find((c) => c.id === calfId);
  if (calf) {
    openCreate(calf);
  }
}

watch(
  () => route.query.calf_id,
  () => {
    if (activeTab.value === 'becerros' && calves.value.length) {
      openCalfFromQuery();
    }
  },
);
</script>
