@extends('admin-layouts.master')

@section('title', 'Edit Role - ' . $role->display_name)

@section('content')
<style>
:root {
    --primary-color: #4e73df;
    --success-color: #1cc88a;
    --info-color: #36b9cc;
    --warning-color: #f6c23e;
    --danger-color: #e74a3b;
    --secondary-color: #858796;
    --light-bg: #f8f9fc;
    --border-color: #e3e6f0;
    --text-dark: #5a5c69;
}

.card {
    border-radius: 10px;
    border: none;
    box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15);
    transition: all 0.3s ease;
}

.card:hover {
    box-shadow: 0 0.3rem 2rem 0 rgba(58, 59, 69, 0.2);
}

.form-control {
    border-radius: 8px;
    border: 1px solid var(--border-color);
    padding: 0.75rem 1rem;
    font-size: 0.9rem;
    transition: all 0.3s ease;
}

.form-control:focus {
    border-color: var(--primary-color);
    box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.15);
}

.custom-control-label {
    cursor: pointer;
    font-size: 0.9rem;
}

.custom-control-input:checked ~ .custom-control-label::before {
    background-color: var(--primary-color);
    border-color: var(--primary-color);
}

.transition-icon {
    transition: transform 0.3s ease;
    font-size: 0.85rem;
}

.btn-link:not(.collapsed) .transition-icon {
    transform: rotate(90deg);
}

.accordion .card-header {
    background-color: transparent;
}

.btn-link {
    color: var(--text-dark) !important;
    text-decoration: none;
}

.btn-link:hover {
    color: var(--primary-color) !important;
}

.badge {
    font-size: 0.75rem;
    font-weight: 500;
    padding: 0.35rem 0.65rem;
    border-radius: 6px;
}

.border-right {
    border-right: 1px solid var(--border-color) !important;
}

.form-label {
    font-size: 0.8rem;
    letter-spacing: 0.3px;
    text-transform: uppercase;
    margin-bottom: 0.5rem;
    color: var(--text-dark);
    font-weight: 600;
}

.permission-item {
    background-color: #e7f1ff;
    color: #004085;
    padding: 4px 10px;
    border-radius: 12px;
    font-size: 0.75rem;
    margin: 2px;
    display: inline-block;
}

.role-icon {
    flex-shrink: 0;
}

.alert {
    border-radius: 8px;
    border: none;
}

.modal-content {
    border-radius: 10px;
}

.changes-section {
    border-left: 4px solid #007bff;
    padding-left: 20px;
    margin-bottom: 25px;
}

.changes-section.added {
    border-color: var(--success-color);
}

.changes-section.removed {
    border-color: var(--danger-color);
}

.changes-section.modified {
    border-color: var(--warning-color);
}

.btn {
    border-radius: 8px;
    font-weight: 500;
    padding: 0.625rem 1.25rem;
    transition: all 0.3s ease;
}

.btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}

.card-header {
    border-bottom: 1px solid var(--border-color);
    background-color: white;
}

.stat-box {
    background: linear-gradient(135deg, var(--light-bg) 0%, #ffffff 100%);
    border-radius: 8px;
    padding: 1rem;
}
</style>

<div class="container-fluid">
    <!-- Header Section -->
    <div class="row mb-4">
        <div class="col-md-12">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <!-- Role Icon -->
                    <div class="role-icon mr-3">
                        @if($role->name === 'superadmin')
                            <div class="bg-danger rounded-circle d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                                <i class="fas fa-crown text-white fa-lg"></i>
                            </div>
                        @elseif($role->name === 'manager')
                            <div class="bg-warning rounded-circle d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                                <i class="fas fa-user-tie text-white fa-lg"></i>
                            </div>
                        @else
                            <div class="bg-primary rounded-circle d-flex align-items-center justify-content-center" style="width: 50px; height: 50px;">
                                <i class="fas fa-user-shield text-white fa-lg"></i>
                            </div>
                        @endif
                    </div>
                    <div>
                        <h2 class="mb-1 text-dark font-weight-bold">Edit Role</h2>
                        <p class="text-muted mb-0">Modify role information and permissions for {{ $role->display_name }}</p>
                    </div>
                </div>
                <div>
                    <a href="{{ route('roles.show', $role) }}" class="btn btn-info btn-sm shadow-sm mr-2">
                        <i class="fas fa-eye mr-1"></i> View Details
                    </a>
                    <a href="{{ route('roles.index') }}" class="btn btn-secondary btn-sm shadow-sm">
                        <i class="fas fa-arrow-left mr-1"></i> Back
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Alert Messages -->
    @if(session('success'))
    <div class="row mb-3">
        <div class="col-md-12">
            <div class="alert alert-success alert-dismissible fade show shadow-sm" role="alert">
                <i class="fas fa-check-circle mr-2"></i>
                {{ session('success') }}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        </div>
    </div>
    @endif

    @if($errors->any())
    <div class="row mb-3">
        <div class="col-md-12">
            <div class="alert alert-danger alert-dismissible fade show shadow-sm" role="alert">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <strong>Please fix the following errors:</strong>
                <ul class="mb-0 mt-2">
                    @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            </div>
        </div>
    </div>
    @endif

    <form action="{{ route('roles.update', $role) }}" method="POST" id="roleForm">
        @csrf
        @method('PUT')
        <div class="row">
            <!-- Role Information Card -->
            <div class="col-md-4 mb-4">
                <div class="card h-100">
                    <div class="card-header py-3">
                        <h6 class="mb-0 text-dark font-weight-bold">
                            <i class="fas fa-info-circle text-primary mr-2"></i>
                            Role Information
                        </h6>
                    </div>
                    <div class="card-body">
                        <!-- Display Name -->
                        <div class="form-group">
                            <label for="name" class="form-label">Display Name <span class="text-danger">*</span></label>
                            <input type="text"
                                   class="form-control @error('name') is-invalid @enderror"
                                   id="name"
                                   name="name"
                                   value="{{ old('name', $role->name) }}"
                                   placeholder="e.g., admin"
                                   required>
                            <small class="form-text text-muted">Human-readable name for display</small>
                            @error('name')
                                <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        <!-- Role Statistics -->
                        <div class="mt-4 stat-box">
                            <div class="row text-center">
                                <div class="col-6">
                                    <div class="border-right">
                                        <h5 class="mb-1 text-primary font-weight-bold">{{ $role->permissions()->count() }}</h5>
                                        <small class="text-muted">Permissions</small>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <h5 class="mb-1 text-info font-weight-bold">{{ $role->users()->count() }}</h5>
                                    <small class="text-muted">Users</small>
                                </div>
                            </div>
                        </div>

                        <!-- Selected Permissions Summary -->
                        <div class="mt-4 p-3 bg-light rounded">
                            <div class="d-flex justify-content-between align-items-center mb-2">
                                <span class="font-weight-semibold text-dark">Selected Permissions</span>
                                <span class="badge badge-primary" id="selectedCount">{{ count($rolePermissions) }}</span>
                            </div>
                            <div id="selectedPermissionsList" class="small">
                                @if(count($rolePermissions) > 0)
                                    @php
                                        $rolePerms = $role->permissions()->get();
                                    @endphp
                                    @foreach($rolePerms->take(3) as $permission)
                                        <span class="permission-item">{{ $permission->display_name ?? $permission->name }}</span>
                                    @endforeach
                                    @if($rolePerms->count() > 3)
                                        <span class="text-muted">... and {{ $rolePerms->count() - 3 }} more</span>
                                    @endif
                                @else
                                    <span class="text-muted">No permissions selected</span>
                                @endif
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Permissions Card -->
            <div class="col-md-8 mb-4">
                <div class="card h-100">
                    <div class="card-header py-3">
                        <div class="d-flex justify-content-between align-items-center">
                            <h6 class="mb-0 text-dark font-weight-bold">
                                <i class="fas fa-key text-primary mr-2"></i>
                                Assign Permissions
                            </h6>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-primary" id="selectAll">
                                    <i class="fas fa-check-double mr-1"></i> Select All
                                </button>
                                <button type="button" class="btn btn-sm btn-outline-secondary ml-1" id="clearAll">
                                    <i class="fas fa-times mr-1"></i> Clear All
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        @if($groupedPermissions->count() > 0)
                        <div class="accordion" id="permissionsAccordion">
                            @foreach($groupedPermissions as $group => $groupPermissions)
                            <div class="border-bottom">
                                <div class="card-header bg-white py-3" id="heading{{ $loop->index }}">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <button class="btn btn-link text-left p-0 collapsed"
                                                type="button"
                                                data-toggle="collapse"
                                                data-target="#collapse{{ $loop->index }}"
                                                aria-expanded="false">
                                            <h6 class="mb-0 text-dark font-weight-semibold">
                                                <i class="fas fa-chevron-right mr-2 transition-icon"></i>
                                                {{ ucfirst($group) }}
                                            </h6>
                                        </button>
                                        <div class="d-flex align-items-center">
                                            @php
                                                $groupPermissionIds = $groupPermissions->pluck('id')->toArray();
                                                $selectedInGroup = array_intersect($rolePermissions, $groupPermissionIds);
                                                $selectedCount = count($selectedInGroup);
                                                $totalCount = count($groupPermissionIds);
                                            @endphp
                                            <span class="badge badge-light mr-2">
                                                {{ $selectedCount }}/{{ $totalCount }} selected
                                            </span>
                                            <div class="custom-control custom-checkbox">
                                                <input type="checkbox"
                                                       class="custom-control-input group-checkbox"
                                                       id="group{{ $loop->index }}"
                                                       data-group="{{ $loop->index }}"
                                                       {{ $selectedCount === $totalCount ? 'checked' : '' }}>
                                                <label class="custom-control-label" for="group{{ $loop->index }}">
                                                    <small>Select All</small>
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                <div id="collapse{{ $loop->index }}"
                                     class="collapse {{ $selectedCount > 0 ? 'show' : '' }}"
                                     data-parent="#permissionsAccordion">
                                    <div class="card-body pt-0 pb-3">
                                        <div class="row">
                                            @foreach($groupPermissions as $permission)
                                            <div class="col-md-6 mb-2">
                                                <div class="custom-control custom-checkbox">
                                                    <input type="checkbox"
                                                           class="custom-control-input permission-checkbox"
                                                           id="permission{{ $permission->id }}"
                                                           name="permissions[]"
                                                           value="{{ $permission->id }}"
                                                           data-group="{{ $loop->parent->index }}"
                                                           {{ in_array($permission->id, $rolePermissions) ? 'checked' : '' }}>
                                                    <label class="custom-control-label" for="permission{{ $permission->id }}">
                                                        <span class="font-weight-medium">{{ $permission->display_name ?? $permission->name }}</span>
                                                        @if($permission->description)
                                                        <br><small class="text-muted">{{ $permission->description }}</small>
                                                        @endif
                                                    </label>
                                                </div>
                                            </div>
                                            @endforeach
                                        </div>
                                    </div>
                                </div>
                            </div>
                            @endforeach
                        </div>
                        @else
                        <div class="text-center py-5">
                            <i class="fas fa-key fa-3x text-muted mb-3"></i>
                            <h5 class="text-muted">No Permissions Available</h5>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
        </div>

        <!-- Action Buttons -->
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <a href="{{ route('roles.index') }}" class="btn btn-light px-4">
                                <i class="fas fa-times mr-1"></i> Cancel
                            </a>
                            <button type="submit" class="btn btn-primary px-4" id="submitBtn">
                                <i class="fas fa-save mr-1"></i> Update Role
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

@push('scripts')
<script>
$(document).ready(function() {
    const originalPermissions = @json($rolePermissions);

    // Set indeterminate checkboxes
    $('.group-checkbox').each(function() {
        const groupIndex = $(this).data('group');
        const groupPermissions = $(`.permission-checkbox[data-group="${groupIndex}"]`);
        const checkedInGroup = groupPermissions.filter(':checked').length;
        const totalInGroup = groupPermissions.length;

        if (checkedInGroup > 0 && checkedInGroup < totalInGroup) {
            this.indeterminate = true;
        }
    });

    // Update selected permissions count and list
    function updateSelectedPermissions() {
        const checked = $('.permission-checkbox:checked');
        const count = checked.length;
        $('#selectedCount').text(count);

        if (count === 0) {
            $('#selectedPermissionsList').html('<span class="text-muted">No permissions selected</span>');
        } else {
            let html = '';
            const displayCount = Math.min(count, 3);

            checked.slice(0, displayCount).each(function() {
                const label = $(this).next('label').find('span').first().text();
                html += '<span class="permission-item">' + label + '</span>';
            });

            if (count > 3) {
                html += '<span class="text-muted">... and ' + (count - 3) + ' more</span>';
            }

            $('#selectedPermissionsList').html(html);
        }
    }

    // Handle permission checkbox changes
    $('.permission-checkbox').change(function() {
        updateSelectedPermissions();

        // Update group checkbox state
        const groupIndex = $(this).data('group');
        const groupPermissions = $(`.permission-checkbox[data-group="${groupIndex}"]`);
        const checkedInGroup = groupPermissions.filter(':checked').length;
        const totalInGroup = groupPermissions.length;

        const groupCheckbox = $(`#group${groupIndex}`);
        const groupBadge = groupCheckbox.closest('.d-flex').find('.badge');

        groupBadge.text(`${checkedInGroup}/${totalInGroup} selected`);

        if (checkedInGroup === 0) {
            groupCheckbox.prop('indeterminate', false);
            groupCheckbox.prop('checked', false);
        } else if (checkedInGroup === totalInGroup) {
            groupCheckbox.prop('indeterminate', false);
            groupCheckbox.prop('checked', true);
        } else {
            groupCheckbox.prop('indeterminate', true);
        }
    });

    // Handle group checkbox changes
    $('.group-checkbox').change(function() {
        const groupIndex = $(this).data('group');
        const isChecked = $(this).prop('checked');

        $(`.permission-checkbox[data-group="${groupIndex}"]`).prop('checked', isChecked);
        updateSelectedPermissions();

        // Update badge
        const groupPermissions = $(`.permission-checkbox[data-group="${groupIndex}"]`);
        const totalInGroup = groupPermissions.length;
        const checkedInGroup = isChecked ? totalInGroup : 0;
        const groupBadge = $(this).closest('.d-flex').find('.badge');
        groupBadge.text(`${checkedInGroup}/${totalInGroup} selected`);

        // Remove indeterminate state
        this.indeterminate = false;
    });

    // Select all permissions
    $('#selectAll').click(function() {
        $('.permission-checkbox, .group-checkbox').prop('checked', true);
        $('.group-checkbox').prop('indeterminate', false);
        updateSelectedPermissions();

        // Update all badges
        $('.group-checkbox').each(function() {
            const groupIndex = $(this).data('group');
            const totalInGroup = $(`.permission-checkbox[data-group="${groupIndex}"]`).length;
            const groupBadge = $(this).closest('.d-flex').find('.badge');
            groupBadge.text(`${totalInGroup}/${totalInGroup} selected`);
        });
    });

    // Clear all permissions
    $('#clearAll').click(function() {
        $('.permission-checkbox, .group-checkbox').prop('checked', false);
        $('.group-checkbox').prop('indeterminate', false);
        updateSelectedPermissions();

        // Update all badges
        $('.group-checkbox').each(function() {
            const groupIndex = $(this).data('group');
            const totalInGroup = $(`.permission-checkbox[data-group="${groupIndex}"]`).length;
            const groupBadge = $(this).closest('.d-flex').find('.badge');
            groupBadge.text(`0/${totalInGroup} selected`);
        });
    });

    // Form validation
    $('#roleForm').submit(function(e) {
        // Add loading state to submit button
        $('#submitBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Updating...');
    });

    // Initialize selected permissions on page load
    updateSelectedPermissions();

    // Auto hide alerts after 5 seconds
    setTimeout(function() {
        $('.alert').fadeOut('slow');
    }, 5000);
});
</script>
@endpush
@endsection
