<template>
  <div class="layout-px-spacing">
    <div class="row layout-top-spacing">
      <div class="col-12 layout-spacing">
        <div class="panel p-4">
          <h3>Rendimiento de peso (GDP)</h3>
          <p class="text-muted">
            Identifica animales con ganancia diaria baja, sin pesajes recientes o sin historial suficiente.
          </p>

          <form class="row g-2 mb-4" @submit.prevent="load">
            <div class="col-md-3">
              <label class="form-label">GDP mínimo esperado (kg/día)</label>
              <input v-model.number="minGdp" type="number" step="0.01" min="0" class="form-control" />
            </div>
            <div class="col-md-3">
              <label class="form-label">Alerta si no se pesa (días)</label>
              <input v-model.number="daysWithoutWeigh" type="number" min="1" class="form-control" />
            </div>
            <div class="col-md-3 d-flex align-items-end gap-2">
              <button type="submit" class="btn btn-primary flex-grow-1" :disabled="loading">Actualizar</button>
            </div>
            <div class="col-md-3 d-flex align-items-end" v-if="canNotify">
              <button type="button" class="btn btn-outline-secondary w-100" :disabled="sendingEmail" @click="sendEmail">
                {{ sendingEmail ? 'Enviando...' : 'Enviar alertas por correo' }}
              </button>
            </div>
          </form>

          <div v-if="report" class="alert alert-warning" v-show="report.alert_count > 0">
            <strong>{{ report.alert_count }}</strong> animal(es) requieren atención según los criterios actuales.
          </div>

          <div v-if="report?.alerts?.length" class="mb-4">
            <h5 class="text-danger">Alertas</h5>
            <div class="table-responsive">
              <table class="table table-sm table-bordered">
                <thead>
                  <tr>
                    <th>Arete</th>
                    <th>Lote engorda</th>
                    <th>Último pesaje</th>
                    <th>Kg</th>
                    <th>GDP</th>
                    <th class="text-end">Meta</th>
                    <th>Motivo</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="row in report.alerts" :key="row.cattle_id" class="table-warning">
                    <td>{{ row.ear_tag }}</td>
                    <td>{{ row.fattening_lot || '—' }}</td>
                    <td>{{ row.last_weighed_at || '—' }}</td>
                    <td>{{ row.last_weight_kg ?? '—' }}</td>
                    <td>{{ formatGdp(row.daily_weight_gain) }}</td>
                    <td class="text-end">{{ formatGdp(row.effective_min_gdp_kg_per_day) }}</td>
                    <td>{{ row.alert_message }}</td>
                    <td>
                      <router-link :to="{ name: 'ranch-animal-detail', params: { id: row.cattle_id } }" class="btn btn-sm btn-outline-primary">
                        Ver
                      </router-link>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <h5>Todos los animales activos</h5>
          <div class="table-responsive" v-if="report">
            <table class="table table-hover table-sm">
              <thead>
                <tr>
                  <th>Arete</th>
                  <th>Raza</th>
                  <th>Último pesaje</th>
                  <th>Peso kg</th>
                  <th>Ganancia</th>
                  <th>GDP kg/día</th>
                  <th class="text-end">Meta GDP</th>
                  <th>Días sin pesar</th>
                </tr>
              </thead>
              <tbody>
                <tr
                  v-for="row in report.all_active"
                  :key="row.cattle_id"
                  :class="{ 'table-warning': row.alert_type }"
                >
                  <td>
                    <router-link :to="{ name: 'ranch-animal-detail', params: { id: row.cattle_id } }">
                      {{ row.ear_tag }}
                    </router-link>
                  </td>
                  <td>{{ row.breed || '—' }}</td>
                  <td>{{ row.last_weighed_at || '—' }}</td>
                  <td>{{ row.last_weight_kg ?? '—' }}</td>
                  <td>{{ row.weight_gain_kg ?? '—' }}</td>
                  <td>{{ formatGdp(row.daily_weight_gain) }}</td>
                  <td class="text-end">{{ formatGdp(row.effective_min_gdp_kg_per_day) }}</td>
                  <td>{{ row.days_since_weigh ?? '—' }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const { hasAnyPermission } = usePermissions();
const canNotify = computed(() => hasAnyPermission(['administracion.usuarios', 'ranch.reports.view']));

const minGdp = ref(0.5);
const daysWithoutWeigh = ref(30);
const report = ref(null);
const loading = ref(false);
const sendingEmail = ref(false);

function formatGdp(v) {
  if (v === null || v === undefined) return '—';
  return Number(v).toFixed(2);
}

async function load() {
  loading.value = true;
  try {
    report.value = await RanchRepository.weightPerformance({
      min_gdp: minGdp.value,
      days_without_weigh: daysWithoutWeigh.value,
    });
  } finally {
    loading.value = false;
  }
}

async function sendEmail() {
  sendingEmail.value = true;
  try {
    const result = await RanchRepository.sendWeightAlertEmail({
      min_gdp: minGdp.value,
      days_without_weigh: daysWithoutWeigh.value,
    });
    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 {
    sendingEmail.value = false;
  }
}

onMounted(load);
</script>
