<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">Registro de partos</h3>
              <p class="text-muted mb-0">
                Da de alta el becerro y lo vincula a la madre. El arete del becerro es opcional al nacer.
                Opcional: peso al nacer (primer pesaje).
              </p>
            </div>
            <button class="btn btn-primary btn-sm" type="button" @click="openCreate">Registrar parto</button>
          </div>

          <AppModal v-model="showForm" title="Nuevo parto" size="lg" :busy="saving">
            <form id="calving-form" class="row g-2" @submit.prevent="submit">
              <div class="col-md-6">
                <label class="form-label">Arete madre *</label>
                <input
                  v-model="form.mother_ear_tag"
                  class="form-control"
                  required
                  placeholder="Buscar vaca"
                  @blur="resolveMother"
                />
                <small v-if="motherPreview" class="text-success">{{ motherPreview.breed || 'Sin raza' }} · {{ motherPreview.pasture_location || 'Sin corral' }}</small>
              </div>
              <div class="col-md-6">
                <label class="form-label">Arete becerro</label>
                <input v-model="form.ear_tag" class="form-control" placeholder="Opcional al nacer" />
                <small class="text-muted">Si aún no tiene arete, déjalo vacío y asígnalo después.</small>
              </div>
              <div class="col-md-4">
                <label class="form-label">Género *</label>
                <select v-model="form.gender" class="form-select" required>
                  <option value="male">Macho</option>
                  <option value="female">Hembra</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">Fecha parto *</label>
                <input v-model="form.calving_date" type="date" class="form-control" required />
              </div>
              <div class="col-md-4">
                <label class="form-label">Peso nacer (kg)</label>
                <input v-model.number="form.birth_weight_kg" type="number" step="0.01" class="form-control" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Raza</label>
                <input v-model="form.breed" class="form-control" placeholder="Hereda de madre" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Potrero / corral</label>
                <select v-model="form.pasture_id" class="form-select">
                  <option :value="null">Hereda de madre</option>
                  <option v-for="p in pastures" :key="p.id" :value="p.id">{{ p.name }}</option>
                </select>
              </div>
              <div class="col-md-4">
                <label class="form-label">Notas</label>
                <input v-model="form.calving_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="calving-form" class="btn btn-success" :disabled="saving">
                {{ saving ? 'Guardando…' : 'Registrar' }}
              </button>
            </template>
          </AppModal>

          <div class="card mb-4 p-3">
            <div class="d-flex justify-content-between align-items-center flex-wrap gap-2 mb-3">
              <h5 class="mb-0">Reporte por periodo</h5>
              <div v-if="report" class="d-flex gap-2">
                <button
                  v-if="canNotify"
                  type="button"
                  class="btn btn-outline-secondary btn-sm"
                  :disabled="sendingReportEmail || reportLoading"
                  @click="sendReportEmail"
                >
                  {{ sendingReportEmail ? 'Enviando...' : 'Enviar resumen por correo' }}
                </button>
                <button
                  type="button"
                  class="btn btn-outline-primary btn-sm"
                  :disabled="reportLoading"
                  @click="exportReportCsv"
                >
                  Exportar CSV
                </button>
              </div>
            </div>
            <form class="row g-2 mb-3" @submit.prevent="loadReport">
              <div class="col-md-2">
                <label class="form-label small">Desde</label>
                <input v-model="reportFilters.from" type="date" class="form-control" />
              </div>
              <div class="col-md-2">
                <label class="form-label small">Hasta</label>
                <input v-model="reportFilters.to" type="date" class="form-control" />
              </div>
              <div class="col-md-2">
                <label class="form-label small">Potrero</label>
                <select v-model="reportFilters.pasture_id" class="form-select">
                  <option value="">Todos</option>
                  <option v-for="p in pastures" :key="p.id" :value="p.id">{{ p.name }}</option>
                </select>
              </div>
              <div class="col-md-2 d-flex align-items-end">
                <button class="btn btn-primary w-100" :disabled="reportLoading">Generar</button>
              </div>
            </form>
            <div v-if="report" class="row g-3 mb-0">
              <div class="col-md-3">
                <div class="border rounded p-2">
                  <small class="text-muted">Partos</small>
                  <h5 class="mb-0">{{ report.totals.calvings_count }}</h5>
                </div>
              </div>
              <div class="col-md-3">
                <div class="border rounded p-2">
                  <small class="text-muted">Machos / hembras</small>
                  <h5 class="mb-0">{{ report.totals.male_calves }} / {{ report.totals.female_calves }}</h5>
                </div>
              </div>
              <div class="col-md-3">
                <div class="border rounded p-2">
                  <small class="text-muted">Peso prom. nacer</small>
                  <h5 class="mb-0">{{ report.totals.avg_birth_weight_kg ?? '—' }} kg</h5>
                </div>
              </div>
            </div>
            <table v-if="report?.by_mother?.length" class="table table-sm mt-3 mb-0">
              <thead>
                <tr><th>Vaca</th><th class="text-end">Partos</th></tr>
              </thead>
              <tbody>
                <tr v-for="m in report.by_mother.slice(0, 5)" :key="m.mother_id">
                  <td>{{ m.mother_ear_tag }}</td>
                  <td class="text-end">{{ m.calvings_count }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <form class="row g-2 mb-3" @submit.prevent="loadHistory">
            <div class="col-md-3">
              <input v-model="filters.mother_ear_tag" class="form-control" placeholder="Filtrar por madre" />
            </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">
              <button class="btn btn-secondary w-100">Filtrar historial</button>
            </div>
          </form>

          <div class="table-responsive">
            <table class="table table-hover table-sm">
              <thead>
                <tr>
                  <th>Fecha</th>
                  <th>Madre</th>
                  <th>Becerro</th>
                  <th>Género</th>
                  <th class="text-end">Peso nacer</th>
                  <th>Corral</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="row in history" :key="row.id">
                  <td>{{ row.calving_date }}</td>
                  <td>{{ row.mother?.ear_tag }}</td>
                  <td>{{ row.calf?.display_ear_tag || row.calf?.ear_tag || 'Sin arete' }}</td>
                  <td>{{ row.calf?.gender === 'female' ? 'Hembra' : 'Macho' }}</td>
                  <td class="text-end">{{ row.birth_weight_kg ?? '—' }}</td>
                  <td>{{ row.pasture_location || '—' }}</td>
                  <td>
                    <router-link
                      v-if="row.calf"
                      :to="{ name: 'ranch-animal-detail', params: { id: row.calf.id } }"
                      class="btn btn-sm btn-link p-0 me-2"
                    >
                      Ver
                    </router-link>
                    <router-link
                      v-if="row.calf && row.calf.status === 'active'"
                      :to="{ path: '/ganaderia/pesajes', query: { tab: 'becerros', calf_id: row.calf.id } }"
                      class="btn btn-sm btn-outline-primary"
                    >
                      Pesaje
                    </router-link>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const route = useRoute();
const { hasAnyPermission } = usePermissions();
const canNotify = computed(() =>
  hasAnyPermission(['administracion.usuarios', 'ranch.reports.view', 'ranch.cattle.view']),
);
const showForm = ref(false);
const saving = ref(false);
const sendingReportEmail = ref(false);
const motherPreview = ref(null);
const pastures = ref([]);
const history = ref([]);
const form = ref({
  mother_id: null,
  mother_ear_tag: '',
  ear_tag: '',
  gender: 'male',
  calving_date: new Date().toISOString().slice(0, 10),
  birth_weight_kg: null,
  breed: '',
  pasture_id: null,
  calving_notes: '',
});
const report = ref(null);
const reportLoading = ref(false);
const reportFilters = ref({
  from: new Date(new Date().getFullYear(), new Date().getMonth(), 1).toISOString().slice(0, 10),
  to: new Date().toISOString().slice(0, 10),
  pasture_id: '',
});
const filters = ref({ mother_ear_tag: '', from: '', to: '' });

function resetForm() {
  form.value = {
    mother_id: null,
    mother_ear_tag: '',
    ear_tag: '',
    gender: 'male',
    calving_date: new Date().toISOString().slice(0, 10),
    birth_weight_kg: null,
    breed: '',
    pasture_id: null,
    calving_notes: '',
  };
  motherPreview.value = null;
}

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

function reportParams() {
  return {
    from: reportFilters.value.from || undefined,
    to: reportFilters.value.to || undefined,
    pasture_id: reportFilters.value.pasture_id || undefined,
    mother_id: form.value.mother_id || undefined,
  };
}

async function loadReport() {
  reportLoading.value = true;
  try {
    report.value = await RanchRepository.calvingsReport(reportParams());
  } finally {
    reportLoading.value = false;
  }
}

async function exportReportCsv() {
  const blob = await RanchRepository.downloadCalvingsReportCsv(reportParams());
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `partos-${reportFilters.value.from || 'completo'}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

async function sendReportEmail() {
  sendingReportEmail.value = true;
  try {
    const result = await RanchRepository.sendCalvingReportEmail(reportParams());
    Swal.fire({
      icon: result.sent ? 'success' : 'info',
      title: result.sent ? 'Correo enviado' : 'Sin envío',
      text: result.message,
    });
  } catch {
    Swal.fire({ icon: 'error', title: 'No se pudo enviar el correo' });
  } finally {
    sendingReportEmail.value = false;
  }
}

async function resolveMother() {
  const tag = form.value.mother_ear_tag.trim();
  if (!tag) {
    motherPreview.value = null;
    form.value.mother_id = null;
    return;
  }
  try {
    const found = await RanchRepository.searchCattle(tag);
    if (found.gender !== 'female') {
      Swal.fire({ icon: 'warning', title: 'Debe ser una vaca (hembra)' });
      return;
    }
    form.value.mother_id = found.id;
    motherPreview.value = found;
    if (!form.value.breed) form.value.breed = found.breed || '';
    if (!form.value.pasture_id) form.value.pasture_id = found.pasture_id ?? null;
  } catch {
    motherPreview.value = null;
    form.value.mother_id = null;
  }
}

async function submit() {
  saving.value = true;
  try {
    const payload = {
      ...form.value,
      mother_id: form.value.mother_id || undefined,
      ear_tag: form.value.ear_tag?.trim() || null,
      birth_weight_kg: form.value.birth_weight_kg || undefined,
      breed: form.value.breed || undefined,
      pasture_id: form.value.pasture_id || undefined,
    };
    const result = await RanchRepository.registerCalving(payload);
    const calfLabel = result.calf.display_ear_tag || result.calf.ear_tag || 'Sin arete';
    Swal.fire({
      icon: 'success',
      title: 'Parto registrado',
      text: `Becerro ${calfLabel} vinculado a ${result.calving_event.mother.ear_tag}`,
      timer: 2500,
      showConfirmButton: false,
    });
    showForm.value = false;
    await Promise.all([loadHistory(), loadReport()]);
  } catch (e) {
    Swal.fire({ icon: 'error', title: 'Error', text: e.response?.data?.message || 'No se pudo registrar' });
  } finally {
    saving.value = false;
  }
}

async function loadHistory() {
  const params = {};
  if (filters.value.from) params.from = filters.value.from;
  if (filters.value.to) params.to = filters.value.to;
  if (form.value.mother_id) params.mother_id = form.value.mother_id;
  const page = await RanchRepository.listCalvings(params);
  history.value = page.data || [];
}

onMounted(async () => {
  const catalog = await RanchRepository.catalog();
  pastures.value = catalog.pastures || [];
  if (route.query.mother) {
    form.value.mother_ear_tag = String(route.query.mother);
    await resolveMother();
    showForm.value = true;
  }
  await Promise.all([loadHistory(), loadReport()]);
});
</script>
