<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">Catálogo de potreros / corrales</h3>
              <p class="text-muted small mb-0">Ubicaciones para inventario y movimientos</p>
            </div>
            <button class="btn btn-primary btn-sm" type="button" @click="openCreate">Agregar potrero</button>
          </div>

          <AppModal
            v-model="showForm"
            :title="editingId ? 'Editar potrero' : 'Nuevo potrero'"
            size="md"
            :busy="saving"
          >
            <form id="pasture-form" class="row g-2" @submit.prevent="save">
              <div class="col-12">
                <label class="form-label">Nombre *</label>
                <input v-model="form.name" class="form-control" placeholder="Nombre" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Código</label>
                <input v-model="form.code" class="form-control" placeholder="Código" />
              </div>
              <div class="col-md-6">
                <label class="form-label">Orden</label>
                <input v-model.number="form.sort_order" type="number" class="form-control" placeholder="Orden" />
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="pasture-form" class="btn btn-primary" :disabled="saving">
                {{ saving ? 'Guardando…' : (editingId ? 'Actualizar' : 'Agregar') }}
              </button>
            </template>
          </AppModal>

          <div class="table-responsive">
            <table class="table table-hover">
              <thead>
                <tr>
                  <th>Nombre</th>
                  <th>Código</th>
                  <th class="text-end">Activos</th>
                  <th>Estado</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="p in pastures" :key="p.id">
                  <td>{{ p.name }}</td>
                  <td>{{ p.code || '—' }}</td>
                  <td class="text-end">{{ p.active_cattle_count ?? 0 }}</td>
                  <td>
                    <span class="badge" :class="p.active ? 'bg-success' : 'bg-secondary'">
                      {{ p.active ? 'Activo' : 'Inactivo' }}
                    </span>
                  </td>
                  <td class="text-end">
                    <button class="btn btn-sm btn-outline-primary me-1" type="button" @click="edit(p)">Editar</button>
                    <button
                      class="btn btn-sm btn-outline-warning"
                      type="button"
                      @click="toggleActive(p)"
                    >
                      {{ p.active ? 'Desactivar' : 'Activar' }}
                    </button>
                  </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 AppModal from '@/components/ui/AppModal.vue';

const pastures = ref([]);
const showForm = ref(false);
const saving = ref(false);
const editingId = ref(null);
const form = ref({ name: '', code: '', sort_order: 0 });

function resetForm() {
  editingId.value = null;
  form.value = { name: '', code: '', sort_order: 0 };
}

function openCreate() {
  resetForm();
  showForm.value = true;
}

function edit(p) {
  editingId.value = p.id;
  form.value = { name: p.name, code: p.code || '', sort_order: p.sort_order || 0 };
  showForm.value = true;
}

async function load() {
  pastures.value = await RanchRepository.listPastures(false);
}

async function save() {
  saving.value = true;
  try {
    if (editingId.value) {
      await RanchRepository.updatePasture(editingId.value, form.value);
    } else {
      await RanchRepository.createPasture(form.value);
    }
    Swal.fire({
      icon: 'success',
      title: editingId.value ? 'Potrero actualizado' : 'Potrero creado',
      timer: 1400,
      showConfirmButton: false,
    });
    showForm.value = false;
    resetForm();
    await load();
  } catch (e) {
    Swal.fire({ icon: 'error', title: 'Error', text: e.response?.data?.message || 'No se pudo guardar' });
  } finally {
    saving.value = false;
  }
}

async function toggleActive(p) {
  await RanchRepository.updatePasture(p.id, { active: !p.active });
  await load();
}

onMounted(load);
</script>
