<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">Comparativo de lotes cerrados</h3>
              <p class="text-muted mb-0">
                Ranking por conversión alimenticia y utilidad. Ingreso proyectado = peso salida × $/kg del lote.
              </p>
            </div>
            <button v-if="report" type="button" class="btn btn-outline-primary btn-sm" :disabled="loading" @click="exportCsv">
              Exportar CSV
            </button>
          </div>

          <form class="row g-2 mb-4" @submit.prevent="load">
            <div class="col-md-3">
              <label class="form-label">Cierre desde</label>
              <input v-model="from" type="date" class="form-control" />
            </div>
            <div class="col-md-3">
              <label class="form-label">Cierre hasta</label>
              <input v-model="to" type="date" class="form-control" />
            </div>
            <div class="col-md-3">
              <label class="form-label">Ordenar por</label>
              <select v-model="sortBy" class="form-select">
                <option value="net_profit">Utilidad proyectada</option>
                <option value="feed_conversion">Conversión alimenticia</option>
                <option value="profit_per_kg">Utilidad / kg ganado</option>
              </select>
            </div>
            <div class="col-md-3 d-flex align-items-end">
              <button class="btn btn-primary w-100" :disabled="loading">Generar</button>
            </div>
          </form>

          <div v-if="report?.best" class="row g-3 mb-4">
            <div class="col-md-4" v-if="report.best.feed_conversion">
              <div class="card border-success h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">Mejor conversión (menor)</p>
                  <h6 class="mb-0">{{ report.best.feed_conversion.lot_name }}</h6>
                  <span class="text-success">{{ report.best.feed_conversion.feed_conversion_ratio ?? '—' }} kg alimento / kg carne</span>
                </div>
              </div>
            </div>
            <div class="col-md-4" v-if="report.best.net_profit">
              <div class="card border-primary h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">Mayor utilidad proyectada</p>
                  <h6 class="mb-0">{{ report.best.net_profit.lot_name }}</h6>
                  <span>{{ money(report.best.net_profit.net_profit) }}</span>
                </div>
              </div>
            </div>
            <div class="col-md-4" v-if="report.best.profit_per_kg">
              <div class="card border-info h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">Mejor utilidad / kg</p>
                  <h6 class="mb-0">{{ report.best.profit_per_kg.lot_name }}</h6>
                  <span>{{ money(report.best.profit_per_kg.profit_per_kg_gained) }}/kg</span>
                </div>
              </div>
            </div>
          </div>

          <p v-if="report && !report.lots_count" class="text-muted">No hay lotes cerrados en el periodo.</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>Cierre</th>
                  <th class="text-end">Días</th>
                  <th class="text-end">Animales</th>
                  <th class="text-end">Kg +</th>
                  <th class="text-end">Conversión</th>
                  <th class="text-end">Costos</th>
                  <th class="text-end">Ing. proyect.</th>
                  <th class="text-end">Utilidad</th>
                  <th class="text-end">$/kg</th>
                  <th></th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="lot in report.lots" :key="lot.lot_id" :class="rowClass(lot)">
                  <td>{{ lot.rank }}</td>
                  <td>{{ lot.lot_name }}</td>
                  <td>{{ lot.closed_at }}</td>
                  <td class="text-end">{{ lot.days_in_confinement }}</td>
                  <td class="text-end">{{ lot.animals_count }}</td>
                  <td class="text-end">{{ lot.total_weight_gain_kg }}</td>
                  <td class="text-end">{{ lot.feed_conversion_ratio ?? '—' }}</td>
                  <td class="text-end">{{ money(lot.total_cost) }}</td>
                  <td class="text-end">{{ money(lot.projected_income) }}</td>
                  <td class="text-end fw-semibold">{{ money(lot.net_profit) }}</td>
                  <td class="text-end">{{ lot.profit_per_kg_gained != null ? money(lot.profit_per_kg_gained) : '—' }}</td>
                  <td>
                    <router-link :to="{ name: 'ranch-fattening-detail', params: { id: lot.lot_id } }" class="btn btn-sm btn-link p-0">
                      Ver
                    </router-link>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="report?.rankings" class="row mt-4">
            <div class="col-md-4">
              <h6>Top conversión (menor = mejor)</h6>
              <ol class="small mb-0">
                <li v-for="(item, i) in report.rankings.by_feed_conversion.slice(0, 5)" :key="i">
                  {{ item.lot_name }} — {{ item.feed_conversion_ratio ?? '—' }}
                </li>
              </ol>
            </div>
            <div class="col-md-4">
              <h6>Top utilidad</h6>
              <ol class="small mb-0">
                <li v-for="(item, i) in report.rankings.by_net_profit.slice(0, 5)" :key="i">
                  {{ item.lot_name }} — {{ money(item.net_profit) }}
                </li>
              </ol>
            </div>
            <div class="col-md-4">
              <h6>Top utilidad / kg</h6>
              <ol class="small mb-0">
                <li v-for="(item, i) in report.rankings.by_profit_per_kg.slice(0, 5)" :key="i">
                  {{ item.lot_name }} — {{ item.profit_per_kg_gained != null ? money(item.profit_per_kg_gained) : '—' }}
                </li>
              </ol>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue';
import RanchRepository from '@/repositories/RanchRepository';

const loading = ref(false);
const report = ref(null);
const from = ref('');
const to = ref('');
const sortBy = ref('net_profit');

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

function rowClass(lot) {
  if (lot.met_target === true) return 'table-success';
  if (lot.met_target === false) return 'table-warning';
  return '';
}

function params() {
  return {
    from: from.value || undefined,
    to: to.value || undefined,
    sort_by: sortBy.value,
  };
}

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

async function exportCsv() {
  const blob = await RanchRepository.downloadClosedLotsRankingCsv(params());
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = `lotes-cerrados-${from.value || 'completo'}.csv`;
  a.click();
  URL.revokeObjectURL(url);
}

onMounted(load);
</script>
