<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 mb-3 flex-wrap gap-2">
            <div>
              <h3 class="mb-1">Lotes de engorda</h3>
              <p class="text-muted small mb-0">Proyección y utilidad estimada se actualizan con los pesajes del lote.</p>
            </div>
            <div class="d-flex gap-2">
              <router-link to="/ganaderia/engorda-proyeccion" class="btn btn-outline-secondary btn-sm">Proyección cierre</router-link>
              <router-link to="/ganaderia/lotes-cerrados" class="btn btn-outline-secondary btn-sm">Comparar cerrados</router-link>
              <button class="btn btn-primary btn-sm" @click="openCreate">Nuevo lote</button>
            </div>
          </div>

          <AppModal v-model="showNew" title="Nuevo lote de engorda" size="lg" :busy="saving">
            <form id="lot-create-form" class="row g-2" @submit.prevent="createLot">
              <div class="col-md-6">
                <label class="form-label">Nombre *</label>
                <input v-model="newLot.name" class="form-control" placeholder="Nombre del lote" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha de entrada *</label>
                <input v-model="newLot.entry_date" type="date" class="form-control" required />
              </div>
              <div class="col-12">
                <label class="form-label">Descripción</label>
                <input v-model="newLot.description" class="form-control" placeholder="Descripción" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Duración engorda (días)</label>
                <input v-model.number="newLot.planned_duration_days" type="number" min="1" class="form-control" placeholder="90 (3 meses)" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Meta utilidad ($)</label>
                <input v-model.number="newLot.target_net_profit" type="number" class="form-control" placeholder="Meta utilidad $" />
              </div>
              <div class="col-md-4">
                <label class="form-label">$/kg proyección</label>
                <input v-model.number="newLot.target_price_per_kg" type="number" class="form-control" placeholder="$/kg proyección" />
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="lot-create-form" class="btn btn-success" :disabled="saving">
                {{ saving ? 'Creando…' : 'Crear' }}
              </button>
            </template>
          </AppModal>

          <div class="table-responsive">
            <table class="table table-hover align-middle">
              <thead>
                <tr>
                  <th>Nombre</th>
                  <th>Entrada</th>
                  <th class="text-end">Días</th>
                  <th class="text-end">Animales</th>
                  <th class="text-end">Inversión</th>
                  <th class="text-end">Vacunación</th>
                  <th class="text-end">Venta est.</th>
                  <th class="text-end">Ganancia est.</th>
                  <th>Estatus</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="lot in lots" :key="lot.id">
                  <td>{{ lot.name }}</td>
                  <td>{{ formatRanchDate(lot.entry_date) }}</td>
                  <td class="text-end">{{ daysSince(lot.entry_date) }}</td>
                  <td class="text-end">{{ lot.animals_count ?? 0 }}</td>
                  <td class="text-end">{{ formatMoney(lot.summary?.total_investment) }}</td>
                  <td class="text-end">{{ formatMoney(lot.summary?.health_cost) }}</td>
                  <td class="text-end">{{ formatMoney(lot.summary?.estimated_sale_total) }}</td>
                  <td class="text-end" :class="profitClass(lot.summary?.estimated_net_profit)">
                    {{ formatMoney(lot.summary?.estimated_net_profit) }}
                  </td>
                  <td>
                    <span class="badge" :class="lot.status === 'open' ? 'bg-success' : 'bg-secondary'">
                      {{ lot.status === 'open' ? 'Abierto' : 'Cerrado' }}
                    </span>
                  </td>
                  <td>
                    <div class="d-flex gap-1 justify-content-end lot-row-actions">
                      <router-link
                        :to="{ name: 'ranch-fattening-detail', params: { id: lot.id } }"
                        class="btn btn-sm btn-outline-primary"
                      >
                        Ver
                      </router-link>
                      <router-link
                        v-if="lot.status === 'open' && canWeigh"
                        :to="{ name: 'ranch-fattening-detail', params: { id: lot.id }, query: { tab: 'pesajes' } }"
                        class="btn btn-sm btn-primary lot-weigh-link"
                      >
                        Pesar
                      </router-link>
                    </div>
                  </td>
                </tr>
                <tr v-if="!lots.length">
                  <td colspan="10" class="text-muted text-center py-4">No hay lotes registrados.</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import RanchRepository from '@/repositories/RanchRepository';
import AppModal from '@/components/ui/AppModal.vue';
import { formatMoney, formatRanchDate } from '@/utils/ranchFormat';
import { usePermissions } from '@/composables/use-permissions';

const { hasPermission } = usePermissions();
const canWeigh = computed(() => hasPermission('ranch.weight.record'));

const lots = ref([]);
const showNew = ref(false);
const saving = ref(false);
const newLot = ref({
  name: '',
  entry_date: new Date().toISOString().slice(0, 10),
  description: '',
  planned_duration_days: 90,
  target_net_profit: null,
  target_price_per_kg: null,
});

function openCreate() {
  newLot.value = {
    name: '',
    entry_date: new Date().toISOString().slice(0, 10),
    description: '',
    planned_duration_days: 90,
    target_net_profit: null,
    target_price_per_kg: null,
  };
  showNew.value = true;
}

function daysSince(date) {
  const d = new Date(String(date).slice(0, 10));
  const today = new Date();
  return Math.max(0, Math.floor((today - d) / (1000 * 60 * 60 * 24)));
}

function profitClass(value) {
  if (value == null) return '';
  return Number(value) >= 0 ? 'text-success' : 'text-danger';
}

async function load() {
  const page = await RanchRepository.listFatteningLots();
  lots.value = page.data || [];
}

async function createLot() {
  saving.value = true;
  try {
    await RanchRepository.createFatteningLot(newLot.value);
    showNew.value = false;
    await load();
  } finally {
    saving.value = false;
  }
}

onMounted(load);
</script>

<style scoped>
.lot-row-actions {
  min-width: 132px;
}

.lot-weigh-link {
  font-weight: 600;
  box-shadow: 0 2px 6px rgba(67, 97, 238, 0.2);
}
</style>
