@extends('admin.layouts.home')

@section('title', 'Group Categories')

@section('content')
<div class="container-fluid">
    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Group Categories</h1>
    </div>

    <!-- Categories List -->
    <div class="card shadow mb-4">
        <div class="card-header py-3">
            <div class="d-flex justify-content-between">
                <h6 class="m-0 font-weight-bold text-primary">All Categories</h6>
                <button type="button" class="d-none d-sm-inline-block btn btn-sm btn-primary shadow-sm" data-bs-toggle="modal" data-bs-target="#createCategoryModal">
                    <i class="fas fa-plus fa-sm text-white-50"></i> Add New Category
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="categoriesTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Icon</th>
                            <th>Description</th>
                            <th>Groups</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="cat-table">
                        @forelse($categories as $category)
                        <tr>
                            <td>{{ $category->id }}</td>
                            <td>{{ $category->name }}</td>
                            <td>
                                @if($category->icon)
                                    <i class="fas {{ $category->icon }}"></i> {{ $category->icon }}
                                @else
                                    <span class="text-muted">None</span>
                                @endif
                            </td>
                            <td>{{ Str::limit($category->description, 50) }}</td>
                            <td>
                                <span class="badge bg-primary">{{ $category->groups_count ?? 0 }} groups</span>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-info edit-category" 
                                        data-id="{{ $category->id }}"
                                        data-name="{{ $category->name }}"
                                        data-icon="{{ $category->icon }}"
                                        data-description="{{ $category->description }}">
                                    <i class="fas fa-edit"></i>
                                </button>
                                
                                <form action="{{ route('admin.groups.delete-category', $category->id) }}" method="POST" class="d-inline">
                                    @csrf
                                    @method('DELETE')
                                    <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this category? All groups in this category will be moved to the default category.')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="6" class="text-center">No categories found. Create one to get started!</td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create Category Modal -->
<div class="modal fade" id="createCategoryModal" tabindex="-1" role="dialog" aria-labelledby="createCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form action="{{ route('admin.groups.store-category') }}" method="POST">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="createCategoryModalLabel">Create New Category</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="name">Category Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="name" name="name" required>
                    </div>
                    
                    <div class="form-group">
                        <label for="icon">Icon Class (FontAwesome)</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fas fa-icons"></i></span>
                            </div>
                            <input type="text" class="form-control" id="icon" name="icon" placeholder="fa-users">
                        </div>
                        <small class="form-text text-muted">Enter a FontAwesome icon class (e.g., fa-users, fa-music)</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Category Modal -->
<div class="modal fade" id="editCategoryModal" tabindex="-1" role="dialog" aria-labelledby="editCategoryModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="editCategoryForm" action="" method="POST">
                @csrf
                @method('PUT')
                <div class="modal-header">
                    <h5 class="modal-title" id="editCategoryModalLabel">Edit Category</h5>
                    <button type="button" class="btn close" data-bs-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="alert alert-danger" id="editErrorMessage" style="display: none;"></div>
                    <div class="form-group">
                        <label for="edit_name">Category Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control @error('name') is-invalid @enderror" id="edit_name" name="name" required>
                        <div class="invalid-feedback" id="edit_name_error"></div>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_icon">Icon Class (FontAwesome)</label>
                        <div class="input-group">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i id="icon_preview" class="fas fa-icons"></i></span>
                            </div>
                            <input type="text" class="form-control @error('icon') is-invalid @enderror" id="edit_icon" name="icon" placeholder="fa-users">
                            <div class="invalid-feedback" id="edit_icon_error"></div>
                        </div>
                        <small class="form-text text-muted">Enter a FontAwesome icon class (e.g., fa-users, fa-music)</small>
                    </div>
                    
                    <div class="form-group">
                        <label for="edit_description">Description</label>
                        <textarea class="form-control @error('description') is-invalid @enderror" id="edit_description" name="description" rows="3"></textarea>
                        <div class="invalid-feedback" id="edit_description_error"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary" id="updateCategoryBtn">Update Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    $(document).ready(function() {
        
        // Set up edit category modal
        $('#cat-table').on('click', '.edit-category',function() {
            var id = $(this).data('id');
            var name = $(this).data('name');
            var icon = $(this).data('icon');
            var description = $(this).data('description');
            console.log(id, name, icon, description);
            // Reset form and error messages
            $('#editErrorMessage').hide();
            $('.is-invalid').removeClass('is-invalid');
            $('.invalid-feedback').text('');
            
            $('#editCategoryForm').attr('action', '{{ route("admin.groups.update-category", "") }}/' + id);
            $('#edit_name').val(name);
            $('#edit_icon').val(icon);
            $('#edit_description').val(description);
            $('#editCategoryModal').modal('show');
            if (icon) {
                $('#icon_preview').attr('class', 'fas ' + icon);
            } else {
                $('#icon_preview').attr('class', 'fas fa-icons');
            }
        });
        
        // Handle edit form submission
        $('#editCategoryForm').on('submit', function(e) {
            e.preventDefault();
            var form = $(this);
            var submitBtn = $('#updateCategoryBtn');
            
            // Disable submit button
            submitBtn.prop('disabled', true);
            
            $.ajax({
                url: form.attr('action'),
                method: 'PUT',
                data: form.serialize(),
                success: function(response) {
                    // Hide modal and reload page
                    $('#editCategoryModal').modal('hide');
                    location.reload();
                },
                error: function(xhr) {
                    // Enable submit button
                    submitBtn.prop('disabled', false);
                    
                    // Reset error states
                    $('.is-invalid').removeClass('is-invalid');
                    $('.invalid-feedback').text('');
                    
                    if (xhr.status === 422) {
                        // Validation errors
                        var errors = xhr.responseJSON.errors;
                        $.each(errors, function(field, messages) {
                            $('#edit_' + field).addClass('is-invalid');
                            $('#edit_' + field + '_error').text(messages[0]);
                        });
                    } else {
                        // General error
                        $('#editErrorMessage')
                            .text('An error occurred while updating the category. Please try again.')
                            .show();
                    }
                }
            });
        });
        
        // Update icon preview when typing
        $('#edit_icon').on('input', function() {
            var iconClass = $(this).val();
            if (iconClass) {
                $('#icon_preview').attr('class', 'fas ' + iconClass);
            } else {
                $('#icon_preview').attr('class', 'fas fa-icons');
            }
        });
        
        $('#icon').on('input', function() {
            var iconClass = $(this).val();
            if (iconClass) {
                $(this).closest('.input-group').find('.input-group-text i').attr('class', 'fas ' + iconClass);
            } else {
                $(this).closest('.input-group').find('.input-group-text i').attr('class', 'fas fa-icons');
            }
        });
    });
</script>
@endsection