<template>
  <div class="layout-px-spacing">
    <div class="row layout-top-spacing">
      <div class="col-lg-8 mx-auto layout-spacing">
        <div class="panel p-4">
          <h3 class="mb-4">Baja de animal</h3>
          <div class="mb-3">
            <span class="badge bg-secondary me-2">1. Buscar</span>
            <span class="badge bg-secondary me-2">2. Motivo</span>
            <span class="badge bg-secondary me-2">3. Peso / precio</span>
            <span class="badge bg-secondary">4. Confirmar</span>
          </div>

          <div v-if="step === 1">
            <label class="form-label">Número de arete</label>
            <div class="input-group mb-3">
              <input v-model="earTag" class="form-control" @keyup.enter="search" />
              <button class="btn btn-primary" @click="search">Buscar</button>
            </div>
            <div v-if="cattle" class="alert alert-success">
              <strong>{{ cattle.ear_tag }}</strong> — {{ cattle.breed }} ({{ cattle.gender }})
              <br />
              Ubicación: <strong>{{ cattle.location_label || 'Sin ubicación' }}</strong>
              <button class="btn btn-sm btn-success float-end" @click="step = 2">Continuar</button>
            </div>
          </div>

          <div v-if="step === 2">
            <label class="form-label">Motivo de baja *</label>
            <select v-model="form.reason" class="form-select mb-3">
              <option value="sold">Venta</option>
              <option value="dead">Muerte</option>
              <option value="consumed">Consumo</option>
            </select>
            <div v-if="form.reason === 'dead'" class="mb-3">
              <label class="form-label">Causa de muerte *</label>
              <input v-model="form.death_cause" class="form-control" />
            </div>
            <button class="btn btn-secondary me-2" @click="step = 1">Atrás</button>
            <button class="btn btn-primary" @click="step = 3">Siguiente</button>
          </div>

          <div v-if="step === 3">
            <div class="mb-2">
              <label class="form-label">Peso de salida (kg) *</label>
              <input
                v-model.number="form.exit_weight_kg"
                type="number"
                step="0.01"
                class="form-control"
                @change="loadClosurePreview"
              />
            </div>
            <div v-if="form.reason === 'sold'" class="row g-2">
              <div class="col-md-6">
                <label class="form-label">Precio por kg</label>
                <input v-model.number="form.price_per_kg" type="number" step="0.01" class="form-control" />
              </div>
              <div class="col-md-6">
                <label class="form-label">Precio total</label>
                <input v-model.number="form.total_price" type="number" step="0.01" class="form-control" />
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha de venta</label>
                <input v-model="form.sale_date" type="date" class="form-control" />
              </div>
            </div>
            <button class="btn btn-secondary me-2 mt-2" @click="step = 2">Atrás</button>
            <button class="btn btn-primary mt-2" @click="goReview">Revisar</button>
          </div>

          <div v-if="step === 4">
            <p>
              Arete <strong>{{ cattle?.ear_tag }}</strong> — Motivo: <strong>{{ reasonLabel }}</strong> —
              Peso salida: <strong>{{ form.exit_weight_kg }} kg</strong>
            </p>

            <div v-if="closurePreview" class="card card-body bg-light mb-3">
              <h6 class="mb-2">Cierre de historial</h6>
              <ul class="mb-0 small">
                <li v-if="closurePreview.current_fattening_lot">
                  Lote actual: <strong>{{ closurePreview.current_fattening_lot }}</strong>
                </li>
                <li>
                  Días totales en engorda: <strong>{{ closurePreview.total_days_in_fattening }}</strong>
                </li>
                <li>
                  Alimento asignado (engorda): <strong>${{ closurePreview.total_allocated_feed_cost }}</strong>
                </li>
                <li v-if="closurePreview.current_stint_weight_gain_kg != null">
                  Ganancia en ciclo actual: <strong>{{ closurePreview.current_stint_weight_gain_kg }} kg</strong>
                </li>
                <li v-if="closurePreview.lifetime_weight_gain_kg != null">
                  Ganancia desde primer pesaje: <strong>{{ closurePreview.lifetime_weight_gain_kg }} kg</strong>
                </li>
              </ul>
              <div v-if="closurePreview.fattening_stints?.length" class="mt-2">
                <p class="mb-1 fw-semibold">Ciclos de engorda</p>
                <div
                  v-for="(stint, i) in closurePreview.fattening_stints"
                  :key="i"
                  class="border-top pt-1 mt-1 small"
                >
                  {{ stint.lot_name }}: {{ stint.entry_weight_kg }} → {{ stint.exit_weight_kg ?? '?' }} kg
                  ({{ stint.days_in_confinement }} días, alimento ${{ stint.allocated_feed_cost }})
                </div>
              </div>
            </div>

            <p v-if="form.reason === 'sold'" class="text-muted small">
              Se registrará ingreso por venta en el periodo de la fecha indicada.
            </p>
            <p v-if="form.reason === 'dead'" class="text-muted small">
              Se contabilizará en la tasa de mortalidad del periodo (pérdida de activo).
            </p>

            <button class="btn btn-secondary me-2" @click="step = 3">Atrás</button>
            <button class="btn btn-danger" :disabled="loading" @click="confirm">Confirmar baja</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import RanchRepository from '@/repositories/RanchRepository';
import Swal from 'sweetalert2';

const router = useRouter();
const step = ref(1);
const earTag = ref('');
const cattle = ref(null);
const closurePreview = ref(null);
const loading = ref(false);
const form = ref({
  reason: 'sold',
  exit_weight_kg: null,
  death_cause: '',
  price_per_kg: null,
  total_price: null,
  sale_date: new Date().toISOString().slice(0, 10),
});

const reasonLabel = computed(() => {
  const map = { sold: 'Venta', dead: 'Muerte', consumed: 'Consumo' };
  return map[form.value.reason] || form.value.reason;
});

async function search() {
  try {
    cattle.value = await RanchRepository.searchCattle(earTag.value.trim());
    if (cattle.value.status !== 'active') {
      Swal.fire({ icon: 'warning', title: 'El animal no está activo' });
      cattle.value = null;
      return;
    }
  } catch {
    Swal.fire({ icon: 'error', title: 'No encontrado' });
    cattle.value = null;
  }
}

async function loadClosurePreview() {
  if (!cattle.value?.ear_tag || !form.value.exit_weight_kg) {
    closurePreview.value = null;
    return;
  }
  try {
    const data = await RanchRepository.searchCattle(cattle.value.ear_tag, {
      exit_weight_kg: form.value.exit_weight_kg,
    });
    closurePreview.value = data.deactivation_preview || null;
  } catch {
    closurePreview.value = null;
  }
}

async function goReview() {
  if (!form.value.exit_weight_kg) {
    Swal.fire({ icon: 'warning', title: 'Indique el peso de salida' });
    return;
  }
  await loadClosurePreview();
  step.value = 4;
}

async function confirm() {
  loading.value = true;
  try {
    const result = await RanchRepository.deactivateCattle(cattle.value.id, form.value);
    const summary = result.closure_summary;
    let extra = '';
    if (summary?.total_allocated_feed_cost) {
      extra = ` Alimento en engorda: $${summary.total_allocated_feed_cost}.`;
    }
    Swal.fire({ icon: 'success', title: 'Baja registrada', text: extra });
    router.push({ name: 'ranch-animals' });
  } catch (e) {
    Swal.fire({ icon: 'error', text: e.response?.data?.message || 'Error al dar de baja' });
  } finally {
    loading.value = false;
  }
}
</script>
