<template>
  <div class="layout-px-spacing">
    <div class="row layout-top-spacing">
      <div class="col-12 layout-spacing">
        <div class="panel p-4 mb-3" v-if="summary">
          <h5 class="mb-2">Resumen del mes</h5>
          <p class="mb-1">
            Eventos: <strong>{{ summary.total_events }}</strong> ·
            Enfermedades: <strong>{{ summary.illness_count }}</strong> ·
            Gasto vacunación/salud: <strong>{{ money(summary.vaccination_cost) }}</strong> ·
            Gasto total: <strong>{{ money(summary.total_cost) }}</strong>
          </p>
          <div v-if="summary.at_risk_mothers?.length" class="alert alert-warning py-2 mb-0">
            <strong>{{ summary.at_risk_mothers.length }}</strong> vaca(s) con varias enfermedades en crías.
          </div>
        </div>

        <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">Historial de salud</h3>
              <p class="text-muted small mb-0">Vacunas, tratamientos y enfermedades</p>
            </div>
            <button class="btn btn-primary btn-sm" type="button" @click="openCreate">Registrar evento</button>
          </div>

          <AppModal v-model="showForm" title="Registrar evento de salud" size="lg" :busy="saving">
            <form id="health-event-form" class="row g-2" @submit.prevent="submit">
              <div class="col-md-6">
                <label class="form-label">Arete *</label>
                <input v-model="form.ear_tag" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Tipo *</label>
                <select v-model="form.event_type" class="form-select" required>
                  <option v-for="(label, key) in catalog.event_types" :key="key" :value="key">{{ label }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha *</label>
                <input v-model="form.event_date" type="date" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Concepto *</label>
                <input v-model="form.title" class="form-control" placeholder="Ej. Vacuna clostridial" required />
              </div>
              <div class="col-12">
                <label class="form-label">Producto / medicamento</label>
                <input v-model="form.product_name" class="form-control" />
              </div>
              <div class="col-md-6" v-if="form.event_type === 'illness'">
                <label class="form-label">Resultado *</label>
                <select v-model="form.outcome" class="form-select" required>
                  <option value="">Seleccione...</option>
                  <option v-for="(label, key) in catalog.outcomes" :key="key" :value="key">{{ label }}</option>
                </select>
              </div>
              <div class="col-md-6" v-else-if="form.outcome">
                <label class="form-label">Resultado</label>
                <select v-model="form.outcome" class="form-select">
                  <option value="">—</option>
                  <option v-for="(label, key) in catalog.outcomes" :key="key" :value="key">{{ label }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Costo ($)</label>
                <input v-model.number="form.cost" type="number" step="0.01" class="form-control" />
                <small v-if="catalog.auto_material_expense" class="text-muted">
                  Si indica costo, se crea automáticamente el gasto en materiales (Salud Animal) para el balance.
                </small>
              </div>
              <div class="col-md-6" v-if="form.cost > 0 && catalog.material_types?.length">
                <label class="form-label">Material (salud)</label>
                <select v-model.number="form.material_type_id" class="form-select">
                  <option :value="null">Por defecto del catálogo</option>
                  <option v-for="m in catalog.material_types" :key="m.id" :value="m.id">{{ m.name }}</option>
                </select>
              </div>
              <div class="col-12">
                <label class="form-label">Notas</label>
                <textarea v-model="form.notes" class="form-control" rows="2" />
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="health-event-form" class="btn btn-primary" :disabled="saving">
                {{ saving ? 'Guardando…' : 'Guardar' }}
              </button>
            </template>
          </AppModal>

          <ul class="nav nav-pills mb-3 gap-1">
            <li class="nav-item">
              <button type="button" class="nav-link py-1 px-3" :class="{ active: healthListMode === 'animal' }" @click="healthListMode = 'animal'">
                Por animal (dosis)
              </button>
            </li>
            <li class="nav-item">
              <button type="button" class="nav-link py-1 px-3" :class="{ active: healthListMode === 'date' }" @click="healthListMode = 'date'">
                Por fecha
              </button>
            </li>
          </ul>

          <template v-if="healthListMode === 'animal'">
            <div v-if="!healthByAnimal.length" class="text-muted text-center py-4">Sin eventos de salud.</div>
            <div v-for="animal in healthByAnimal" :key="animal.cattle_id" class="animal-health-group mb-3">
              <div class="animal-health-header d-flex justify-content-between align-items-center flex-wrap gap-2">
                <h6 class="mb-0">
                  Arete {{ animal.ear_tag }}
                  <router-link :to="{ name: 'ranch-animal-detail', params: { id: animal.cattle_id } }" class="small ms-2">Ver animal</router-link>
                </h6>
                <span class="small text-muted">
                  {{ animal.applications.length }} aplicaciones · Total: <strong class="text-body">{{ money(animal.total_cost) }}</strong>
                </span>
              </div>
              <div class="table-responsive">
                <table class="table table-sm table-hover mb-0">
                  <thead>
                    <tr>
                      <th>Fecha</th>
                      <th>Tipo</th>
                      <th>Concepto</th>
                      <th class="text-end">Dosis</th>
                      <th class="text-end">Gasto</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="app in animal.applications" :key="app.id">
                      <td>{{ formatRanchDate(app.event_date) }}</td>
                      <td>{{ typeLabel(app.event_type) }}</td>
                      <td>{{ app.title }}</td>
                      <td class="text-end">{{ healthEventDose(app) }}</td>
                      <td>
                        <span v-if="eventCost(app)" class="badge bg-success">{{ money(eventCost(app)) }}</span>
                        <span v-else>—</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </template>

          <div v-else class="table-responsive">
            <table class="table table-sm table-hover">
              <thead>
                <tr>
                  <th>Fecha</th>
                  <th>Arete</th>
                  <th>Tipo</th>
                  <th>Concepto</th>
                  <th class="text-end">Dosis</th>
                  <th>Resultado</th>
                  <th>Gasto</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="e in events" :key="e.id">
                  <td>{{ formatRanchDate(e.event_date) }}</td>
                  <td>
                    <router-link :to="{ name: 'ranch-animal-detail', params: { id: e.cattle_id } }">
                      {{ e.cattle?.ear_tag }}
                    </router-link>
                  </td>
                  <td>{{ typeLabel(e.event_type) }}</td>
                  <td>{{ e.title }}</td>
                  <td class="text-end">{{ healthEventDose(e) }}</td>
                  <td>{{ outcomeLabel(e.outcome) }}</td>
                  <td>
                    <span v-if="eventCost(e)" class="badge bg-success">{{ money(eventCost(e)) }}</span>
                    <span v-else>—</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue';
import RanchRepository from '@/repositories/RanchRepository';
import Swal from 'sweetalert2';
import AppModal from '@/components/ui/AppModal.vue';
import { formatRanchDate, healthEventDose } from '@/utils/ranchFormat';

const catalog = ref({ event_types: {}, outcomes: {}, material_types: [], auto_material_expense: true });
const form = ref({
  ear_tag: '',
  event_type: 'vaccination',
  event_date: new Date().toISOString().slice(0, 10),
  title: '',
  product_name: '',
  outcome: '',
  cost: null,
  material_type_id: null,
  notes: '',
});
const events = ref([]);
const summary = ref(null);
const healthListMode = ref('animal');
const showForm = ref(false);
const saving = ref(false);

function typeLabel(t) {
  return catalog.value.event_types?.[t] || t;
}

function outcomeLabel(o) {
  if (!o) return '—';
  return catalog.value.outcomes?.[o] || o;
}

function money(n) {
  return new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n || 0);
}

function eventCost(event) {
  return event.material_expense?.total_cost ?? event.cost ?? null;
}

const healthByAnimal = computed(() => {
  const byCattle = new Map();

  for (const event of events.value) {
    const cattleId = event.cattle_id ?? event.cattle?.id;
    if (!cattleId) continue;

    if (!byCattle.has(cattleId)) {
      byCattle.set(cattleId, {
        cattle_id: cattleId,
        ear_tag: event.cattle?.ear_tag || '—',
        applications: [],
        total_cost: 0,
      });
    }

    const row = byCattle.get(cattleId);
    row.applications.push(event);
    row.total_cost += Number(eventCost(event) || 0);
  }

  return [...byCattle.values()]
    .map((row) => ({
      ...row,
      applications: [...row.applications].sort((a, b) => String(b.event_date).localeCompare(String(a.event_date))),
      total_cost: Math.round(row.total_cost * 100) / 100,
    }))
    .sort((a, b) => String(a.ear_tag).localeCompare(String(b.ear_tag)));
});

function resetForm() {
  form.value = {
    ear_tag: '',
    event_type: 'vaccination',
    event_date: new Date().toISOString().slice(0, 10),
    title: '',
    product_name: '',
    outcome: '',
    cost: null,
    material_type_id: null,
    notes: '',
  };
}

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

watch(
  () => form.value.event_type,
  (t) => {
    if (t !== 'illness') form.value.outcome = '';
  }
);

async function load() {
  const [cat, page, sum] = await Promise.all([
    RanchRepository.healthCatalog(),
    RanchRepository.listHealthEvents({ per_page: 100 }),
    RanchRepository.healthSummary({
      from: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10),
      to: new Date().toISOString().slice(0, 10),
    }),
  ]);
  catalog.value = cat;
  events.value = page.data || [];
  summary.value = sum;
}

async function submit() {
  saving.value = true;
  try {
    await RanchRepository.createHealthEvent({ ...form.value, cost: form.value.cost || null });
    Swal.fire({ icon: 'success', title: 'Evento registrado', timer: 1200, showConfirmButton: false });
    showForm.value = false;
    await load();
  } catch (e) {
    Swal.fire({ icon: 'error', text: e.response?.data?.message || 'Error al guardar' });
  } finally {
    saving.value = false;
  }
}

onMounted(load);
</script>

<style scoped>
.animal-health-group {
  border: 1px solid var(--bs-border-color, #dee2e6);
  border-radius: 0.5rem;
  overflow: hidden;
}

.animal-health-header {
  padding: 0.75rem 1rem;
  background: var(--bs-light, #f8f9fa);
  border-bottom: 1px solid var(--bs-border-color, #dee2e6);
}

.animal-health-group .table {
  margin-bottom: 0;
}

.animal-health-group .table thead th {
  background: #fff;
  border-top: none;
}
</style>
