<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 mb-3 flex-wrap gap-2">
            <div>
              <h3 class="mb-1">Compras e insumos</h3>
              <p class="text-muted small mb-0">
                {{ activeTab === 'feed'
                  ? 'Compras de alimento al inventario.'
                  : 'Gastos de vacunación, medicamentos y salud animal.' }}
              </p>
            </div>
            <button v-if="activeTab === 'feed'" class="btn btn-primary btn-sm" type="button" @click="openCreate">Registrar compra</button>
          </div>

          <ul class="nav nav-tabs mb-3">
            <li class="nav-item">
              <button type="button" class="nav-link" :class="{ active: activeTab === 'feed' }" @click="switchTab('feed')">Alimento</button>
            </li>
            <li class="nav-item">
              <button type="button" class="nav-link" :class="{ active: activeTab === 'health' }" @click="switchTab('health')">Vacunación / salud</button>
            </li>
          </ul>

          <ul v-if="activeTab === 'health'" class="nav nav-pills mb-3 gap-1">
            <li class="nav-item">
              <button type="button" class="nav-link py-1 px-3" :class="{ active: healthMode === 'applications' }" @click="setHealthMode('applications')">
                Aplicaciones al lote
              </button>
            </li>
            <li class="nav-item">
              <button type="button" class="nav-link py-1 px-3" :class="{ active: healthMode === 'purchases' }" @click="setHealthMode('purchases')">
                Compra de frascos
              </button>
            </li>
            <li class="nav-item">
              <button type="button" class="nav-link py-1 px-3" :class="{ active: healthMode === 'all' }" @click="setHealthMode('all')">
                Todo
              </button>
            </li>
          </ul>

          <div class="row g-2 mb-3">
            <div class="col-md-3">
              <label class="form-label small mb-1">Desde</label>
              <input v-model="filters.from" type="date" class="form-control form-control-sm" />
            </div>
            <div class="col-md-3">
              <label class="form-label small mb-1">Hasta</label>
              <input v-model="filters.to" type="date" class="form-control form-control-sm" />
            </div>
            <div class="col-md-4">
              <label class="form-label small mb-1">Producto</label>
              <select v-model="filters.material_type_id" class="form-select form-select-sm">
                <option value="">Todos los productos</option>
                <option v-for="m in catalogMaterials" :key="m.id" :value="String(m.id)">{{ m.name }}</option>
              </select>
            </div>
            <div class="col-md-2 d-flex align-items-end gap-2">
              <button class="btn btn-outline-secondary btn-sm w-100" type="button" @click="load">Filtrar</button>
            </div>
          </div>

          <div v-if="summary.total > 0" class="alert alert-light border mb-3 py-2">
            <strong>{{ summary.count }}</strong> {{ activeTab === 'feed' ? 'compras' : 'registros' }} ·
            Total filtrado: <strong>{{ formatMoney(summary.total) }}</strong>
          </div>

          <div v-if="!groupedByDate.length" class="text-muted text-center py-4">
            No hay registros con los filtros actuales.
          </div>

          <div v-for="group in groupedByDate" :key="group.date" class="purchase-date-group mb-4">
            <div class="purchase-date-header d-flex justify-content-between align-items-center flex-wrap gap-2">
              <h6 class="mb-0">{{ formatRanchDate(group.date) }}</h6>
              <span class="small text-muted">
                {{ group.items.length }} {{ group.items.length === 1 ? 'registro' : 'registros' }} ·
                Subtotal: <strong class="text-body">{{ formatMoney(group.total) }}</strong>
              </span>
            </div>

            <div class="table-responsive">
              <table class="table table-sm table-hover align-middle mb-0">
                <thead>
                  <tr>
                    <th>Producto</th>
                    <th class="text-end" v-if="activeTab === 'feed'">Bultos</th>
                    <th class="text-end">Cantidad</th>
                    <th class="text-end">$/u</th>
                    <th class="text-end">Total</th>
                    <th v-if="activeTab === 'health'">Lote</th>
                    <th>Notas</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="e in group.items" :key="e.id">
                    <td>{{ e.material_type?.name || '—' }}</td>
                    <td class="text-end" v-if="activeTab === 'feed'">{{ e.bundle_count ?? '—' }}</td>
                    <td class="text-end">{{ formatQuantity(e.quantity, e.material_type?.unit) }}</td>
                    <td class="text-end">{{ formatMoney(e.unit_cost) }}</td>
                    <td class="text-end fw-semibold">{{ formatMoney(e.total_cost) }}</td>
                    <td v-if="activeTab === 'health'">{{ e.fattening_lot?.name || '—' }}</td>
                    <td class="small text-muted">{{ e.notes || '—' }}</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <AppModal v-model="showForm" title="Registrar compra" size="md" :busy="saving">
            <form id="purchase-form" class="row g-2" @submit.prevent="save">
              <div class="col-12">
                <label class="form-label">Producto</label>
                <select v-model="form.material_type_id" class="form-select" required @change="onMaterialSelected">
                  <option v-for="m in feedMaterials" :key="m.id" :value="m.id">{{ m.name }}</option>
                </select>
              </div>
              <div class="col-md-6">
                <label class="form-label">Fecha de compra</label>
                <input v-model="form.expense_date" type="date" class="form-control" required />
              </div>
              <div class="col-md-6">
                <label class="form-label">Bultos (opcional)</label>
                <input v-model.number="form.bundle_count" type="number" min="1" class="form-control" placeholder="Ej. 2" />
              </div>
              <div class="col-md-4">
                <label class="form-label">Cantidad</label>
                <input v-model.number="form.quantity" type="number" step="0.001" min="0.001" class="form-control" required />
              </div>
              <div class="col-md-4">
                <label class="form-label">Unidad</label>
                <input :value="selectedUnit" class="form-control" disabled />
              </div>
              <div class="col-md-4">
                <label class="form-label">Precio unitario</label>
                <input v-model.number="form.unit_cost" type="number" step="0.01" min="0" class="form-control" required />
              </div>
              <div class="col-12">
                <label class="form-label">Notas (opcional)</label>
                <input v-model="form.notes" class="form-control" placeholder="Ej. 2 bultos de 20 kg" />
              </div>
              <div class="col-12">
                <p class="small text-muted mb-0">Total compra: <strong>{{ formatMoney(totalPreview) }}</strong> · Se suma al inventario.</p>
              </div>
            </form>
            <template #footer="{ close }">
              <button type="button" class="btn btn-outline-secondary" :disabled="saving" @click="close">Cancelar</button>
              <button type="submit" form="purchase-form" class="btn btn-primary" :disabled="saving">
                {{ saving ? 'Guardando…' : 'Registrar compra' }}
              </button>
            </template>
          </AppModal>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import RanchRepository from '@/repositories/RanchRepository';
import Swal from 'sweetalert2';
import AppModal from '@/components/ui/AppModal.vue';
import { formatMoney, formatQuantity, formatRanchDate } from '@/utils/ranchFormat';

const feedMaterials = ref([]);
const healthMaterials = ref([]);
const activeTab = ref('feed');
const healthMode = ref('applications');
const expenses = ref([]);
const showForm = ref(false);
const saving = ref(false);
const summary = ref({ count: 0, total: 0 });
const filters = ref({
  from: '',
  to: '',
  material_type_id: '',
});
const form = ref({
  material_type_id: null,
  expense_date: new Date().toISOString().slice(0, 10),
  bundle_count: null,
  quantity: 1,
  unit_cost: 0,
  notes: '',
  adds_to_inventory: true,
});

const totalPreview = computed(() => ((form.value.quantity || 0) * (form.value.unit_cost || 0)).toFixed(2));

const selectedUnit = computed(() => {
  const m = feedMaterials.value.find((x) => x.id === form.value.material_type_id);
  return m?.unit || 'kg';
});

function onMaterialSelected() {
  const m = feedMaterials.value.find((x) => x.id === form.value.material_type_id);
  if (m?.default_unit_price != null && !form.value.unit_cost) {
    form.value.unit_cost = Number(m.default_unit_price);
  }
}

function resetForm() {
  form.value = {
    material_type_id: feedMaterials.value.length ? feedMaterials.value[0].id : null,
    expense_date: new Date().toISOString().slice(0, 10),
    bundle_count: null,
    quantity: 1,
    unit_cost: feedMaterials.value[0]?.default_unit_price != null
      ? Number(feedMaterials.value[0].default_unit_price)
      : 0,
    notes: '',
    adds_to_inventory: true,
  };
}

function openCreate() {
  resetForm();
  showForm.value = true;
}

const catalogMaterials = computed(() => (activeTab.value === 'health' ? healthMaterials.value : feedMaterials.value));

function currentScope() {
  if (activeTab.value === 'feed') return 'feed_purchases';
  if (healthMode.value === 'purchases') return 'health_purchases';
  if (healthMode.value === 'all') return 'health_all';
  return 'health_applications';
}

function matchesScope(expense, scope) {
  const category = expense.material_type?.category;
  const isRation = Boolean(expense.fattening_lot_feed_intake_item_id);
  const addsInventory = Boolean(expense.adds_to_inventory);

  if (isRation) return false;

  switch (scope) {
    case 'feed_purchases':
      return category === 'feed_supplements' && addsInventory;
    case 'health_applications':
      return category === 'animal_health' && !addsInventory;
    case 'health_purchases':
      return category === 'animal_health' && addsInventory;
    case 'health_all':
      return category === 'animal_health';
    default:
      return true;
  }
}

function expenseDateKey(expense) {
  const raw = expense?.expense_date;
  if (!raw) return '';
  if (typeof raw === 'object' && raw !== null) {
    return String(raw.date || raw).slice(0, 10);
  }
  return String(raw).slice(0, 10);
}

const groupedByDate = computed(() => {
  const groups = new Map();

  for (const expense of expenses.value) {
    const date = expenseDateKey(expense);
    if (!date) continue;

    if (!groups.has(date)) {
      groups.set(date, { date, items: [], total: 0 });
    }

    const group = groups.get(date);
    group.items.push(expense);
    group.total += Number(expense.total_cost || 0);
  }

  return [...groups.values()]
    .map((group) => ({
      ...group,
      items: [...group.items].sort((a, b) => (a.material_type?.name || '').localeCompare(b.material_type?.name || '')),
      total: Math.round(group.total * 100) / 100,
    }))
    .sort((a, b) => b.date.localeCompare(a.date));
});

function switchTab(tab) {
  activeTab.value = tab;
  filters.value.material_type_id = '';
  load();
}

function setHealthMode(mode) {
  healthMode.value = mode;
  load();
}

async function load() {
  const [feed, health] = await Promise.all([
    RanchRepository.listFeedCatalog(),
    RanchRepository.materialTypes({ category: 'animal_health', active_only: false }),
  ]);
  feedMaterials.value = feed;
  healthMaterials.value = health;

  const scope = currentScope();
  const params = { scope };
  if (filters.value.from) params.from = filters.value.from;
  if (filters.value.to) params.to = filters.value.to;
  if (filters.value.material_type_id) params.material_type_id = filters.value.material_type_id;

  const rows = await RanchRepository.listAllExpenses(params);
  expenses.value = rows.filter((row) => matchesScope(row, scope));
  summary.value = {
    count: expenses.value.length,
    total: expenses.value.reduce((sum, row) => sum + Number(row.total_cost || 0), 0),
  };

  if (feedMaterials.value.length && !form.value.material_type_id && activeTab.value === 'feed') {
    form.value.material_type_id = feedMaterials.value[0].id;
  }
}

async function save() {
  saving.value = true;
  try {
    const payload = { ...form.value };
    if (!payload.bundle_count) delete payload.bundle_count;
    if (!payload.notes) delete payload.notes;
    await RanchRepository.createExpense(payload);
    Swal.fire({ icon: 'success', title: 'Compra registrada', timer: 1200, showConfirmButton: false });
    showForm.value = false;
    await load();
  } catch (e) {
    Swal.fire({ icon: 'error', text: e.response?.data?.message || 'Error al registrar la compra.' });
  } finally {
    saving.value = false;
  }
}

onMounted(load);
</script>

<style scoped>
.purchase-date-group {
  border: 1px solid var(--bs-border-color, #dee2e6);
  border-radius: 0.5rem;
  overflow: hidden;
}

.purchase-date-header {
  padding: 0.75rem 1rem;
  background: var(--bs-light, #f8f9fa);
  border-bottom: 1px solid var(--bs-border-color, #dee2e6);
}

.purchase-date-group .table {
  margin-bottom: 0;
}

.purchase-date-group .table thead th {
  background: #fff;
  border-top: none;
}
</style>
