<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">Proyección de cierre — lotes abiertos</h3>
              <p class="text-muted mb-0">
                Estima utilidad al cerrar hoy usando último pesaje o GDP ({{ report?.default_daily_gain_kg ?? '—' }} kg/día por defecto).
              </p>
            </div>
            <div v-if="report" 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 GDP por correo' }}
              </button>
              <button type="button" class="btn btn-outline-primary btn-sm" :disabled="loading" @click="exportCsv">
                Exportar CSV
              </button>
            </div>
          </div>

          <div v-if="report?.below_target_count > 0" class="alert alert-warning">
            <strong>{{ report.below_target_count }}</strong> lote(s) proyectan utilidad por debajo de la meta.
          </div>

          <div v-if="gdpAlerts?.lots_with_alerts_count > 0" class="alert alert-danger">
            <strong>{{ gdpAlerts.lots_with_alerts_count }}</strong> lote(s) con GDP bajo la meta o sin datos de pesaje.
          </div>

          <div v-if="report" class="row g-3 mb-4">
            <div class="col-md-4">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">Lotes abiertos</p>
                  <h4 class="mb-0">{{ report.lots_count }}</h4>
                </div>
              </div>
            </div>
            <div class="col-md-4">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">Bajo meta</p>
                  <h4 class="mb-0 text-warning">{{ report.below_target_count }}</h4>
                </div>
              </div>
            </div>
          </div>

          <p v-if="report && !report.lots_count" class="text-muted">No hay lotes de engorda abiertos.</p>

          <div class="table-responsive" v-if="report?.lots?.length">
            <table class="table table-hover table-sm">
              <thead>
                <tr>
                  <th>#</th>
                  <th>Lote</th>
                  <th class="text-end">Días</th>
                  <th class="text-end">Animales</th>
                  <th class="text-end">Alimento</th>
                  <th class="text-end">Utilidad proj.</th>
                  <th class="text-end">Meta</th>
                  <th class="text-end">Conv. proj.</th>
                  <th class="text-end">GDP prom.</th>
                  <th class="text-end">Bajo GDP</th>
                  <th>Base peso</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="lot in report.lots" :key="lot.lot_id" :class="rowClass(lot, gdpForLot(lot.lot_id))">
                  <td>{{ lot.rank }}</td>
                  <td>{{ lot.lot_name }}</td>
                  <td class="text-end">{{ lot.days_in_confinement }}</td>
                  <td class="text-end">{{ lot.animals_count }}</td>
                  <td class="text-end">{{ money(lot.projected_feed_cost) }}</td>
                  <td class="text-end fw-semibold">{{ money(lot.projected_net_profit) }}</td>
                  <td class="text-end">{{ lot.target_net_profit != null ? money(lot.target_net_profit) : '—' }}</td>
                  <td class="text-end">{{ lot.projected_feed_conversion ?? '—' }}</td>
                  <td class="text-end">{{ gdpForLot(lot.lot_id)?.avg_daily_weight_gain ?? '—' }}</td>
                  <td class="text-end">{{ gdpForLot(lot.lot_id)?.animals_below_gdp ?? 0 }}</td>
                  <td class="small">
                    <span class="badge bg-light text-dark">{{ lot.projection_basis?.weighed ?? 0 }} pesados</span>
                    <span class="badge bg-light text-dark">{{ lot.projection_basis?.gdp_estimate ?? 0 }} GDP</span>
                  </td>
                  <td>
                    <div class="d-flex gap-2 align-items-center">
                      <router-link
                        v-if="canWeigh"
                        :to="{ name: 'ranch-fattening-detail', params: { id: lot.lot_id }, query: { tab: 'pesajes' } }"
                        class="btn btn-sm btn-primary py-0 px-2"
                      >
                        Pesar
                      </router-link>
                      <router-link :to="{ name: 'ranch-fattening-detail', params: { id: lot.lot_id } }" class="btn btn-sm btn-link p-0">
                        Ver lote
                      </router-link>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="gdpAlerts?.animal_alerts?.length" class="mb-4">
            <h6>Animales con alerta de GDP en engorda</h6>
            <table class="table table-sm">
              <thead>
                <tr>
                  <th>Lote</th>
                  <th>Arete</th>
                  <th class="text-end">GDP</th>
                  <th>Alerta</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="a in gdpAlerts.animal_alerts" :key="a.cattle_id + '-' + a.lot_id">
                  <td>{{ a.lot_name }}</td>
                  <td>{{ a.ear_tag }}</td>
                  <td class="text-end">{{ a.daily_weight_gain ?? '—' }}</td>
                  <td class="small text-danger">{{ a.alert_message }}</td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-for="lot in report?.lots || []" :key="'d-' + lot.lot_id" class="card mb-3">
            <div class="card-header py-2 d-flex justify-content-between">
              <strong>{{ lot.lot_name }}</strong>
              <span v-if="lot.meets_target === false" class="badge bg-danger">Bajo meta</span>
              <span v-else-if="lot.meets_target === true" class="badge bg-success">Cumple meta</span>
            </div>
            <div class="card-body p-0">
              <table class="table table-sm mb-0">
                <thead>
                  <tr>
                    <th>Arete</th>
                    <th class="text-end">Entrada</th>
                    <th class="text-end">Días</th>
                    <th class="text-end">Salida proj.</th>
                    <th>Base</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="a in lot.animals" :key="a.cattle_id">
                    <td>{{ a.ear_tag }}</td>
                    <td class="text-end">{{ a.entry_weight_kg }} kg</td>
                    <td class="text-end">{{ a.days_in_lot }}</td>
                    <td class="text-end">{{ a.exit_weight_kg }} kg</td>
                    <td class="small text-muted">{{ a.basis_label }} ({{ a.daily_gain_used }} kg/d)</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

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

const { hasAnyPermission, hasPermission } = usePermissions();
const loading = ref(false);
const sendingEmail = ref(false);
const report = ref(null);
const gdpAlerts = ref(null);
const canWeigh = computed(() => hasPermission('ranch.weight.record'));
const canNotify = computed(() =>
  hasAnyPermission(['administracion.usuarios', 'ranch.reports.view', 'ranch.fattening.manage']),
);

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

function gdpForLot(lotId) {
  return gdpAlerts.value?.lots?.find((l) => l.lot_id === lotId);
}

function rowClass(lot, gdp) {
  if (lot.meets_target === false || gdp?.has_gdp_alert) return 'table-danger';
  if (lot.meets_target === true && !gdp?.has_gdp_alert) return 'table-success';
  return '';
}

async function load() {
  loading.value = true;
  try {
    const [projection, gdp] = await Promise.all([
      RanchRepository.openLotsProjection(),
      RanchRepository.openLotsGdpAlerts(),
    ]);
    report.value = projection;
    gdpAlerts.value = gdp;
  } finally {
    loading.value = false;
  }
}

async function exportCsv() {
  const blob = await RanchRepository.downloadOpenLotsProjectionCsv();
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'engorda-abierta-proyeccion.csv';
  a.click();
  URL.revokeObjectURL(url);
}

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