<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">Alertas de costo por kg</h3>
              <p class="text-muted mb-0">
                Animales <strong>activos</strong> cuyo costo acumulado (alimento + salud) por kg ganado supera el umbral.
              </p>
            </div>
            <div class="d-flex gap-2">
              <button
                v-if="canNotify"
                type="button"
                class="btn btn-outline-secondary btn-sm"
                :disabled="sendingEmail || loading"
                @click="sendEmail"
              >
                {{ sendingEmail ? 'Enviando...' : 'Enviar alertas por correo' }}
              </button>
              <button class="btn btn-outline-secondary btn-sm" :disabled="loading" @click="load">Actualizar</button>
            </div>
          </div>

          <p v-if="report" class="small text-muted mb-3">
            Umbral: <strong>{{ money(report.max_cost_per_kg) }}/kg</strong> ·
            Mín. {{ report.min_weight_gain_kg }} kg ganados para evaluar
          </p>

          <div v-if="report?.alert_count === 0" class="alert alert-success">
            No hay animales activos por encima del umbral de costo/kg.
          </div>

          <div v-else-if="report" class="table-responsive">
            <table class="table table-hover table-sm">
              <thead>
                <tr>
                  <th>Arete</th>
                  <th>Lote</th>
                  <th class="text-end">Kg ganados</th>
                  <th class="text-end">Alimento</th>
                  <th class="text-end">Salud</th>
                  <th class="text-end">Total costos</th>
                  <th class="text-end">$/kg</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="a in report.alerts" :key="a.cattle_id" class="table-warning">
                  <td>
                    <router-link :to="{ name: 'ranch-animal-detail', params: { id: a.cattle_id } }">
                      {{ a.ear_tag }}
                    </router-link>
                  </td>
                  <td>{{ a.current_lot || '—' }}</td>
                  <td class="text-end">{{ a.weight_gain_kg }}</td>
                  <td class="text-end">{{ money(a.feed_cost) }}</td>
                  <td class="text-end">{{ money(a.health_cost) }}</td>
                  <td class="text-end">{{ money(a.total_cost) }}</td>
                  <td class="text-end fw-bold text-danger">{{ money(a.cost_per_kg_gained) }}</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 loading = ref(false);
const sendingEmail = ref(false);
const report = ref(null);

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

async function load() {
  loading.value = true;
  try {
    report.value = await RanchRepository.activeCostAlerts();
  } finally {
    loading.value = false;
  }
}

async function sendEmail() {
  sendingEmail.value = true;
  try {
    const result = await RanchRepository.sendCostAlertEmail({ force: true });
    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>
