<x-admin-layout>
    <div class="p-0 font-sans bg-slate-50 min-h-screen">
        @if($errors->any())
            <div id="error-alert"
                class="mx-4 mb-6 bg-white border-l-4 border-red-500 text-red-800 p-4 rounded-sm shadow-md relative md:mx-0" role="alert">
                <button type="button" onclick="document.getElementById('error-alert').style.display='none'"
                    class="absolute top-2 right-2 text-red-400 hover:text-red-600 focus:outline-none">
                    <svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                </button>
                <div class="flex">
                    <svg class="h-5 w-5 mr-3 flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd"
                            d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                            clip-rule="evenodd" />
                    </svg>
                    <div>
                        <p class="font-semibold">Veuillez corriger les erreurs ci-dessous.</p>
                        <ul class="mt-2 text-sm list-disc list-inside">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        @endif

        <div class="bg-white border-none shadow-none md:rounded-none p-4 md:p-6 relative min-h-screen">
            <div class="mb-6 flex items-center justify-between">
                <h5 class="text-[14px] font-bold text-gray-700 uppercase tracking-wide">
                    Nouvelle Cotisation
                </h5>
                <a href="{{ route('admin.contributions.index') }}"
                    class="px-4 py-2 text-gray-600 hover:text-gray-900 transition-all text-sm font-bold flex items-center">
                    <svg class="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                            d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                    </svg>
                    Retour
                </a>
            </div>

            <form method="POST" action="{{ route('admin.contributions.store') }}" class="space-y-6">
                @csrf

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="project_id" class="block text-sm font-semibold text-gray-700 mb-2">Projet <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="project_id" id="project_id" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="">Sélectionner un projet</option>
                            @foreach($projects as $project)
                                @php
                                    $membersData = $project->members->map(function($m) use ($project) {
                                        // Filter expected contributions for this project only
                                        $expected = $m->expectedContributions
                                            ->where('project_id', $project->id)
                                            ->map(function($ex) {
                                                return [
                                                    'id' => $ex->id,
                                                    'label' => \Carbon\Carbon::parse($ex->due_date)->translatedFormat('d F Y') . ' (' . \App\Models\Setting::format($ex->amount) . ')'
                                                ];
                                            })->values();

                                        return [
                                            'id' => $m->id, 
                                            'name' => $m->name, 
                                            'first_name' => $m->first_name, 
                                            'last_name' => $m->last_name,
                                            'expected_contributions' => $expected
                                        ];
                                    });
                                @endphp
                                <option value="{{ $project->id }}" 
                                    data-amount="{{ $project->amount }}" 
                                    data-members="{{ json_encode($membersData) }}"
                                    {{ (string) old('project_id', optional($selectedProject)->id) === (string) $project->id ? 'selected' : '' }}>
                                    {{ $project->name }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label for="user_id" class="block text-sm font-semibold text-gray-700 mb-2">Membre <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="user_id" id="user_id" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="">Sélectionner un membre</option>
                            @foreach($members as $member)
                                <option value="{{ $member->id }}" {{ (string) old('user_id', optional($selectedMember)->id) === (string) $member->id ? 'selected' : '' }}>
                                    {{ $member->first_name ?? '' }} {{ $member->last_name ?? '' }} ({{ $member->name }})
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label for="amount" class="block text-sm font-semibold text-gray-700 mb-2">Montant ({{ \App\Models\Setting::get('currency', 'FCFA') }}) <span
                                class="text-red-600 font-bold">*</span></label>
                        <input type="number" step="0.01" min="0" name="amount" id="amount"
                            value="{{ old('amount', $selectedAmount ?? optional($selectedProject)->amount) }}" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px]">
                    </div>

                    <div>
                        <label for="payment_date" class="block text-sm font-semibold text-gray-700 mb-2">Date de
                            paiement
                            <span class="text-red-600 font-bold">*</span></label>
                        <input type="date" name="payment_date" id="payment_date" value="{{ old('payment_date', now()->toDateString()) }}"
                            required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px]">
                    </div>

                    <div>
                        <label for="status" class="block text-sm font-semibold text-gray-700 mb-2">Statut <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="status" id="status" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="paye" {{ old('status', 'paye') === 'paye' ? 'selected' : '' }}>Payé</option>
                            <option value="non_paye" {{ old('status') === 'non_paye' ? 'selected' : '' }}>Non payé
                            </option>
                        </select>
                    </div>

                    <div>
                        <label for="expected_contribution_id"
                            class="block text-sm font-semibold text-gray-700 mb-2">Cotisation attendue
                            (optionnel)</label>
                        <select name="expected_contribution_id" id="expected_contribution_id"
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="">Sélectionner une échéance (optionnel)</option>
                        </select>
                    </div>

                    <div>
                        <label for="management_year_id" class="block text-sm font-semibold text-gray-700 mb-2">Année de gestion <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="management_year_id" id="management_year_id" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            @foreach($years as $year)
                                <option value="{{ $year->id }}" {{ old('management_year_id', $year->status === 'active' ? $year->id : '') == $year->id ? 'selected' : '' }}>
                                    Gestion {{ $year->year }}
                                </option>
                            @endforeach
                        </select>
                    </div>

                    <div>
                        <label for="account_id" class="block text-sm font-semibold text-gray-700 mb-2">Compte de dépôt <span
                                class="text-red-600 font-bold">*</span></label>
                        <select name="account_id" id="account_id" required
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all h-[38px] bg-white">
                            <option value="">Sélectionner un compte</option>
                            @foreach($accounts as $index => $account)
                                <option value="{{ $account->id }}" {{ old('account_id', $index === 0 ? $account->id : '') == $account->id ? 'selected' : '' }}>
                                    {{ $account->name }} (Solde: {{ number_format($account->balance, 0, ',', ' ') }})
                                </option>
                            @endforeach
                        </select>
                    </div>



                    <div class="md:col-span-2">
                        <label for="notes" class="block text-sm font-semibold text-gray-700 mb-2">Notes
                            (optionnel)</label>
                        <textarea name="notes" id="notes" rows="3"
                            class="block w-full px-3 py-2 border border-gray-300 rounded-sm focus:ring-1 focus:ring-blue-600 focus:border-blue-600 transition-all">{{ old('notes') }}</textarea>
                    </div>
                </div>

                <div class="flex flex-col sm:flex-row items-stretch sm:items-center justify-end gap-3 pt-2">
                    <a href="{{ route('admin.contributions.index') }}"
                        class="px-5 py-2 bg-white border border-gray-200 text-gray-700 rounded-sm hover:bg-gray-50 transition-all text-sm font-semibold shadow-sm hover:shadow-md text-center h-[38px] inline-flex items-center">
                        Annuler
                    </a>
                    <button type="submit"
                        class="px-5 py-2 text-white rounded-sm hover:opacity-90 transition-all duration-200 text-sm font-semibold shadow-sm hover:shadow-md h-[38px]"
                        style="background-color: #5867dd !important;">
                        Valider
                    </button>
                </div>
            </form>
        </div>
    </div>
</x-admin-layout>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const projectSelect = document.getElementById('project_id');
        const userSelect = document.getElementById('user_id');
        const amountInput = document.getElementById('amount');
        const expectedSelect = document.getElementById('expected_contribution_id');
        
        let amountTouched = "{{ $selectedAmount }}" !== "" || amountInput.value !== "";
        let currentMembers = []; // Stocker les données des membres du projet sélectionné

        function updateFormFromProject() {
            const selectedOption = projectSelect.selectedOptions[0];
            
            // 1. Mise à jour des membres
            if (selectedOption && selectedOption.value) {
                const membersData = selectedOption.getAttribute('data-members');
                userSelect.innerHTML = '<option value="">Sélectionner un membre</option>';
                expectedSelect.innerHTML = '<option value="">Sélectionner une échéance (optionnel)</option>'; // Reset deadlines
                userSelect.disabled = false;
                expectedSelect.disabled = true; // Disabled until user selected

                if (membersData) {
                    try {
                        currentMembers = JSON.parse(membersData);
                        currentMembers.forEach(member => {
                            const option = document.createElement('option');
                            option.value = member.id;
                            option.textContent = (member.first_name || '') + ' ' + (member.last_name || '') + ' (' + member.name + ')';
                            userSelect.appendChild(option);
                        });
                    } catch (e) {
                        console.error("Erreur parsing membres", e);
                        currentMembers = [];
                    }
                }
            } else {
                userSelect.innerHTML = '<option value="">Sélectionner d\'abord un projet</option>';
                userSelect.disabled = true;
                expectedSelect.innerHTML = '<option value="">Sélectionner une échéance (optionnel)</option>';
                expectedSelect.disabled = true;
                currentMembers = [];
            }

            // 2. Mise à jour du montant
            if (selectedOption && selectedOption.dataset.amount) {
                if (!amountTouched) {
                    amountInput.value = selectedOption.dataset.amount;
                }
            }
        }

        function updateExpectedContributions() {
            const userId = parseInt(userSelect.value);
            expectedSelect.innerHTML = '<option value="">Sélectionner une échéance (optionnel)</option>';
            
            if (!userId) {
                expectedSelect.disabled = true;
                return;
            }

            const member = currentMembers.find(m => m.id === userId);
            
            if (member && member.expected_contributions && member.expected_contributions.length > 0) {
                expectedSelect.disabled = false;
                member.expected_contributions.forEach(ex => {
                    const option = document.createElement('option');
                    option.value = ex.id;
                    option.textContent = ex.label;
                    expectedSelect.appendChild(option);
                });
            } else {
                const option = document.createElement('option');
                option.textContent = "Aucun impayé trouvé";
                expectedSelect.appendChild(option);
                expectedSelect.disabled = true; 
                // On pourrait laisser enabled pour permettre 'Aucune' mais c'est informatif
            }
        }

        // Écouteur Project Change
        projectSelect.addEventListener('change', function() {
            amountTouched = false;
            updateFormFromProject();
        });

        // Écouteur User Change
        userSelect.addEventListener('change', function() {
            updateExpectedContributions();
        });

        // Amount touch detection
        amountInput.addEventListener('input', function() {
            amountTouched = true;
        });

        // Init au chargement
        if(projectSelect.value) {
            updateFormFromProject();
            
            // Restaurer membre
            const selectedUserId = "{{ old('user_id', optional($selectedMember)->id) }}";
            if(selectedUserId) {
                const memberExists = Array.from(userSelect.options).some(o => o.value == selectedUserId);
                if(memberExists) {
                    userSelect.value = selectedUserId;
                    updateExpectedContributions();
                    
                    // Restaurer cotisation attendue
                    const selectedExpectedId = "{{ old('expected_contribution_id', $selectedExpectedContributionId) }}";
                    if(selectedExpectedId) {
                        expectedSelect.value = selectedExpectedId;
                    }
                }
            }
        } else {
             userSelect.innerHTML = '<option value="">Sélectionner d\'abord un projet</option>';
             userSelect.disabled = true;
             expectedSelect.disabled = true;
        }
    });
</script>