@extends('layouts.app')

@section('content')
    <x-common.page-breadcrumb pageTitle="{{ isset($role) ? 'Edit Role' : 'Tambah Role' }}" />

    <div class="mx-auto max-w-7xl">
        <div class="rounded-2xl border border-gray-200 bg-white dark:border-gray-800 dark:bg-white/[0.03]">
            <div class="border-b border-gray-200 px-5 py-4 dark:border-gray-800">
                <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                    <div>
                        <h3 class="text-lg font-semibold text-gray-800 dark:text-white/90">
                            {{ isset($role) ? 'Edit Role' : 'Form Role Baru' }}
                        </h3>
                        <p class="mt-1 text-sm text-gray-500 dark:text-gray-400">
                            Hak akses dikelompokkan berdasarkan kategori agar lebih mudah dikelola.
                        </p>
                    </div>

                    @if(isset($role))
                        <div class="rounded-xl bg-gray-50 px-4 py-2 text-sm text-gray-600 dark:bg-gray-800 dark:text-gray-300">
                            Role aktif:
                            <span class="font-semibold text-gray-900 dark:text-white">{{ $role->name }}</span>
                        </div>
                    @endif
                </div>
            </div>

            <form action="{{ isset($role) ? route('roles.update', $role) : route('roles.store') }}" method="POST">
                @csrf

                @if(isset($role))
                    @method('PUT')
                @endif

                <div class="space-y-6 p-5">
                    <div class="grid grid-cols-1 gap-5 lg:grid-cols-3">
                        <div class="lg:col-span-1">
                            <x-form.input
                                name="name"
                                label="Nama Role"
                                placeholder="Contoh: administrasi"
                                :value="old('name', $role->name ?? '')"
                                :required="true"
                                :readonly="(isset($role) && $role->name === 'developer')"
                            />

                            @if(isset($role) && $role->name === 'developer')
                                <p class="mt-2 text-xs text-amber-600 dark:text-amber-400">
                                    Role developer tidak bisa diubah namanya, tetapi permission tetap bisa dicek.
                                </p>
                            @endif
                        </div>

                        <div class="rounded-2xl border border-blue-100 bg-blue-50 p-4 text-sm text-blue-700 dark:border-blue-500/20 dark:bg-blue-500/10 dark:text-blue-300 lg:col-span-2">
                            <div class="font-semibold">Tips Pengaturan Role</div>
                            <p class="mt-1">
                                Gunakan tombol <strong>Pilih Semua</strong> pada setiap kategori untuk memberi akses cepat.
                                Gunakan pencarian untuk menemukan permission tertentu seperti invoice, pembayaran, surat jalan, atau laporan.
                            </p>
                        </div>
                    </div>

                    <div
                        x-data="{
                            search: '',
                            selectedCount() {
                                return document.querySelectorAll('input[name=&quot;permissions[]&quot;]:checked').length;
                            },
                            totalCount() {
                                return document.querySelectorAll('input[name=&quot;permissions[]&quot;]').length;
                            },
                            matches(text) {
                                return (text || '').toLowerCase().includes(this.search.toLowerCase());
                            },
                            toggleGroup(groupId, checked) {
                                document.querySelectorAll('[data-group=' + groupId + '] input[name=&quot;permissions[]&quot;]').forEach(el => {
                                    if (!el.disabled) el.checked = checked;
                                });
                            }
                        }"
                    >
                        <div class="sticky top-0 z-10 mb-5 rounded-2xl border border-gray-200 bg-white/95 p-4 shadow-sm backdrop-blur dark:border-gray-800 dark:bg-gray-900/95">
                            <div class="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
                                <div>
                                    <label class="block text-sm font-semibold text-gray-800 dark:text-white/90">
                                        Hak Akses / Permissions
                                    </label>
                                    <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                        Terpilih:
                                        <span class="font-semibold text-brand-600" x-text="selectedCount()"></span>
                                        /
                                        <span x-text="totalCount()"></span>
                                        permission
                                    </p>
                                </div>

                                <div class="flex flex-col gap-2 sm:flex-row sm:items-center">
                                    <input
                                        x-model="search"
                                        type="text"
                                        placeholder="Cari permission / kategori..."
                                        class="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm focus:border-brand-500 focus:ring-brand-500 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 sm:w-80"
                                    >

                                    <button
                                        type="button"
                                        @click="document.querySelectorAll('input[name=&quot;permissions[]&quot;]').forEach(el => el.checked = true)"
                                        class="rounded-lg bg-gray-900 px-3 py-2 text-xs font-semibold text-white hover:bg-gray-800"
                                    >
                                        Pilih Semua
                                    </button>

                                    <button
                                        type="button"
                                        @click="document.querySelectorAll('input[name=&quot;permissions[]&quot;]').forEach(el => el.checked = false)"
                                        class="rounded-lg border border-gray-300 bg-white px-3 py-2 text-xs font-semibold text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
                                    >
                                        Kosongkan
                                    </button>
                                </div>
                            </div>
                        </div>

                        <div class="grid grid-cols-1 gap-5 xl:grid-cols-2">
                            @foreach($groupedPermissions as $groupName => $permissions)
                                @php
                                    $groupId = 'permission_group_' . $loop->index;
                                    $checkedCount = isset($rolePermissions)
                                        ? $permissions->filter(fn($permission) => in_array($permission->name, old('permissions', $rolePermissions ?? [])))->count()
                                        : 0;
                                @endphp

                                <section
                                    data-group="{{ $groupId }}"
                                    x-show="!search || matches(@js($groupName)) || Array.from($el.querySelectorAll('[data-permission-name]')).some(el => matches(el.dataset.permissionName))"
                                    class="rounded-2xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900"
                                >
                                    <div class="border-b border-gray-200 p-4 dark:border-gray-800">
                                        <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
                                            <div>
                                                <h4 class="font-bold text-gray-800 dark:text-white/90">
                                                    {{ $groupName }}
                                                </h4>
                                                <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
                                                    {{ $permissions->count() }} permission
                                                    @if($checkedCount > 0)
                                                        · {{ $checkedCount }} sudah aktif
                                                    @endif
                                                </p>
                                            </div>

                                            <div class="flex items-center gap-2">
                                                <button
                                                    type="button"
                                                    @click="toggleGroup('{{ $groupId }}', true)"
                                                    class="rounded-lg bg-brand-500 px-3 py-1.5 text-xs font-semibold text-white hover:bg-brand-600"
                                                >
                                                    Pilih Semua
                                                </button>

                                                <button
                                                    type="button"
                                                    @click="toggleGroup('{{ $groupId }}', false)"
                                                    class="rounded-lg border border-gray-300 bg-white px-3 py-1.5 text-xs font-semibold text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700"
                                                >
                                                    Hapus
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="grid grid-cols-1 gap-2 p-4 sm:grid-cols-2">
                                        @foreach($permissions as $permission)
                                            @php
                                                $checkedPermissions = old('permissions', $rolePermissions ?? []);
                                                $isChecked = in_array($permission->name, $checkedPermissions);
                                                $label = $permissionLabels[$permission->name] ?? ucwords(str_replace(['_', '-'], ' ', $permission->name));
                                            @endphp

                                            <label
                                                data-permission-name="{{ $permission->name }}"
                                                x-show="!search || matches(@js($permission->name)) || matches(@js($groupName))"
                                                class="group flex cursor-pointer items-start gap-3 rounded-xl border border-gray-200 p-3 transition hover:border-brand-300 hover:bg-brand-50/50 dark:border-gray-700 dark:hover:border-brand-500/40 dark:hover:bg-brand-500/10"
                                            >
                                                <input
                                                    type="checkbox"
                                                    name="permissions[]"
                                                    value="{{ $permission->name }}"
                                                    class="mt-0.5 h-4 w-4 rounded border-gray-300 text-brand-500 focus:ring-brand-500/20 dark:border-gray-600 dark:bg-gray-800 dark:ring-offset-gray-900"
                                                    @checked($isChecked)
                                                >

                                                <span class="min-w-0">
                                                    <span class="block text-sm font-semibold text-gray-700 group-hover:text-brand-700 dark:text-gray-300 dark:group-hover:text-brand-300">
                                                        {{ $label }}
                                                    </span>
                                                    <span class="mt-0.5 block break-all text-[11px] text-gray-400">
                                                        {{ $permission->name }}
                                                    </span>
                                                </span>
                                            </label>
                                        @endforeach
                                    </div>
                                </section>
                            @endforeach
                        </div>
                    </div>
                </div>

                <div class="flex items-center justify-end gap-3 border-t border-gray-200 px-5 py-4 dark:border-gray-800">
                    <a href="{{ route('roles.index') }}"
                       class="rounded-lg border border-gray-300 bg-white px-4 py-2.5 text-sm font-medium text-gray-700 hover:bg-gray-50 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700">
                        Batal
                    </a>

                    <button type="submit"
                            class="rounded-lg bg-brand-500 px-4 py-2.5 text-sm font-medium text-white hover:bg-brand-600">
                        Simpan Role
                    </button>
                </div>
            </form>
        </div>
    </div>
@endsection
