<div>
    <div class="card">
        <div class="card-header">
            <h4 class="card-title mb-0">Student Batch Assignment</h4>
        </div>
        <div class="card-body">
            <div class="row mb-4">
                <div class="col-md-4">
                    <label for="selectedClass" class="form-label">Filter by Class</label>
                    <select class="form-select" id="selectedClass" wire:model.live="selectedClass">
                        <option value="">All Classes</option>
                        @foreach($schoolClasses as $class)
                            <option value="{{ $class->id }}">{{ $class->display_name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="search" class="form-label">Search Students</label>
                    <input type="text" class="form-control" id="search" placeholder="Search by name or ID..."
                           wire:model.live="search">
                </div>
                <div class="col-md-4">
                    <label class="form-label">&nbsp;</label>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" id="showUnassignedOnly"
                               wire:model.live="showUnassignedOnly">
                        <label class="form-check-label" for="showUnassignedOnly">
                            Show only unassigned students
                        </label>
                    </div>
                </div>
            </div>

            <!-- Mass Assignment Controls -->
            @if(count($selectedStudents) > 0)
                <div class="card border-primary mb-4 shadow-sm">
                    <div class="card-header bg-dark text-light">
                        <h6 class="mb-0 text-light">
                            <i class="fas fa-users me-2"></i>
                            {{ count($selectedStudents) }} Student{{ count($selectedStudents) > 1 ? 's' : '' }} Selected
                        </h6>
                    </div>
                    <div class="card-body">
                        <div class="row align-items-center">
                            <div class="col-md-6 mb-3 mb-md-0">
                                <label class="form-label fw-bold">Select Target Batch:</label>
                                <select class="form-select" wire:model.live="selectedBatch">
                                    <option value="">Choose batch for assignment...</option>
                                    @foreach($allBatches as $batch)
                                        <option value="{{ $batch->id }}">
                                            {{ $batch->name }} - {{ $batch->schoolClass->display_name }}
                                            ({{ $batch->current_students }}/{{ $batch->capacity }})
                                        </option>
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-6">
                                <label class="form-label fw-bold">Actions:</label>
                                <div class="d-flex gap-2">
                                    <button class="btn btn-success"
                                            onclick="confirmMassAssign()">
                                        <i class="fas fa-user-plus me-1"></i>Assign Selected
                                    </button>
                                    <button class="btn btn-danger" onclick="confirmMassDetach()">
                                        <i class="fas fa-user-times me-1"></i>Detach Selected
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            @endif

            <!-- Desktop 2-Column Layout -->
            <div class="d-none d-md-block">
                <div class="row mb-3">
                    <div class="col-12">
                        <div class="d-flex gap-2">
                            <button type="button" class="btn btn-primary"
                                    onclick="document.querySelectorAll('input[type=checkbox]').forEach(cb => { cb.checked = true; cb.dispatchEvent(new Event('change')); }); @this.call('selectAll')">
                                <i class="fas fa-check-square me-1"></i>Select All
                            </button>
                            <button type="button" class="btn btn-secondary"
                                    onclick="document.querySelectorAll('input[type=checkbox]').forEach(cb => { cb.checked = false; cb.dispatchEvent(new Event('change')); }); @this.call('deselectAll')">
                                <i class="fas fa-square me-1"></i>Deselect All
                            </button>
                        </div>
                    </div>
                </div>

                <div class="row">
                    @forelse($students->chunk(ceil($students->count() / 2)) as $columnIndex => $studentChunk)
                        <div class="col-md-6">
                            @foreach($studentChunk as $student)
                                <div class="card mb-2 shadow-sm border-0 student-card">
                                    <div class="card-body p-3">
                                        <div class="row align-items-center">
                                            <div class="col-1">
                                                <input type="checkbox" class="form-check-input"
                                                       wire:model.live="selectedStudents" value="{{ $student->id }}">
                                            </div>
                                            <div class="col-3">
                                                <strong>{{ $student->name }}</strong><br>
                                                <small class="text-muted">{{ $student->student_id ?? 'N/A' }}</small>
                                            </div>
                                            <div class="col-4">
                                                @if($student->batch)
                                                    <span
                                                        class="badge bg-info badge-sm">{{ $student->batch->name }}</span>
                                                @else
                                                    <span class="badge bg-secondary badge-sm">Unassigned</span>
                                                @endif
                                            </div>
                                            <div class="col-4">
                                                @if($selectedClass && count($batches) > 0)
                                                    <select class="form-select form-select-sm"
                                                            onchange="confirmAssignStudent({{ $student->id }}, this.value, '{{ $student->name }}', this.options[this.selectedIndex].text)">
                                                        <option value="">Select...</option>
                                                        @foreach($batches as $batch)
                                                            <option value="{{ $batch->id }}"
                                                                {{ $student->batch_id == $batch->id ? 'selected' : '' }}
                                                                {{ $batch->current_students >= $batch->capacity && $student->batch_id != $batch->id ? 'disabled' : '' }}>
                                                                {{ $batch->name }} ({{ $batch->current_students }}/{{ $batch->capacity }})
                                                            </option>
                                                        @endforeach
                                                    </select>
                                                @else
                                                    <small class="text-muted">{{ $selectedClass ? 'No batches available' : 'Select a class first' }}</small>
                                                @endif
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    @empty
                        <div class="col-12 text-center py-4">
                            <i class="fas fa-user-graduate fa-2x text-muted mb-2"></i>
                            <p class="text-muted mb-0">No students found</p>
                        </div>
                    @endforelse
                </div>
            </div>

            <!-- Mobile Cards -->
            <div class="d-md-none">
                @forelse($students as $student)
                    <div class="card mb-3">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start">
                                <h6 class="card-title">{{ $student->name }}</h6>
                                <input type="checkbox" class="form-check-input"
                                       wire:model.live="selectedStudents" value="{{ $student->id }}">
                            </div>
                            <p class="card-text">
                                <strong>ID:</strong> {{ $student->student_id ?? 'N/A' }}<br>
                                <strong>Current Batch:</strong>
                                @if($student->batch)
                                    <span class="badge bg-info">{{ $student->batch->name }}</span>
                                @else
                                    <span class="badge bg-secondary">Unassigned</span>
                                @endif
                            </p>


                            @if($selectedClass && count($batches) > 0)
                                <select class="form-select form-select-sm"
                                        onchange="confirmAssignStudent({{ $student->id }}, this.value, '{{ $student->name }}', this.options[this.selectedIndex].text)">
                                    <option value="">Select Batch...</option>
                                    @foreach($batches as $batch)
                                        <option value="{{ $batch->id }}"
                                            {{ $student->batch_id == $batch->id ? 'selected' : '' }}
                                            {{ $batch->current_students >= $batch->capacity && $student->batch_id != $batch->id ? 'disabled' : '' }}>
                                            {{ $batch->name }} ({{ $batch->current_students }}/{{ $batch->capacity }})
                                        </option>
                                    @endforeach
                                </select>
                            @else
                                <small class="text-muted">Select a class first</small>
                            @endif
                        </div>
                    </div>
                @empty
                    <div class="text-center py-4">
                        <i class="fas fa-user-graduate fa-3x text-muted mb-3"></i>
                        <p class="text-muted">No students found</p>
                    </div>
                @endforelse
            </div>

            <!-- Pagination -->
            <div class="d-flex justify-content-center mt-4">
                {{ $students->links('custom.pagination') }}
            </div>
        </div>
    </div>
</div>

<script>
    function confirmAssignStudent(studentId, batchId, studentName, batchName) {
        if (!batchId) return;

        Swal.fire({
            title: 'Assign Student?',
            text: `Assign ${studentName} to ${batchName}?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: 'var(--bs-primary)',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Assign',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                @this.call('assignStudent', studentId, batchId);
            } else {
                // Reset the dropdown
                event.target.value = '';
            }
        });
    }

    function confirmMassAssign() {
        const selectedCount = @this.selectedStudents.length;
        const batchSelect = document.querySelector('select[wire\\:model\\.live="selectedBatch"]');
        const batchName = batchSelect.options[batchSelect.selectedIndex].text;

        if (!batchSelect.value) {
            Swal.fire('No Batch Selected', 'Please select a batch for assignment.', 'warning');
            return;
        }

        Swal.fire({
            title: 'Mass Assignment',
            text: `Assign ${selectedCount} selected students to ${batchName}?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: 'var(--bs-primary)',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Assign All',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                @this.call('massAssign');
            }
        });
    }

    function confirmMassDetach() {
        const selectedCount = @this.selectedStudents.length;

        if (selectedCount === 0) {
            Swal.fire('No Selection', 'Please select students to detach.', 'warning');
            return;
        }

        Swal.fire({
            title: 'Mass Detachment',
            text: `Detach ${selectedCount} selected students from their current batches?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Detach All',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                @this.call('massDetach');
            }
        });
    }
</script>
