import { Controller } from '@hotwired/stimulus';

/* Sélecteur de concessions (port de ConcessionPicker.tsx + storeConcessions → /api/concessions). */
export default class extends Controller {
    static targets = ['search', 'item', 'list', 'empty', 'count', 'selectedInfo', 'selectedCount', 'confirm', 'error'];
    static values = { redirect: String, total: Number };

    connect() {
        this.updateCounts();
        this.searchTarget?.focus();
    }

    filter() {
        const q = this.searchTarget.value.trim().toLowerCase();
        let visible = 0;
        this.itemTargets.forEach((item) => {
            const match = !q || item.dataset.name.includes(q);
            item.classList.toggle('hidden', !match);
            if (match) visible++;
        });
        this.emptyTarget.classList.toggle('hidden', visible > 0);
        this.emptyTarget.classList.toggle('flex', visible === 0);
        this.countTarget.textContent = q
            ? `${visible} résultat${visible > 1 ? 's' : ''}`
            : `${this.totalValue} concessions`;
    }

    visibleCheckboxes() {
        return this.itemTargets
            .filter((item) => !item.classList.contains('hidden'))
            .map((item) => item.querySelector('input[type=checkbox]'));
    }

    selectAll() {
        this.visibleCheckboxes().forEach((cb) => { cb.checked = true; });
        this.updateCounts();
    }

    clearAll() {
        this.visibleCheckboxes().forEach((cb) => { cb.checked = false; });
        this.updateCounts();
    }

    selected() {
        return this.itemTargets
            .map((item) => item.querySelector('input[type=checkbox]'))
            .filter((cb) => cb.checked)
            .map((cb) => cb.value);
    }

    updateCounts() {
        const count = this.selected().length;
        this.selectedCountTarget.textContent = String(count);
        this.selectedInfoTarget.classList.toggle('hidden', count === 0);
        this.confirmTarget.disabled = count === 0;
        this.confirmTarget.textContent = count === 0
            ? 'Sélectionnez au moins une concession'
            : `Confirmer (${count} concession${count > 1 ? 's' : ''})`;
    }

    async confirm() {
        const concessions = this.selected();
        if (concessions.length === 0) return;

        this.confirmTarget.disabled = true;
        this.confirmTarget.textContent = 'Enregistrement…';
        try {
            const res = await fetch('/api/concessions', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ concessions }),
            });
            if (!res.ok) throw new Error('save failed');
            window.location.href = this.redirectValue || '/';
        } catch {
            this.errorTarget.textContent = "Erreur lors de l'enregistrement. Réessayez.";
            this.errorTarget.classList.remove('hidden');
            this.updateCounts();
        }
    }
}
