<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 flex-wrap gap-2 mb-3">
            <div>
              <h3 class="mb-1">Catálogo de alimentos</h3>
              <p class="text-muted mb-0">Capítulo de comida: define precio por kg (u otra unidad) para calcular la inversión de las raciones.</p>
            </div>
            <button class="btn btn-primary btn-sm" type="button" @click="openCreate">Agregar alimento</button>
          </div>

          <AppModal
            v-model="showForm"
            :title="editingId ? 'Editar alimento' : 'Nuevo alimento'"
            size="md"
            :busy="saving"
          >
            <form id="feed-form" class="row g-2" @submit.prevent="save">
              <div class="col-12">
                <label class="form-label small">Nombre</label>
                <input v-model="form.name" class="form-control" placeholder="Ej. Maíz molido" required />
              </div>
              <div class="col-md-6">
                <label class="form-label small">Unidad</label>
                <input v-model="form.unit" class="form-control" placeholder="kg" />
              </div>
              <div class="col-md-6">
                <label class="form-label small">Precio unitario ($)</label>
                <input v-model.number="form.default_unit_price" type="number" step="0.0001" min="0" class="form-control" required />
              </div>
              <div class="col-12">
                <div class="form-check">
                  <input id="feed-active" v-model="form.active" class="form-check-input" type="checkbox" />
                  <label class="form-check-label" for="feed-active">Activo</label>
                </div>
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="feed-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>Alimento</th>
                  <th>Unidad</th>
                  <th class="text-end">Inventario</th>
                  <th class="text-end">Precio ref.</th>
                  <th>Estado</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in items" :key="item.id">
                  <td>{{ item.name }}</td>
                  <td>{{ item.unit }}</td>
                  <td class="text-end">{{ formatQuantity(item.stock_quantity, item.unit) }}</td>
                  <td class="text-end">{{ money(item.default_unit_price) }}</td>
                  <td>
                    <span class="badge" :class="item.active ? 'bg-success' : 'bg-secondary'">
                      {{ item.active ? 'Activo' : 'Inactivo' }}
                    </span>
                  </td>
                  <td class="text-end">
                    <button class="btn btn-sm btn-outline-primary me-1" type="button" @click="edit(item)">Editar</button>
                    <button
                      class="btn btn-sm btn-outline-secondary"
                      type="button"
                      @click="toggleActive(item)"
                    >
                      {{ item.active ? 'Desactivar' : 'Activar' }}
                    </button>
                  </td>
                </tr>
                <tr v-if="!items.length">
                  <td colspan="6" class="text-muted text-center">Aún no hay alimentos en el catálogo.</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';
import { formatQuantity } from '@/utils/ranchFormat';

const items = ref([]);
const editingId = ref(null);
const showForm = ref(false);
const saving = ref(false);
const form = ref({
  name: '',
  unit: 'kg',
  default_unit_price: null,
  active: true,
});

function money(n) {
  if (n === null || n === undefined || n === '') return '—';
  return new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(Number(n));
}

function resetForm() {
  editingId.value = null;
  form.value = { name: '', unit: 'kg', default_unit_price: null, active: true };
}

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

function edit(item) {
  editingId.value = item.id;
  form.value = {
    name: item.name,
    unit: item.unit || 'kg',
    default_unit_price: item.default_unit_price != null ? Number(item.default_unit_price) : null,
    active: !!item.active,
  };
  showForm.value = true;
}

async function load() {
  const [catalog, inventory] = await Promise.all([
    RanchRepository.listFeedCatalog(),
    RanchRepository.getFeedInventory(),
  ]);
  const stockById = Object.fromEntries((inventory || []).map((row) => [row.id, row.stock_quantity]));
  items.value = catalog.map((item) => ({
    ...item,
    stock_quantity: stockById[item.id] ?? item.stock_quantity ?? 0,
  }));
}

async function save() {
  saving.value = true;
  try {
    const payload = {
      category: 'feed_supplements',
      name: form.value.name,
      unit: form.value.unit || 'kg',
      default_unit_price: form.value.default_unit_price,
      active: form.value.active,
    };

    if (editingId.value) {
      await RanchRepository.updateMaterialType(editingId.value, payload);
    } else {
      await RanchRepository.createMaterialType(payload);
    }

    showForm.value = false;
    resetForm();
    await load();
    Swal.fire({ icon: 'success', title: 'Catálogo actualizado', timer: 1400, showConfirmButton: false });
  } catch (e) {
    Swal.fire('Error', e?.response?.data?.message || 'No se pudo guardar el alimento.', 'error');
  } finally {
    saving.value = false;
  }
}

async function toggleActive(item) {
  try {
    await RanchRepository.updateMaterialType(item.id, { active: !item.active });
    await load();
  } catch (e) {
    Swal.fire('Error', e?.response?.data?.message || 'No se pudo actualizar.', 'error');
  }
}

onMounted(load);
</script>
