<template>
  <div class="layout-px-spacing" v-if="sheet">
    <div class="row layout-top-spacing">
      <div class="col-12 layout-spacing">
        <div class="panel p-4">
          <router-link to="/ganaderia/animales" class="btn btn-link mb-2">← Volver al inventario</router-link>

          <div class="row g-3 mb-4 align-items-start">
            <div class="col-auto">
              <div class="cattle-photo-box">
                <img :src="photoDisplayUrl" :alt="'Foto ' + animalLabel" class="cattle-photo-img" />
              </div>
              <div v-if="canManage" class="mt-2 d-flex flex-column gap-1" style="width: 140px">
                <label class="btn btn-sm btn-outline-primary mb-0">
                  {{ uploadingPhoto ? 'Subiendo...' : 'Subir foto' }}
                  <input
                    type="file"
                    accept="image/jpeg,image/png,image/webp,image/gif"
                    class="d-none"
                    :disabled="uploadingPhoto"
                    @change="onPhotoSelected"
                  />
                </label>
                <button
                  v-if="sheet.animal.photo_url"
                  type="button"
                  class="btn btn-sm btn-outline-danger"
                  :disabled="uploadingPhoto"
                  @click="removePhoto"
                >
                  Quitar foto
                </button>
              </div>
            </div>
            <div class="col">
          <div class="d-flex justify-content-between align-items-start flex-wrap gap-2 mb-0">
            <div>
              <h3 class="mb-1">Expediente — {{ animalLabel }}</h3>
              <p class="text-muted mb-0">
                Hoja de vida · desarrollo · dinero invertido
                <span class="badge me-2" :class="statusClass(sheet.animal.status)">{{ statusLabel(sheet.animal.status) }}</span>
                {{ sheet.metrics.location_label }}
              </p>
            </div>
            <div class="d-flex gap-2 flex-wrap">
              <button
                type="button"
                class="btn btn-sm btn-outline-primary"
                :disabled="exportingPdf"
                @click="exportPdf"
              >
                {{ exportingPdf ? 'Generando PDF...' : 'Exportar expediente PDF' }}
              </button>
              <router-link
                v-if="sheet.animal.mother"
                :to="{ name: 'ranch-animal-detail', params: { id: sheet.animal.mother.id } }"
                class="btn btn-sm btn-outline-secondary"
              >
                Ver madre ({{ sheet.animal.mother.ear_tag }})
              </router-link>
              <router-link
                v-if="sheet.animal.gender === 'female' && sheet.animal.status === 'active'"
                :to="{ name: 'ranch-calvings', query: { mother: sheet.animal.ear_tag } }"
                class="btn btn-sm btn-outline-success"
              >
                Registrar parto
              </router-link>
            </div>
          </div>
            </div>
          </div>

          <div v-if="sheet.metrics.profitability" class="card border-0 shadow-sm mb-4">
            <div class="card-body">
              <h5 class="mb-3">Dinero invertido y resultado</h5>
              <div class="row g-3 mb-3">
                <div class="col-md-3">
                  <div class="border rounded p-3 h-100 bg-light">
                    <p class="text-muted small mb-1">Invertido (total)</p>
                    <h4 class="mb-0 text-primary">{{ money(sheet.metrics.profitability.money_invested) }}</h4>
                    <p class="small text-muted mb-0 mt-1">
                      Alimento {{ money(sheet.metrics.profitability.feed_cost) }} ·
                      Salud {{ money(sheet.metrics.profitability.health_cost) }}
                    </p>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="border rounded p-3 h-100">
                    <p class="text-muted small mb-1">Ingresos (venta)</p>
                    <h4 class="mb-0">{{ money(sheet.metrics.profitability.income) }}</h4>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="border rounded p-3 h-100">
                    <p class="text-muted small mb-1">Utilidad neta</p>
                    <h4
                      class="mb-0"
                      :class="sheet.metrics.profitability.net_profit >= 0 ? 'text-success' : 'text-danger'"
                    >
                      {{ money(sheet.metrics.profitability.net_profit) }}
                    </h4>
                    <p v-if="sheet.metrics.profitability.margin_pct != null" class="small text-muted mb-0">
                      Margen {{ sheet.metrics.profitability.margin_pct }}%
                    </p>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="border rounded p-3 h-100">
                    <p class="text-muted small mb-1">Eficiencia</p>
                    <p class="mb-0 small">
                      {{ sheet.metrics.profitability.weight_gain_kg ?? '—' }} kg ganados
                    </p>
                    <p class="mb-0 small">
                      Costo/kg: {{ sheet.metrics.profitability.cost_per_kg_gained != null ? money(sheet.metrics.profitability.cost_per_kg_gained) : '—' }}
                    </p>
                    <p class="mb-0 small">
                      Utilidad/kg: {{ sheet.metrics.profitability.profit_per_kg_gained != null ? money(sheet.metrics.profitability.profit_per_kg_gained) : '—' }}
                    </p>
                  </div>
                </div>
              </div>
              <div v-if="investmentChartOptions" class="mt-2">
                <p class="text-muted small mb-2">Desglose actual (totales)</p>
                <apexchart type="bar" height="120" :options="investmentChartOptions" :series="investmentChartSeries" />
              </div>

              <div v-if="hasInvestmentTimeline" class="mt-4">
                <p class="text-muted small mb-2">Inversión acumulada en el tiempo</p>
                <p class="text-muted small mb-2">
                  Cada gasto de alimento del lote se reparte entre los animales que estaban en engorda esa fecha.
                </p>
                <apexchart
                  type="area"
                  height="300"
                  :options="investmentTimelineOptions"
                  :series="investmentTimelineSeries"
                />
              </div>
              <p v-else-if="sheet.metrics.investment_timeline" class="small text-muted mb-0 mt-3">
                Aún no hay gastos con fecha para mostrar la curva de inversión (registra gastos de lote o eventos de salud).
              </p>

              <div v-if="investmentEvents.length" class="mt-3">
                <h6 class="small text-muted mb-2">Últimos movimientos</h6>
                <table class="table table-sm mb-0">
                  <thead>
                    <tr>
                      <th>Fecha</th>
                      <th>Concepto</th>
                      <th class="text-end">Monto</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="(ev, idx) in investmentEvents" :key="idx">
                      <td>{{ ev.date }}</td>
                      <td>{{ ev.label }}</td>
                      <td class="text-end" :class="ev.category === 'income' ? 'text-success' : ''">
                        {{ ev.category === 'income' ? '+' : '' }}{{ money(ev.amount) }}
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <div v-if="!hasDevelopmentChart && developmentPoints.length === 1" class="alert alert-info mb-4">
            Hay un solo pesaje; registra al menos otro para ver la gráfica de desarrollo.
          </div>

          <div v-if="hasDevelopmentChart" class="card border-0 shadow-sm mb-4">
            <div class="card-body">
              <h5 class="mb-1">Gráfica de desarrollo</h5>
              <p class="text-muted small mb-3">
                Evolución de peso (kg) y GDP por periodo entre pesajes.
                Meta GDP: {{ sheet.metrics.development_chart?.target_min_gdp_kg_per_day ?? sheet.metrics.effective_min_gdp_kg_per_day }} kg/día
              </p>
              <apexchart type="line" height="320" :options="weightChartOptions" :series="weightChartSeries" />
            </div>
          </div>

          <div class="row g-3 mb-4">
            <div class="col-md-3" v-for="kpi in kpis" :key="kpi.label">
              <div class="card border-0 shadow-sm h-100">
                <div class="card-body py-3">
                  <p class="text-muted small mb-1">{{ kpi.label }}</p>
                  <h5 class="mb-0">{{ kpi.value }}</h5>
                </div>
              </div>
            </div>
          </div>

          <div class="row mb-4">
            <div class="col-lg-6">
              <h5>Datos generales</h5>
              <ul class="list-group">
                <li class="list-group-item">
                  Arete:
                  <strong>{{ animalLabel }}</strong>
                  <span v-if="!sheet.animal.ear_tag" class="badge bg-warning text-dark ms-2">Pendiente</span>
                </li>
                <li class="list-group-item">Raza: {{ sheet.animal.breed || '—' }}</li>
                <li class="list-group-item">Género: {{ sheet.animal.gender === 'female' ? 'Hembra' : 'Macho' }}</li>
                <li class="list-group-item">Nacimiento: {{ sheet.animal.birth_date || '—' }}</li>
                <li class="list-group-item">Edad: {{ sheet.metrics.age_months != null ? sheet.metrics.age_months + ' meses' : '—' }}</li>
                <li class="list-group-item">Madre: {{ sheet.animal.mother?.ear_tag || '—' }}</li>
                <li class="list-group-item">Notas: {{ sheet.animal.notes || '—' }}</li>
                <li class="list-group-item">
                  Meta GDP:
                  {{ sheet.metrics.effective_min_gdp_kg_per_day }} kg/día
                  <span class="text-muted small">({{ gdpTargetLabel(sheet.metrics.gdp_target_source) }})</span>
                </li>
              </ul>

              <form
                v-if="canManage && sheet.animal.status === 'active' && !sheet.animal.ear_tag"
                class="card card-body mt-3 border-warning"
                @submit.prevent="assignEarTag"
              >
                <h6 class="mb-2">Asignar arete</h6>
                <p class="small text-muted mb-2">Este becerro nació sin arete. Puedes colocarlo ahora.</p>
                <div class="row g-2">
                  <div class="col-md-6">
                    <input v-model="editEarTag" class="form-control" placeholder="Número de arete" required />
                  </div>
                  <div class="col-md-4">
                    <button class="btn btn-warning w-100" type="submit" :disabled="saving">Guardar arete</button>
                  </div>
                </div>
              </form>
            </div>
            <div class="col-lg-6" v-if="sheet.animal.status === 'active' && canManage">
              <div class="d-flex justify-content-between align-items-center mb-2">
                <h5 class="mb-0">Ubicación (activo)</h5>
                <router-link
                  :to="{ name: 'ranch-location-movements', query: { ear_tag: sheet.animal.ear_tag } }"
                  class="btn btn-sm btn-outline-secondary"
                >
                  Mover / historial
                </router-link>
              </div>
              <form @submit.prevent="saveLocation" class="card card-body">
                <label class="form-label">Potrero / corral</label>
                <select v-model="editPastureId" class="form-select mb-2">
                  <option :value="null">Sin asignar</option>
                  <option v-for="p in pastures" :key="p.id" :value="p.id">{{ p.name }}</option>
                </select>
                <label class="form-label">Meta GDP (kg/día)</label>
                <input
                  v-model.number="editTargetGdp"
                  type="number"
                  step="0.01"
                  min="0"
                  class="form-control mb-1"
                  :placeholder="`Vacío = lote o ${defaultMinGdp} por defecto`"
                />
                <p class="small text-muted mb-2">
                  Efectiva hoy: {{ sheet.metrics.effective_min_gdp_kg_per_day }} kg/día
                </p>
                <label class="form-label">Notas</label>
                <textarea v-model="editNotes" class="form-control mb-2" rows="2" />
                <button type="submit" class="btn btn-primary btn-sm" :disabled="saving">Guardar</button>
              </form>
            </div>
            <div class="col-lg-6" v-else-if="sheet.animal.status !== 'active'">
              <h5>Baja / venta</h5>
              <ul class="list-group">
                <li class="list-group-item">Fecha baja: {{ sheet.animal.deactivated_at || '—' }}</li>
                <li class="list-group-item">Peso salida: {{ sheet.animal.exit_weight_kg ?? '—' }} kg</li>
                <li v-if="sheet.animal.status === 'sold'" class="list-group-item">
                  Venta: {{ money(sheet.animal.sale_total_price) }}
                  <span v-if="sheet.animal.sale_price_per_kg"> ({{ sheet.animal.sale_price_per_kg }}/kg)</span>
                </li>
                <li v-if="sheet.animal.death_cause" class="list-group-item">Causa: {{ sheet.animal.death_cause }}</li>
              </ul>
              <div v-if="sheet.closure_summary" class="mt-2 small text-muted">
                Engorda: {{ sheet.closure_summary.total_days_in_fattening }} días ·
                Alimento asignado: {{ money(sheet.closure_summary.total_allocated_feed_cost) }}
              </div>
            </div>
          </div>

          <h5 class="mt-2">Historial de salud</h5>
          <p v-if="!sheet.health_events?.length" class="text-muted">Sin eventos de salud.</p>
          <table v-else class="table table-sm mb-4">
            <thead>
              <tr><th>Fecha</th><th>Tipo</th><th>Concepto</th><th>Resultado</th><th>Costo</th><th>En balance</th></tr>
            </thead>
            <tbody>
              <tr v-for="h in sheet.health_events" :key="h.id">
                <td>{{ h.event_date }}</td>
                <td>{{ healthTypeLabel(h.event_type) }}</td>
                <td>{{ h.title }}</td>
                <td>{{ healthOutcomeLabel(h.outcome) }}</td>
                <td>{{ h.cost != null ? money(h.cost) : '—' }}</td>
                <td>
                  <span v-if="h.expense_recorded" class="text-success small">✓ Gasto registrado</span>
                  <span v-else class="text-muted small">—</span>
                </td>
              </tr>
            </tbody>
          </table>

          <div v-if="sheet.offspring_performance" class="mb-4">
            <h5>Rendimiento como madre</h5>
            <div class="alert alert-light border">
              {{ sheet.offspring_performance.offspring_count }} crías ·
              {{ sheet.offspring_performance.offspring_active }} activas ·
              Mortalidad progenie: {{ sheet.offspring_performance.mortality_rate_pct }}% ·
              Enfermedades en crías: {{ sheet.offspring_performance.offspring_illness_events }}
              <span v-if="sheet.offspring_performance.health_risk" class="badge bg-danger ms-1">Riesgo salud</span>
              · Peso prom.: {{ sheet.offspring_performance.avg_offspring_weight_kg ?? '—' }} kg
              <router-link to="/ganaderia/vacas-madre" class="ms-2">Ver ranking vacas</router-link>
            </div>
            <table v-if="sheet.offspring.length" class="table table-sm">
              <thead>
                <tr><th>Arete cría</th><th>Estatus</th><th>Peso ref.</th><th></th></tr>
              </thead>
              <tbody>
                <tr v-for="c in sheet.offspring" :key="c.id">
                  <td>{{ c.ear_tag }}</td>
                  <td>{{ statusLabel(c.status) }}</td>
                  <td>{{ c.exit_weight_kg ?? '—' }}</td>
                  <td>
                    <router-link :to="{ name: 'ranch-animal-detail', params: { id: c.id } }">Ver</router-link>
                  </td>
                </tr>
              </tbody>
            </table>
            <h6 v-if="sheet.calving_events?.length" class="mt-3">Partos registrados</h6>
            <table v-if="sheet.calving_events?.length" class="table table-sm">
              <thead>
                <tr><th>Fecha</th><th>Cría</th><th>Peso nacer</th><th></th></tr>
              </thead>
              <tbody>
                <tr v-for="ev in sheet.calving_events" :key="ev.id">
                  <td>{{ ev.calving_date }}</td>
                  <td>{{ ev.calf?.ear_tag }}</td>
                  <td>{{ ev.birth_weight_kg ?? '—' }}</td>
                  <td>
                    <router-link v-if="ev.calf" :to="{ name: 'ranch-animal-detail', params: { id: ev.calf.id } }">Ver</router-link>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <h5>Historial de ubicación</h5>
          <p v-if="!sheet.location_movements?.length" class="text-muted">Sin movimientos registrados.</p>
          <table v-else class="table table-sm mb-4">
            <thead>
              <tr>
                <th>Fecha</th>
                <th>Motivo</th>
                <th>Desde</th>
                <th>Hacia</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="m in sheet.location_movements" :key="m.id">
                <td>{{ m.moved_at }}</td>
                <td>{{ m.reason_label }}</td>
                <td>{{ m.from_type_label }}{{ m.from_label ? ': ' + m.from_label : '' }}</td>
                <td>{{ m.to_type_label }}{{ m.to_label ? ': ' + m.to_label : '' }}</td>
              </tr>
            </tbody>
          </table>

          <h5>Historial de engorda</h5>
          <p v-if="!sheet.fattening_stints.length" class="text-muted">Sin registros en lotes de engorda.</p>
          <table v-else class="table table-sm mb-4">
            <thead>
              <tr>
                <th>Lote</th>
                <th>Entrada</th>
                <th>Salida</th>
                <th>Días</th>
                <th>Peso inicio</th>
                <th>Peso fin</th>
                <th>Ganancia</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(s, i) in sheet.fattening_stints" :key="i">
                <td>
                  {{ s.lot_name }}
                  <span v-if="s.is_active" class="badge bg-primary ms-1">Actual</span>
                </td>
                <td>{{ s.entry_date }}</td>
                <td>{{ s.exit_date || '—' }}</td>
                <td>{{ s.days_in_confinement }}</td>
                <td>{{ s.entry_weight_kg }}</td>
                <td>{{ s.exit_weight_kg ?? '—' }}</td>
                <td>{{ s.weight_gain_kg ?? '—' }}</td>
              </tr>
            </tbody>
          </table>

          <h5>Historial de pesajes</h5>
          <p v-if="!sheet.weight_records.length" class="text-muted">Sin pesajes.</p>
          <table v-else class="table table-sm">
            <thead>
              <tr>
                <th>Fecha</th>
                <th>Kg</th>
                <th>Ganancia</th>
                <th>GDP (kg/día)</th>
                <th>Notas</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="w in sheet.weight_records" :key="w.id">
                <td>{{ w.weighed_at }}</td>
                <td>{{ w.weight_kg }}</td>
                <td>{{ w.weight_gain_kg ?? '—' }}</td>
                <td>{{ w.daily_weight_gain ?? '—' }}</td>
                <td class="small text-muted">{{ w.notes || '' }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
  <p v-else class="p-4 text-muted">Cargando hoja de vida...</p>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import { useRoute } from 'vue-router';
import apexchart from 'vue3-apexcharts';
import RanchRepository from '@/repositories/RanchRepository';
import { usePermissions } from '@/composables/use-permissions';
import Swal from 'sweetalert2';
import defaultCattleImg from '@/assets/images/user-avtar.svg';

const route = useRoute();
const { hasPermission } = usePermissions();
const sheet = ref(null);
const saving = ref(false);
const exportingPdf = ref(false);
const uploadingPhoto = ref(false);

const photoDisplayUrl = computed(() => sheet.value?.animal?.photo_url || defaultCattleImg);
const animalLabel = computed(() =>
  sheet.value?.animal?.display_ear_tag
  || sheet.value?.animal?.ear_tag
  || (sheet.value?.animal?.id ? `Sin arete · #${sheet.value.animal.id}` : 'Sin arete'),
);
const pastures = ref([]);
const editPastureId = ref(null);
const editNotes = ref('');
const editTargetGdp = ref(null);
const editEarTag = ref('');
const defaultMinGdp = ref(0.5);

const canManage = computed(() => hasPermission('ranch.cattle.manage'));

const kpis = computed(() => {
  if (!sheet.value) return [];
  const m = sheet.value.metrics;
  const p = m.profitability;
  return [
    { label: 'Último peso', value: m.last_weight_kg != null ? `${m.last_weight_kg} kg` : '—' },
    { label: 'Último GDP', value: m.last_daily_weight_gain != null ? `${m.last_daily_weight_gain} kg/d` : '—' },
    { label: 'Invertido', value: p ? money(p.money_invested) : '—' },
    { label: 'Ganancia peso', value: m.lifetime_weight_gain_kg != null ? `${m.lifetime_weight_gain_kg} kg` : '—' },
  ];
});

const developmentPoints = computed(() => {
  const pts = sheet.value?.metrics?.development_chart?.points;
  if (pts?.length) return pts;
  const records = sheet.value?.weight_records || [];
  return [...records]
    .sort((a, b) => String(a.weighed_at).localeCompare(String(b.weighed_at)))
    .map((w) => ({
      date: w.weighed_at,
      weight_kg: w.weight_kg,
      daily_weight_gain: w.daily_weight_gain,
    }));
});

const hasDevelopmentChart = computed(() => developmentPoints.value.length >= 2);

const weightChartSeries = computed(() => {
  const gdp = developmentPoints.value.map((p) => p.daily_weight_gain);
  const hasGdp = gdp.some((v) => v != null);
  const series = [
    { name: 'Peso (kg)', type: 'line', data: developmentPoints.value.map((p) => p.weight_kg) },
  ];
  if (hasGdp) {
    series.push({
      name: 'GDP (kg/día)',
      type: 'line',
      data: gdp.map((v) => (v != null ? v : null)),
      yAxisIndex: 1,
    });
    const target = sheet.value?.metrics?.development_chart?.target_min_gdp_kg_per_day
      ?? sheet.value?.metrics?.effective_min_gdp_kg_per_day;
    if (target != null) {
      series.push({
        name: 'Meta GDP',
        type: 'line',
        data: developmentPoints.value.map(() => target),
        yAxisIndex: 1,
      });
    }
  }
  return series;
});

const weightChartOptions = computed(() => ({
  chart: { toolbar: { show: false }, zoom: { enabled: false } },
  stroke: { width: [3, 2, 2], dashArray: [0, 0, 6] },
  colors: ['#4361ee', '#00ab55', '#e7515a'],
  xaxis: {
    categories: developmentPoints.value.map((p) => p.date),
    labels: { rotate: -35 },
  },
  yaxis: [
    { title: { text: 'Peso (kg)' }, decimalsInFloat: 1 },
    {
      opposite: true,
      title: { text: 'GDP (kg/día)' },
      decimalsInFloat: 2,
      min: 0,
    },
  ],
  tooltip: { shared: true, intersect: false },
  legend: { position: 'top' },
  markers: { size: 4 },
}));

const investmentChartSeries = computed(() => {
  const p = sheet.value?.metrics?.profitability;
  if (!p) return [];
  return [{ name: 'MXN', data: [p.feed_cost || 0, p.health_cost || 0] }];
});

const investmentChartOptions = computed(() => {
  const p = sheet.value?.metrics?.profitability;
  if (!p) return null;
  return {
    chart: { toolbar: { show: false } },
    plotOptions: { bar: { horizontal: true, distributed: true } },
    colors: ['#4361ee', '#e2a03f'],
    xaxis: { categories: ['Alimento', 'Salud'] },
    dataLabels: { enabled: false },
    tooltip: {
      y: { formatter: (v) => money(v) },
    },
  };
});

const investmentTimeline = computed(() => sheet.value?.metrics?.investment_timeline);

const hasInvestmentTimeline = computed(
  () => investmentTimeline.value?.has_data && (investmentTimeline.value?.series?.length ?? 0) > 0,
);

const investmentEvents = computed(() => {
  const events = investmentTimeline.value?.events ?? [];
  return [...events].slice(-8).reverse();
});

const investmentTimelineSeries = computed(() => {
  const points = investmentTimeline.value?.series ?? [];
  const series = [
    {
      name: 'Inversión acumulada',
      type: 'area',
      data: points.map((p) => p.cumulative_invested),
    },
    {
      name: 'Alimento (acum.)',
      type: 'line',
      data: points.map((p) => p.cumulative_feed),
    },
    {
      name: 'Salud (acum.)',
      type: 'line',
      data: points.map((p) => p.cumulative_health),
    },
  ];
  if (points.some((p) => p.cumulative_income > 0)) {
    series.push({
      name: 'Ingresos (acum.)',
      type: 'line',
      data: points.map((p) => p.cumulative_income),
    });
    series.push({
      name: 'Resultado neto',
      type: 'line',
      data: points.map((p) => p.cumulative_net),
    });
  }
  return series;
});

const investmentTimelineOptions = computed(() => ({
  chart: { toolbar: { show: false }, zoom: { enabled: true } },
  stroke: { width: [2, 1, 1, 2, 2], curve: 'smooth' },
  fill: {
    type: ['gradient', 'solid', 'solid', 'solid', 'solid'],
    opacity: [0.4, 1, 1, 1, 1],
  },
  colors: ['#4361ee', '#805dca', '#e2a03f', '#00ab55', '#1abc9c'],
  xaxis: {
    categories: (investmentTimeline.value?.series ?? []).map((p) => p.date),
    labels: { rotate: -35 },
  },
  yaxis: {
    labels: {
      formatter: (v) => money(v),
    },
  },
  tooltip: {
    shared: true,
    y: { formatter: (v) => money(v) },
  },
  legend: { position: 'top' },
  markers: { size: 3 },
}));

function statusLabel(s) {
  const map = { active: 'Activo', sold: 'Vendido', dead: 'Muerto', consumed: 'Consumido' };
  return map[s] || s;
}

function statusClass(s) {
  const map = { active: 'bg-success', sold: 'bg-primary', dead: 'bg-dark', consumed: 'bg-secondary' };
  return map[s] || 'bg-secondary';
}

function money(n) {
  if (n == null) return '—';
  return new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n);
}

const healthTypes = {
  vaccination: 'Vacunación',
  deworming: 'Desparasitación',
  illness: 'Enfermedad',
  treatment: 'Tratamiento',
  checkup: 'Revisión',
};

const healthOutcomes = {
  recovered: 'Recuperado',
  ongoing: 'En tratamiento',
  fatal: 'Falleció',
};

function healthTypeLabel(t) {
  return healthTypes[t] || t;
}

function healthOutcomeLabel(o) {
  if (!o) return '—';
  return healthOutcomes[o] || o;
}

function gdpTargetLabel(source) {
  const map = { animal: 'meta del animal', lot: 'meta del lote', default: 'valor por defecto' };
  return map[source] || source;
}

async function load() {
  sheet.value = await RanchRepository.getCattle(route.params.id);
  editPastureId.value = sheet.value.animal.pasture_id ?? null;
  editNotes.value = sheet.value.animal.notes || '';
  editTargetGdp.value = sheet.value.animal.target_min_gdp_kg_per_day ?? null;
  editEarTag.value = sheet.value.animal.ear_tag || '';
}

async function assignEarTag() {
  const tag = editEarTag.value.trim();
  if (!tag) {
    Swal.fire({ icon: 'warning', title: 'Indica el número de arete' });
    return;
  }
  saving.value = true;
  try {
    sheet.value = await RanchRepository.updateCattle(route.params.id, { ear_tag: tag });
    Swal.fire({ icon: 'success', title: 'Arete asignado', timer: 1500, showConfirmButton: false });
  } catch (e) {
    Swal.fire({ icon: 'error', text: e.response?.data?.message || 'No se pudo asignar el arete' });
  } finally {
    saving.value = false;
  }
}

async function onPhotoSelected(event) {
  const file = event.target.files?.[0];
  if (!file) return;
  if (file.size > 3 * 1024 * 1024) {
    Swal.fire({ icon: 'warning', title: 'La imagen no debe superar 3 MB' });
    event.target.value = '';
    return;
  }
  uploadingPhoto.value = true;
  try {
    const result = await RanchRepository.uploadCattlePhoto(route.params.id, file);
    sheet.value.animal.photo_url = result.photo_url;
    Swal.fire({ icon: 'success', title: 'Foto guardada', timer: 1200, showConfirmButton: false });
  } catch (e) {
    Swal.fire({ icon: 'error', title: 'No se pudo subir la foto', text: e.response?.data?.message });
  } finally {
    uploadingPhoto.value = false;
    event.target.value = '';
  }
}

async function removePhoto() {
  const confirm = await Swal.fire({
    icon: 'question',
    title: '¿Quitar la foto?',
    showCancelButton: true,
    confirmButtonText: 'Quitar',
  });
  if (!confirm.isConfirmed) return;
  uploadingPhoto.value = true;
  try {
    await RanchRepository.deleteCattlePhoto(route.params.id);
    sheet.value.animal.photo_url = null;
    Swal.fire({ icon: 'success', title: 'Foto eliminada', timer: 1200, showConfirmButton: false });
  } catch {
    Swal.fire({ icon: 'error', title: 'No se pudo eliminar la foto' });
  } finally {
    uploadingPhoto.value = false;
  }
}

async function exportPdf() {
  exportingPdf.value = true;
  try {
    const blob = await RanchRepository.downloadCattleExpedientePdf(route.params.id);
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `expediente-${sheet.value.animal.ear_tag || sheet.value.animal.id}.pdf`;
    a.click();
    URL.revokeObjectURL(url);
  } catch {
    Swal.fire({ icon: 'error', title: 'No se pudo generar el PDF' });
  } finally {
    exportingPdf.value = false;
  }
}

async function saveLocation() {
  saving.value = true;
  try {
    sheet.value = await RanchRepository.updateCattle(route.params.id, {
      pasture_id: editPastureId.value || null,
      notes: editNotes.value || null,
      target_min_gdp_kg_per_day: editTargetGdp.value === '' || editTargetGdp.value == null
        ? null
        : editTargetGdp.value,
    });
    Swal.fire({ icon: 'success', title: 'Ubicación actualizada', timer: 1500, showConfirmButton: false });
  } catch (e) {
    Swal.fire({ icon: 'error', text: e.response?.data?.message || 'Error al guardar' });
  } finally {
    saving.value = false;
  }
}

onMounted(async () => {
  const catalog = await RanchRepository.catalog();
  pastures.value = catalog.pastures || [];
  defaultMinGdp.value = catalog.default_min_gdp_kg_per_day ?? 0.5;
  await load();
});
</script>

<style scoped>
.cattle-photo-box {
  width: 140px;
  height: 140px;
  border-radius: 12px;
  overflow: hidden;
  border: 2px solid #e0e6ed;
  background: #f8f9fa;
}
.cattle-photo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>
