@extends('layouts.app')

@section('title', 'Edit role')
@section('heading', 'Edit role: '.$role->display_name)

@section('content')
    @php
        $selectedIds = $role->permissions->pluck('id')->map(fn ($id) => (int) $id)->all();
    @endphp
    <div
        class="space-y-6"
        @unless($isSystem)
        x-data="{
            search: '',
            permVisible(p) {
                const q = (this.search || '').trim().toLowerCase();
                if (!q) return true;
                return (p.name || '').toLowerCase().includes(q) || (p.d || '').toLowerCase().includes(q);
            },
            groupVisible(items) {
                if (!this.search.trim()) return true;
                return items.some(p => this.permVisible(p));
            },
            setAll(root, on) {
                if (!root) return;
                root.querySelectorAll('input[name=\'permission_ids[]\']').forEach(c => { c.checked = on; });
            },
            countSelected(root) {
                if (!root) return 0;
                return root.querySelectorAll('input[name=\'permission_ids[]\']:checked').length;
            },
            countAll(root) {
                if (!root) return 0;
                return root.querySelectorAll('input[name=\'permission_ids[]\']').length;
            }
        }"
        @endunless
    >
        <a href="{{ route('tenant-roles.index') }}" class="inline-flex items-center gap-2 text-sm font-medium text-slate-600 hover:text-slate-900">
            <i class="bi bi-arrow-left"></i>
            Back to roles
        </a>

        <x-card>
            @if($isSystem)
                <p class="mb-6 flex gap-2 rounded-xl border border-sky-200 bg-sky-50 px-4 py-3 text-sm text-sky-900">
                    <i class="bi bi-info-circle mt-0.5 shrink-0 text-sky-600"></i>
                    <span>This is a <strong>system</strong> role. Permission sets are updated when you run <code class="rounded bg-white px-1.5 py-0.5 font-mono text-xs text-slate-800 shadow-sm">php artisan hrms:reset-permissions</code>. You can still change the display name and description below.</span>
                </p>
            @endif
            <form method="post" action="{{ route('tenant-roles.update', $role) }}" class="space-y-6">
                @csrf
                @method('PUT')
                <div class="mb-6 border-b border-slate-100 pb-4">
                    <h2 class="text-lg font-semibold text-slate-900">Role details</h2>
                </div>
                <div class="grid gap-6 sm:grid-cols-2 max-w-3xl">
                    <div>
                        <label class="mb-1.5 block text-sm font-medium text-slate-800">Slug</label>
                        <input type="text" value="{{ $role->name }}" readonly class="w-full cursor-not-allowed rounded-xl border border-slate-200 bg-slate-50 px-4 py-2.5 font-mono text-sm text-slate-600" />
                    </div>
                    <div></div>
                    <div class="sm:col-span-2">
                        <label class="mb-1.5 block text-sm font-medium text-slate-800">Display name <span class="text-red-500">*</span></label>
                        <input type="text" name="display_name" value="{{ old('display_name', $role->display_name) }}" required class="w-full rounded-xl border border-slate-200 px-4 py-2.5 text-sm focus:border-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-200" />
                    </div>
                    <div class="sm:col-span-2">
                        <label class="mb-1.5 block text-sm font-medium text-slate-800">Description <span class="text-xs text-slate-400">(optional)</span></label>
                        <textarea name="description" rows="2" class="w-full rounded-xl border border-slate-200 px-4 py-2.5 text-sm focus:border-slate-400 focus:outline-none focus:ring-2 focus:ring-slate-200">{{ old('description', $role->description) }}</textarea>
                    </div>
                </div>

                @if($isSystem)
                    <div class="mt-6 border-t border-slate-100 pt-6">
                        <h2 class="mb-3 text-lg font-semibold text-slate-900">Current permissions</h2>
                        <p class="mb-4 text-sm text-slate-500">Grouped for readability. To change the underlying set, use the reset command above.</p>
                        <div class="space-y-3">
                            @foreach($roleGroups as $g)
                                @if(empty($g['items']))
                                    @continue
                                @endif
                                <div class="overflow-hidden rounded-xl border border-slate-200">
                                    <div class="flex items-center gap-2 border-b border-slate-100 bg-slate-50 px-4 py-2.5 text-sm font-semibold text-slate-800">
                                        <i class="bi {{ $g['icon'] }} text-indigo-600"></i>
                                        {{ $g['label'] }}
                                        <span class="ml-auto text-xs font-normal text-slate-500">{{ count($g['items']) }}</span>
                                    </div>
                                    <ul class="grid gap-0.5 p-2 sm:grid-cols-2 sm:p-3">
                                        @foreach($g['items'] as $item)
                                            <li class="rounded-lg px-2.5 py-1.5 text-sm text-slate-700">
                                                <span class="font-medium text-slate-900">{{ $item['d'] }}</span>
                                                <span class="mt-0.5 block font-mono text-xs text-slate-500">{{ $item['name'] }}</span>
                                            </li>
                                        @endforeach
                                    </ul>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @else
                    <div class="mt-6 border-t border-slate-100 pt-6">
                        <div class="mb-4 flex flex-col gap-4 sm:flex-row sm:items-end sm:justify-between">
                            <div>
                                <h2 class="text-lg font-semibold text-slate-900">Permissions</h2>
                                <p class="mt-1 text-sm text-slate-500">Adjust what this role can access.</p>
                            </div>
                            <div class="relative w-full sm:max-w-sm">
                                <i class="bi bi-search pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"></i>
                                <input
                                    type="search"
                                    x-model="search"
                                    placeholder="Search…"
                                    class="w-full rounded-xl border border-slate-200 py-2.5 pl-10 pr-3 text-sm"
                                    autocomplete="off"
                                />
                            </div>
                        </div>
                        <div class="space-y-3">
                            @foreach($roleGroups as $g)
                                <div
                                    class="overflow-hidden rounded-xl border border-slate-200 bg-slate-50/40"
                                    x-show="groupVisible(@js($g['items']))"
                                >
                                    <div class="flex flex-wrap items-center justify-between gap-2 border-b border-slate-200/80 bg-white px-4 py-3">
                                        <div class="flex min-w-0 items-center gap-2.5">
                                            <span class="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-indigo-100 text-indigo-700">
                                                <i class="bi {{ $g['icon'] }} text-lg"></i>
                                            </span>
                                            <h3 class="text-sm font-semibold text-slate-900">{{ $g['label'] }}</h3>
                                        </div>
                                        <div class="flex items-center gap-2">
                                            <span class="hidden text-xs text-slate-500 sm:inline" x-show="!search.trim()" x-text="countSelected($refs.pg_{{ $g['key'] }}) + ' / ' + countAll($refs.pg_{{ $g['key'] }}) + ' selected'"></span>
                                            <button type="button" class="rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-medium" @click="setAll($refs.pg_{{ $g['key'] }}, true)">All</button>
                                            <button type="button" class="rounded-lg border border-slate-200 bg-white px-2.5 py-1.5 text-xs font-medium" @click="setAll($refs.pg_{{ $g['key'] }}, false)">None</button>
                                        </div>
                                    </div>
                                    <div class="bg-white p-3 sm:p-4" x-ref="pg_{{ $g['key'] }}">
                                        <ul class="grid gap-0.5 sm:grid-cols-2">
                                            @foreach($g['items'] as $item)
                                                <li class="list-none" x-show="permVisible(@js($item))">
                                                    <label class="flex cursor-pointer items-start gap-3 rounded-lg p-2.5 hover:bg-slate-50 has-[:checked]:bg-indigo-50/80">
                                                        <input
                                                            type="checkbox"
                                                            name="permission_ids[]"
                                                            value="{{ $item['id'] }}"
                                                            @checked(in_array($item['id'], old('permission_ids', $selectedIds), true))
                                                            class="mt-0.5 h-4 w-4 rounded border-slate-300 text-indigo-600"
                                                        />
                                                        <span class="min-w-0">
                                                            <span class="block text-sm font-medium text-slate-900">{{ $item['d'] }}</span>
                                                            <span class="mt-0.5 block break-all font-mono text-xs text-slate-500">{{ $item['name'] }}</span>
                                                        </span>
                                                    </label>
                                                </li>
                                            @endforeach
                                        </ul>
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif

                <div class="flex flex-wrap gap-3 border-t border-slate-200 pt-4">
                    <button type="submit" class="inline-flex items-center gap-2 rounded-xl bg-slate-900 px-5 py-2.5 text-sm font-semibold text-white hover:bg-slate-800">
                        <i class="bi bi-check-lg"></i>
                        Save changes
                    </button>
                    <a href="{{ route('tenant-roles.index') }}" class="rounded-xl border border-slate-200 px-4 py-2.5 text-sm font-medium text-slate-800 hover:bg-slate-50">Cancel</a>
                </div>
            </form>
        </x-card>
    </div>
@endsection
