/**
 * Animal Form — Alta y edición de animal
 */

$(document).ready(function() {
    AnimalForm.init();
});

const AnimalForm = {
    animalId: null,
    photoFiles: [],

    async init() {
        this.animalId = $('#animalForm').data('animal-id') || null;

        await this.loadSelectOptions();

        if (this.animalId) {
            await this.loadAnimalData();
        }

        this.bindEvents();
    },

    // ─── LOAD SELECT OPTIONS ────────────────────────────────

    async loadSelectOptions() {
        const [speciesRes, lotsRes, locationsRes] = await Promise.all([
            API.get('/species'),
            API.get('/lots'),
            API.get('/ranches/1/locations'),
        ]);

        if (speciesRes.success) {
            speciesRes.data.forEach(s => {
                $('#species_id').append(`<option value="${s.id}">${s.name}</option>`);
            });
        }

        if (lotsRes.success) {
            lotsRes.data.forEach(l => {
                $('#lot_id').append(`<option value="${l.id}">${l.name}</option>`);
            });
        }

        if (locationsRes.success) {
            locationsRes.data.forEach(l => {
                $('#location_id').append(`<option value="${l.id}">${l.name} (${l.location_type || ''})</option>`);
            });
        }
    },

    // ─── LOAD ANIMAL DATA (Edit) ────────────────────────────

    async loadAnimalData() {
        const res = await API.get(`/animals/${this.animalId}`);
        if (!res.success) {
            Toast.error('No se pudo cargar el animal');
            return;
        }

        const a = res.data;

        // Fill form fields
        const fields = ['name', 'tag_id', 'sex', 'color', 'birth_date', 'entry_date',
            'origin', 'notes', 'status', 'health_status', 'reproductive_status',
            'current_weight', 'target_weight'];

        fields.forEach(f => {
            const $el = $(`#${f}`);
            if ($el.length && a[f] !== null && a[f] !== undefined) {
                $el.val(a[f]);
            }
        });

        // Species → trigger breed load
        if (a.species_id) {
            $('#species_id').val(a.species_id);
            await this.loadBreeds(a.species_id);
            if (a.breed_id) $('#breed_id').val(a.breed_id);
        }

        // Lot, location
        if (a.lot_id) $('#lot_id').val(a.lot_id);
        if (a.location_id) $('#location_id').val(a.location_id);

        // Parents
        if (a.mother_id) await this.loadParentOption('mother_id', a.mother_id, a.mother_name);
        if (a.father_id) await this.loadParentOption('father_id', a.father_id, a.father_name);

        // Photo — field from DB is primary_photo
        const mainPhoto = a.primary_photo || a.main_photo;
        if (mainPhoto) {
            const photoUrl = mainPhoto.startsWith('/') ? mainPhoto : '/' + mainPhoto;
            $('#photoPreview').html(`<img src="${photoUrl}" alt="">`);
        }
    },

    async loadParentOption(field, id, name) {
        $(`#${field}`).append(`<option value="${id}" selected>${name || '#' + id}</option>`);
    },

    // ─── LOAD BREEDS by Species ─────────────────────────────

    async loadBreeds(speciesId) {
        const $breed = $('#breed_id');
        $breed.html('<option value="">Selecciona raza</option>');

        if (!speciesId) return;

        const res = await API.get(`/breeds?species_id=${speciesId}`);
        if (res.success) {
            res.data.forEach(b => {
                $breed.append(`<option value="${b.id}">${b.name}</option>`);
            });
        }

        // Also load parents for this species
        await this.loadParents(speciesId);
    },

    async loadParents(speciesId) {
        const [mothersRes, fathersRes] = await Promise.all([
            API.get(`/animals?species_id=${speciesId}&sex=female&per_page=500&status=active`),
            API.get(`/animals?species_id=${speciesId}&sex=male&per_page=500&status=active`),
        ]);

        const $mother = $('#mother_id');
        const $father = $('#father_id');
        const currentMother = $mother.val();
        const currentFather = $father.val();

        $mother.html('<option value="">Sin madre registrada</option>');
        $father.html('<option value="">Sin padre registrado</option>');

        if (mothersRes.success) {
            mothersRes.data.forEach(a => {
                if (a.id != this.animalId) {
                    $mother.append(`<option value="${a.id}">${a.name || a.tag_id || '#' + a.id}</option>`);
                }
            });
        }
        if (fathersRes.success) {
            fathersRes.data.forEach(a => {
                if (a.id != this.animalId) {
                    $father.append(`<option value="${a.id}">${a.name || a.tag_id || '#' + a.id}</option>`);
                }
            });
        }

        if (currentMother) $mother.val(currentMother);
        if (currentFather) $father.val(currentFather);
    },

    // ─── EVENTS ─────────────────────────────────────────────

    bindEvents() {
        const self = this;

        // Species change → load breeds
        $('#species_id').on('change', function() {
            self.loadBreeds($(this).val());
        });

        // Photo upload — use native DOM to avoid jQuery click recursion
        const uploadArea = document.getElementById('photoUploadArea');
        const fileInput = document.getElementById('mainPhoto');

        if (uploadArea && fileInput) {
            uploadArea.addEventListener('click', function(e) {
                // Prevent recursion: if the click came from the input itself, ignore
                if (e.target === fileInput) return;
                fileInput.click();
            });

            fileInput.addEventListener('change', function() {
                if (this.files.length) {
                    self.addPhotos(Array.from(this.files));
                }
            });

            // Drag & drop
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.classList.add('drag-over');
            });
            uploadArea.addEventListener('dragleave', function() {
                this.classList.remove('drag-over');
            });
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('drag-over');
                if (e.dataTransfer.files.length) {
                    self.addPhotos(Array.from(e.dataTransfer.files));
                }
            });
        }

        // Form submit
        $('#animalForm').on('submit', function(e) {
            e.preventDefault();
            self.save();
        });
    },

    addPhotos(files) {
        files.forEach(file => {
            if (!file.type.startsWith('image/')) return;
            this.photoFiles.push(file);
        });
        this.renderPhotoPreview();
    },

    removePhoto(index) {
        this.photoFiles.splice(index, 1);
        this.renderPhotoPreview();
    },

    renderPhotoPreview() {
        const preview = document.getElementById('photoPreview');
        if (!this.photoFiles.length) {
            preview.innerHTML = `
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" style="color:var(--text-muted)">
                    <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
                    <circle cx="12" cy="13" r="4"/>
                </svg>
                <span class="photo-label">Tomar foto</span>`;
            return;
        }

        let html = '<div class="photo-thumbs-row">';
        this.photoFiles.forEach((file, i) => {
            const url = URL.createObjectURL(file);
            html += `
                <div class="photo-thumb-item">
                    <img src="${url}" alt="">
                    <button type="button" class="photo-thumb-remove" onclick="AnimalForm.removePhoto(${i})" title="Quitar">&times;</button>
                    ${i === 0 ? '<span class="photo-thumb-badge">Principal</span>' : ''}
                </div>`;
        });
        html += `
            <div class="photo-thumb-add" id="photoAddMore">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
            </div>
        </div>`;
        html += `<div class="photo-count">${this.photoFiles.length} foto${this.photoFiles.length > 1 ? 's' : ''} seleccionada${this.photoFiles.length > 1 ? 's' : ''}</div>`;
        preview.innerHTML = html;

        // Bind the add-more button
        const addBtn = document.getElementById('photoAddMore');
        if (addBtn) {
            addBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                document.getElementById('mainPhoto').click();
            });
        }
    },

    // ─── SAVE ───────────────────────────────────────────────

    async save() {
        const $btn = $('#btnSave');
        $btn.prop('disabled', true).html('<span class="loader" style="display:inline-block;width:16px;height:16px;border:2px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .6s linear infinite"></span> Guardando...');

        // Collect form data
        const data = {};
        const fields = ['name', 'tag_id', 'species_id', 'breed_id', 'sex', 'color',
            'birth_date', 'entry_date', 'origin', 'mother_id', 'father_id',
            'lot_id', 'location_id', 'status', 'health_status', 'reproductive_status',
            'current_weight', 'target_weight', 'notes'];

        fields.forEach(f => {
            const val = $(`#${f}`).val();
            if (val !== '' && val !== null) data[f] = val;
        });

        let res;
        if (this.animalId) {
            res = await API.put(`/animals/${this.animalId}`, data);
        } else {
            res = await API.post('/animals', data);
        }

        if (res.success) {
            const id = res.data?.id || this.animalId;

            // Upload photos if selected
            if (this.photoFiles.length && id) {
                for (let i = 0; i < this.photoFiles.length; i++) {
                    await API.upload(`/animals/${id}/photos`, this.photoFiles[i], 'photo', {
                        is_primary: i === 0 ? '1' : '0',
                        context: 'profile'
                    });
                }
            }

            Toast.success(this.animalId ? 'Animal actualizado' : 'Animal registrado');

            // Redirect to profile
            setTimeout(() => {
                window.location.href = `/animales/${id}`;
            }, 500);
        } else {
            Toast.error(res.message || 'Error al guardar');
            $btn.prop('disabled', false).html(`
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <polyline points="20 6 9 17 4 12"/>
                </svg>
                ${this.animalId ? 'Guardar Cambios' : 'Registrar Animal'}
            `);
        }
    },
};
