<script setup>
import AuthenticatedLayout from '@/Layouts/AuthenticatedLayout.vue';
import { Head, Link, useForm } from '@inertiajs/vue3';
import { computed, reactive } from 'vue';

const props = defineProps({
    lot: { type: Object, required: true },
    evaluation: { type: Object, default: () => ({}) },
    cattleOptions: { type: Array, default: () => [] },
});

const animals = computed(() => props.lot.active_animals || props.lot.activeAnimals || []);

const addForm = useForm({
    cattle_id: '',
    entry_weight_kg: '',
    entry_date: new Date().toISOString().slice(0, 10),
});

const exitWeights = reactive({});

const addAnimal = () => addForm.post(route('admin.ranch.fattening.add-animal', props.lot.id), {
    onSuccess: () => addForm.reset('cattle_id', 'entry_weight_kg'),
});

const closeForm = useForm({ exit_weights: [] });

const closeLot = () => {
    closeForm.exit_weights = animals.value.map((a) => ({
        cattle_id: a.cattle_id,
        exit_weight_kg: exitWeights[a.cattle_id] || '',
    }));
    closeForm.post(route('admin.ranch.fattening.close', props.lot.id));
};

const money = (n) =>
    new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(Number(n || 0));
</script>

<template>
    <Head :title="lot.name" />

    <AuthenticatedLayout>
        <template #header><h3 class="mb-0">{{ lot.name }}</h3></template>
        <template #breadcrumb>
            <li class="breadcrumb-item"><Link :href="route('dashboard')">Inicio</Link></li>
            <li class="breadcrumb-item"><Link :href="route('admin.ranch.fattening.index')">Engorda</Link></li>
            <li class="breadcrumb-item active">{{ lot.name }}</li>
        </template>

        <div class="row mb-3">
            <div class="col-md-4">
                <div class="info-box">
                    <span class="info-box-icon text-bg-primary"><i class="fa-solid fa-coins"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Costo alimento</span>
                        <span class="info-box-number">{{ money(evaluation.total_feed_cost) }}</span>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="info-box">
                    <span class="info-box-icon text-bg-success"><i class="fa-solid fa-chart-line"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Ganancia peso</span>
                        <span class="info-box-number">{{ evaluation.total_weight_gain_kg ?? 0 }} kg</span>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="info-box">
                    <span class="info-box-icon text-bg-warning"><i class="fa-solid fa-calendar"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text">Días</span>
                        <span class="info-box-number">{{ evaluation.days_in_confinement ?? '—' }}</span>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="lot.status === 'open'" class="card mb-3">
            <div class="card-header"><h3 class="card-title">Agregar animal</h3></div>
            <form @submit.prevent="addAnimal">
                <div class="card-body row g-3">
                    <div class="col-md-5">
                        <select v-model="addForm.cattle_id" class="form-select" required>
                            <option value="">Arete...</option>
                            <option v-for="c in cattleOptions" :key="c.id" :value="c.id">{{ c.ear_tag }}</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <input v-model="addForm.entry_weight_kg" type="number" step="0.01" class="form-control" placeholder="Peso entrada" required />
                    </div>
                    <div class="col-md-2">
                        <input v-model="addForm.entry_date" type="date" class="form-control" />
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-success w-100" :disabled="addForm.processing">Agregar</button>
                    </div>
                </div>
            </form>
        </div>

        <div class="card mb-3">
            <div class="card-header"><h3 class="card-title">Animales en lote</h3></div>
            <div class="card-body table-responsive p-0">
                <table class="table mb-0">
                    <thead>
                        <tr>
                            <th>Arete</th>
                            <th>Peso entrada</th>
                            <th>Fecha</th>
                            <th v-if="lot.status === 'open'">Peso salida</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="a in animals" :key="a.id">
                            <td>{{ a.cattle?.ear_tag }}</td>
                            <td>{{ a.entry_weight_kg }}</td>
                            <td>{{ a.entry_date }}</td>
                            <td v-if="lot.status === 'open'">
                                <input v-model="exitWeights[a.cattle_id]" type="number" step="0.01" class="form-control form-control-sm" style="width: 120px" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div v-if="lot.status === 'open' && animals.length" class="card-footer">
                <button type="button" class="btn btn-danger" :disabled="closeForm.processing" @click="closeLot">
                    Cerrar lote
                </button>
            </div>
        </div>
    </AuthenticatedLayout>
</template>
