<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">Movimientos de ubicación</h3>
              <p class="text-muted mb-0">
                Historial de traslados entre corrales/pastos y entradas o salidas de engorda.
              </p>
            </div>
            <button class="btn btn-primary btn-sm" type="button" @click="openCreate">Mover animal</button>
          </div>

          <AppModal v-model="showForm" title="Mover a otro corral / pasto" size="lg" :busy="saving">
            <form id="location-move-form" class="row g-2" @submit.prevent="submitMove">
              <div class="col-md-6">
                <label class="form-label">Arete *</label>
                <input v-model="moveForm.ear_tag" class="form-control" required @blur="resolveCattle" />
                <small v-if="cattlePreview" class="text-muted">{{ cattlePreview.metrics?.location_label || '—' }}</small>
              </div>
              <div class="col-md-6">
                <label class="form-label">Nuevo potrero / corral</label>
                <select v-model="moveForm.pasture_id" class="form-select">
                  <option :value="null">Sin ubicación</option>
                  <option v-for="p in pastures" :key="p.id" :value="p.id">{{ p.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha</label>
                <input v-model="moveForm.moved_at" type="date" class="form-control" />
              </div>
              <div class="col-md-6">
                <label class="form-label">Notas</label>
                <input v-model="moveForm.notes" class="form-control" />
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="location-move-form" class="btn btn-success" :disabled="saving || !cattleId">
                {{ saving ? 'Guardando…' : 'Mover' }}
              </button>
            </template>
          </AppModal>

          <form class="row g-2 mb-3" @submit.prevent="load">
            <div class="col-md-3">
              <input v-model="filters.ear_tag" class="form-control" placeholder="Arete" />
            </div>
            <div class="col-md-2">
              <input v-model="filters.from" type="date" class="form-control" />
            </div>
            <div class="col-md-2">
              <input v-model="filters.to" type="date" class="form-control" />
            </div>
            <div class="col-md-2">
              <select v-model="filters.reason" class="form-select">
                <option value="">Todos los motivos</option>
                <option value="manual_pasture">Cambio de corral</option>
                <option value="fattening_entry">Entrada engorda</option>
                <option value="fattening_exit">Salida engorda</option>
                <option value="deactivation">Baja</option>
                <option value="calving">Parto / alta</option>
              </select>
            </div>
            <div class="col-md-2">
              <button class="btn btn-secondary w-100">Filtrar</button>
            </div>
          </form>

          <div class="table-responsive">
            <table class="table table-hover table-sm">
              <thead>
                <tr>
                  <th>Fecha</th>
                  <th>Arete</th>
                  <th>Motivo</th>
                  <th>Desde</th>
                  <th>Hacia</th>
                  <th>Notas</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in rows" :key="row.id">
                  <td>{{ row.moved_at?.slice?.(0, 10) || row.moved_at }}</td>
                  <td>{{ row.cattle?.ear_tag }}</td>
                  <td>{{ reasonLabel(row.reason) }}</td>
                  <td>{{ formatLoc(row.from_type, row.from_label) }}</td>
                  <td>{{ formatLoc(row.to_type, row.to_label) }}</td>
                  <td class="small text-muted">{{ row.notes || '—' }}</td>
                  <td>
                    <router-link
                      v-if="row.cattle"
                      :to="{ name: 'ranch-animal-detail', params: { id: row.cattle.id } }"
                      class="btn btn-link btn-sm p-0"
                    >
                      Ver
                    </router-link>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const route = useRoute();
const pastures = ref([]);
const rows = ref([]);
const showForm = ref(false);
const saving = ref(false);
const cattleId = ref(null);
const cattlePreview = ref(null);
const moveForm = ref({
  ear_tag: '',
  pasture_id: null,
  moved_at: new Date().toISOString().slice(0, 10),
  notes: '',
});
const filters = ref({ ear_tag: '', from: '', to: '', reason: '' });

const reasonMap = {
  manual_pasture: 'Cambio de corral',
  fattening_entry: 'Entrada a engorda',
  fattening_exit: 'Salida de engorda',
  deactivation: 'Baja',
  calving: 'Parto / alta',
};

const typeMap = {
  pasture: 'Corral/pasto',
  fattening: 'Engorda',
  unassigned: 'Sin ubicación',
};

function reasonLabel(r) {
  return reasonMap[r] || r;
}

function formatLoc(type, label) {
  const t = typeMap[type] || type;
  return label ? `${t}: ${label}` : t;
}

function resetForm() {
  moveForm.value = {
    ear_tag: '',
    pasture_id: null,
    moved_at: new Date().toISOString().slice(0, 10),
    notes: '',
  };
  cattleId.value = null;
  cattlePreview.value = null;
}

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

async function resolveCattle() {
  const tag = moveForm.value.ear_tag.trim();
  if (!tag) {
    cattleId.value = null;
    cattlePreview.value = null;
    return;
  }
  try {
    const found = await RanchRepository.searchCattle(tag);
    cattleId.value = found.id;
    cattlePreview.value = await RanchRepository.getCattle(found.id);
  } catch {
    cattleId.value = null;
    cattlePreview.value = null;
  }
}

async function submitMove() {
  if (!cattleId.value) return;
  saving.value = true;
  try {
    await RanchRepository.moveCattlePasture(cattleId.value, {
      pasture_id: moveForm.value.pasture_id || null,
      moved_at: moveForm.value.moved_at,
      notes: moveForm.value.notes || undefined,
    });
    Swal.fire({ icon: 'success', title: 'Ubicación actualizada', timer: 1500, showConfirmButton: false });
    showForm.value = false;
    await load();
  } catch (e) {
    Swal.fire({ icon: 'error', title: 'Error', text: e.response?.data?.message || 'No se pudo mover' });
  } finally {
    saving.value = false;
  }
}

async function load() {
  const params = {};
  if (filters.value.ear_tag) params.ear_tag = filters.value.ear_tag;
  if (filters.value.from) params.from = filters.value.from;
  if (filters.value.to) params.to = filters.value.to;
  if (filters.value.reason) params.reason = filters.value.reason;
  const page = await RanchRepository.listLocationMovements(params);
  rows.value = page.data || [];
}

onMounted(async () => {
  const catalog = await RanchRepository.catalog();
  pastures.value = catalog.pastures || [];
  if (route.query.ear_tag) {
    moveForm.value.ear_tag = String(route.query.ear_tag);
    filters.value.ear_tag = moveForm.value.ear_tag;
    await resolveCattle();
    showForm.value = true;
  }
  await load();
});
</script>
