<?php

namespace App\Filament\Resources\Users\Schemas;

use App\Enums\RoleName;
use App\Enums\UserStatus;
use App\Models\Role;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;

class UserForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema->components([
            TextInput::make('name')->label(__('roles.fields.name'))->required()->maxLength(255),
            TextInput::make('email')->label(__('roles.fields.email'))->email()->required()->unique(ignoreRecord: true),
            TextInput::make('password')->label(__('roles.fields.password'))->password()->revealable()->required(fn (string $operation): bool => $operation === 'create')->minLength(8)->dehydrated(fn (?string $state): bool => filled($state)),
            Select::make('status')->label(__('roles.fields.status'))->required()->options(collect(UserStatus::cases())->mapWithKeys(fn ($s) => [$s->value => $s->label()])),
            Select::make('roles')->label(__('roles.fields.roles'))->multiple()->searchable()->preload()->required()
                ->options(function (): array {
                    $q = Role::query();
                    if (! auth()->user()?->hasRole(RoleName::SuperAdmin)) {
                        $q->where('name', '!=', RoleName::SuperAdmin->value);
                    }

                    return $q->get()->sortBy(fn ($r) => array_search($r->name, ['super_admin', 'admin', 'support', 'customer'], true))->mapWithKeys(fn ($r) => [$r->id => __('roles.names.'.$r->name)])->all();
                })
                ->helperText(__('roles.descriptions.help'))->visible(fn () => auth()->user()?->hasPermission('roles.assign') ?? false),
        ]);
    }
}
