<?php

namespace App\Filament\Resources\Roles\Schemas;

use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Components\Fieldset;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Schema;
use Spatie\Permission\Models\Permission;

class RoleForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->required()->columnSpanFull()->unique(),
                Hidden::make('guard_name')
                    ->default('web'),
                Fieldset::make('permissions')
                    ->label('Permissions')
                    ->schema([
                        Grid::make()
                            ->columns(5)
                            ->schema([
                                CheckboxList::make('users_permissions')
                                    ->options(function () {
                                        return Permission::where('name', 'like', '%user%')
                                            ->pluck('name', 'name')
                                            ->toArray();
                                    })
                                    ->bulkToggleable()
                                    ->label('Users')
                                    ->gridDirection('col')
                                    ->columns(1)
                                    ->afterStateHydrated(function ($component, $state) {
                                        $record = $component->getLivewire()->getRecord();

                                        if ($record) {
                                            $component->state(
                                                $record->permissions()
                                                    ->where('name', 'like', '%user%')
                                                    ->pluck('name')
                                                    ->toArray()
                                            );
                                        }
                                    })
                            ])->columnSpanFull()
                    ])
                    ->columnSpanFull()
            ]);
    }
}
