@extends('admin.layouts.home')

@section('title', 'Manage Groups')

@section('content')
<style>
    .min-width-150 {
        min-width: 150px;
    }

    .min-width-200 {
        min-width: 200px;
    }
</style>
<div class="container-fluid p-0">
    <div class="content-wrapper p-3">
        <!-- Page Header with Breadcrumbs -->
        <div class="content-header mb-4">
            <div class="container-fluid">
                <div class="row align-items-center">
                    <div class="col-12">
                        <div class="card bg-primary text-white mb-3">
                            <div class="card-body py-4">
                                <div class="d-flex align-items-center">
                                    <div class="avatar-lg rounded-circle bg-white text-primary me-3">
                                        <i class="bi bi-people-fill fs-1"></i>
                                    </div>
                                    <div>
                                        <h1 class="m-0 fw-bold">Manage Groups</h1>
                                        <nav aria-label="breadcrumb">
                                            <ol class="breadcrumb mb-0 text-white-50">
                                                <li class="breadcrumb-item"><i class="bi bi-speedometer2 me-1"></i><a href="{{ url('/admin') }}" class="text-white-50">Dashboard</a></li>
                                                <li class="breadcrumb-item active text-white" aria-current="page">Manage Groups</li>
                                            </ol>
                                        </nav>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Statistics Cards Row -->
        <div class="row mb-4">
            <!-- Total Groups Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-primary shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Groups</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $totalGroups ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-people-fill fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Active Groups Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-success shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Public Groups</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $publicGroups ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-check-circle-fill fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Pending Requests Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-warning shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Private Groups</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $privateGroups ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-clock-fill fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Reported Groups Card -->
            <div class="col-xl-3 col-md-6 mb-4">
                <div class="card border-left-danger shadow h-100 py-2">
                    <div class="card-body">
                        <div class="row no-gutters align-items-center">
                            <div class="col mr-2">
                                <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">Reported Groups</div>
                                <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $reportedGroups ?? 0 }}</div>
                            </div>
                            <div class="col-auto">
                                <i class="bi bi-flag-fill fa-2x text-gray-300"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Groups List Table -->
        <div class="card shadow mb-4">
            <div class="card-header py-3 d-flex justify-content-between align-items-center">
                <h6 class="m-0 font-weight-bold text-primary">All Groups</h6>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <div class="col-md-12">
                        <form action="{{ route('admin.groups.index') }}" method="GET" class="form-inline bg-white rounded shadow-sm p-3">
                            <div class="d-flex flex-wrap gap-3">
                                <div class="flex-grow-1 min-width-200">
                                    <label class="form-label text-muted small mb-1">Search Groups</label>
                                    <div class="input-group">
                                        <span class="input-group-text bg-light border-0"><i class="bi bi-search"></i></span>
                                        <input type="text" name="search" class="form-control border-0 bg-light" placeholder="Search by group name..." value="{{ request('search') }}">
                                    </div>
                                </div>
                                <div class="min-width-150">
                                    <label class="form-label text-muted small mb-1">Privacy</label>
                                    <select name="privacy" class="form-select border-0 bg-light">
                                        <option value="">All Privacy</option>
                                        <option value="0" {{ request('privacy') === '0' ? 'selected' : '' }}>Public</option>
                                        <option value="1" {{ request('privacy') === '1' ? 'selected' : '' }}>Private</option>
                                    </select>
                                </div>
                                <div class="min-width-150">
                                    <label class="form-label text-muted small mb-1">Sort By</label>
                                    <select name="sort" class="form-select border-0 bg-light">
                                        <option value="newest" {{ request('sort') === 'newest' ? 'selected' : '' }}>Newest First</option>
                                        <option value="oldest" {{ request('sort') === 'oldest' ? 'selected' : '' }}>Oldest First</option>
                                        <option value="members" {{ request('sort') === 'members' ? 'selected' : '' }}>Most Members</option>
                                    </select>
                                </div>
                                <div class="flex-grow-1 min-width-200">
                                    <label class="form-label text-muted small mb-1">Date Range</label>
                                    <div class="d-flex gap-2">
                                        <input type="date" name="date_from" class="form-control border-0 bg-light" value="{{ request('date_from') }}" placeholder="From">
                                        <input type="date" name="date_to" class="form-control border-0 bg-light" value="{{ request('date_to') }}" placeholder="To">
                                    </div>
                                </div>
                                <div class="d-flex gap-2 align-items-end">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-funnel me-1"></i> Filter
                                    </button>
                                    <a href="{{ route('admin.groups.index') }}" class="btn btn-light">
                                        <i class="bi bi-x-circle"></i>
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-bordered" id="groupsTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Group Name</th>
                                <th>Privacy</th>
                                <th>Owner</th>
                                <th>Members</th>
                                <th>Is Featured</th>
                                <th>Created</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @forelse($groups as $group)
                            <tr>
                                <td>{{ $group->id }}</td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <img src="{{ getMedia($group->avatar)}}" class="rounded-circle me-2" width="32" height="32">
                                        <a href="{{ url('group/'.$group->slug) }}">{{ $group->name }}</a>
                                    </div>
                                </td>
                                <td>
                                    @if($group->is_private === 0)
                                        <span class="badge bg-success">Public</span>
                                    @else
                                        <span class="badge bg-warning">Private</span>
                                    @endif
                                </td>
                                <td>
                                    @if($group->owner)
                                        <div class="d-flex align-items-center">
                                            <img src="{{ getMedia($group->owner->avatar) }}" class="rounded-circle me-2" width="24" height="24">
                                            <span>{{ $group->owner->name }}</span>
                                        </div>
                                    @else
                                        <span class="text-muted">No owner</span>
                                    @endif
                                </td>
                                <td>{{ $group->members_count ?? 0 }}</td>
                                <td>{{ $group->is_featured ? "Featured" : "Un-Featured" }}</td>
                                <td>{{ $group->created_at->format('M d, Y') }}</td>
                                <td>
                                    <div class="btn-group">
                                        <a href="{{ url('group/'.$group->slug) }}" class="btn btn-sm btn-info">
                                            <i class="bi bi-eye"></i>
                                        </a>
                                        <button type="button" class="btn btn-sm btn-warning" onclick='openEditModal(@json($group))'>
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm {{ $group->is_featured ? 'btn-success' : 'btn-secondary' }}" 
                                                onclick="toggleFeatured({{ $group->id }})" 
                                                title="{{ $group->is_featured ? 'Remove from featured' : 'Add to featured' }}">
                                            <i class="bi bi-star-fill"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-danger" onclick="deleteGroup({{ $group->id }})">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            @empty
                            <tr>
                                <td colspan="7" class="text-center">No groups found</td>
                            </tr>
                            @endforelse
                        </tbody>
                    </table>
                </div>
                <div class="paginatior mt-3">
                    {{ $groups->links('pagination::bootstrap-5') }}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Group Modal -->
<div class="modal fade" id="editGroupModal" tabindex="-1" aria-labelledby="editGroupModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editGroupModalLabel">Edit Group</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="editGroupForm" method="POST" enctype="multipart/form-data">
                    @csrf
                    @method('PUT')
                    <input type="hidden" id="editGroupId" name="id">
                    
                    <div class="mb-3">
                        <label for="editGroupName" class="form-label">Group Name</label>
                        <input type="text" class="form-control" id="editGroupName" name="name" minlength="3" maxlength="50">
                        <div class="invalid-feedback" id="nameError"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editGroupDescription" class="form-label">Description</label>
                        <textarea class="form-control" id="editGroupDescription" name="description" rows="3" minlength="10" maxlength="500"></textarea>
                        <div class="invalid-feedback" id="descriptionError"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editGroupPrivacy" class="form-label">Privacy</label>
                        <select class="form-select" id="editGroupPrivacy" name="privacy">
                            <option value="public">Public</option>
                            <option value="private">Private</option>
                            <option value="hidden">Hidden</option>
                        </select>
                        <div class="invalid-feedback" id="privacyError"></div>
                    </div>
                    
                    <div class="mb-3">
                        <label for="editGroupCategory" class="form-label">Category</label>
                        <select class="form-select" id="editGroupCategory" name="category_id">
                            <option value="">Select Category</option>
                            @foreach($categories as $category)
                                <option value="{{ $category->id }}">{{ $category->name }}</option>
                            @endforeach
                        </select>
                        <div class="invalid-feedback" id="categoryError"></div>
                    </div>

                    <div class="mb-3">
                        <label for="editGroupCoverImage" class="form-label">Cover Image</label>
                        <input type="file" class="form-control" id="editGroupCoverImage" name="cover_image" accept="image/jpeg,image/png,image/jpg">
                        <small class="text-muted">Max size: 2MB. Allowed formats: JPEG, PNG, JPG</small>
                        <div class="invalid-feedback" id="coverImageError"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" onclick="updateGroup()">Save changes</button>
            </div>
        </div>
    </div>
</div>

<script>
function openEditModal(group) {
    document.getElementById('editGroupId').value = group.id;
    document.getElementById('editGroupName').value = group.name;
    document.getElementById('editGroupDescription').value = group.description;
    document.getElementById('editGroupPrivacy').value = group.is_private ? 'private' : 'public';
    document.getElementById('editGroupCategory').value = group.category_id || '';
    
    // Clear any previous errors
    clearErrors();
    
    new bootstrap.Modal(document.getElementById('editGroupModal')).show();
}

function clearErrors() {
    const errorElements = document.querySelectorAll('.invalid-feedback');
    const formElements = document.querySelectorAll('.form-control, .form-select');
    errorElements.forEach(element => element.textContent = '');
    formElements.forEach(element => element.classList.remove('is-invalid'));
}

function showErrors(errors) {
    Object.keys(errors).forEach(field => {
        showFieldError(field, errors[field][0]);
    });
}

function showFieldError(field, message) {
    const errorElement = document.getElementById(`${field}Error`);
    const inputElement = document.getElementById(`editGroup${field.charAt(0).toUpperCase() + field.slice(1)}`);
    if (errorElement && inputElement) {
        errorElement.textContent = message;
        inputElement.classList.add('is-invalid');
    }
}

function updateGroup() {
    clearErrors();
    
    const form = document.getElementById('editGroupForm');
    const formData = new FormData(form);
    const groupId = document.getElementById('editGroupId').value;
    
    // Basic form validation
    const name = document.getElementById('editGroupName').value;
    const description = document.getElementById('editGroupDescription').value;
    const privacy = document.getElementById('editGroupPrivacy').value;
    const category = document.getElementById('editGroupCategory').value;
    
    let hasErrors = false;
    if (name.length < 3 || name.length > 50) {
        showFieldError('name', 'Group name must be between 3 and 50 characters');
        hasErrors = true;
    }
    if (description.length < 10 || description.length > 500) {
        showFieldError('description', 'Description must be between 10 and 500 characters');
        hasErrors = true;
    }
    if (!privacy) {
        showFieldError('privacy', 'Please select a privacy setting');
        hasErrors = true;
    }
    if (!category) {
        showFieldError('category', 'Please select a category');
        hasErrors = true;
    }
    
    if (hasErrors) return;
    
    // Convert privacy value to boolean for backend
    formData.set('is_private', privacy === 'private' ? 1 : 0);
    
    // File validation
    const coverImage = document.getElementById('editGroupCoverImage').files[0];
    if (coverImage) {
        if (coverImage.size > 2 * 1024 * 1024) { // 2MB
            showFieldError('coverImage', 'Cover image must not exceed 2MB');
            return;
        }
        if (!['image/jpeg', 'image/png', 'image/jpg'].includes(coverImage.type)) {
            showFieldError('coverImage', 'Only JPEG, PNG and JPG formats are allowed');
            return;
        }
    }
    
    // Show loading state
    const saveButton = document.querySelector('#editGroupModal .btn-primary');
    const originalText = saveButton.innerHTML;
    saveButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...';
    saveButton.disabled = true;
    
    fetch(`/admin/groups/${groupId}`, {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            Swal.fire({
                title: 'Success!',
                text: data.message || 'Group updated successfully',
                icon: 'success',
                timer: 1500,
                showConfirmButton: false
            }).then(() => {
                window.location.reload();
            });
        } else {
            if (data.errors) {
                showErrors(data.errors);
            }
            Swal.fire({
                title: 'Error!',
                text: data.message || 'Failed to update group',
                icon: 'error'
            });
        }
    })
    .catch(error => {
        console.error('Error:', error);
        Swal.fire({
            title: 'Error!',
            text: 'Something went wrong while updating the group',
            icon: 'error'
        });
    })
    .finally(() => {
        // Restore button state
        saveButton.innerHTML = originalText;
        saveButton.disabled = false;
    });
}

function toggleFeatured(groupId) {
        fetch(`/admin/groups/${groupId}/toggle-featured`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    title: 'Success!',
                    text: data.message,
                    icon: 'success',
                    timer: 1500,
                    showConfirmButton: false
                }).then(() => {
                    window.location.reload();
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire(
                'Error!',
                'Something went wrong while updating featured status.',
                'error'
            );
        });
    }

    function deleteGroup(groupId) {
        Swal.fire({
            title: 'Are you sure?',
            text: 'You want to delete this group? This action cannot be undone.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete it!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(`/admin/groups/destory/${groupId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire(
                            'Deleted!',
                            'The group has been deleted.',
                            'success'
                        ).then(() => {
                            window.location.reload();
                        });
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire(
                        'Error!',
                        'Something went wrong while deleting the group.',
                        'error'
                    );
                });
            }
        });
    }
</script>
@endsection