<?php

namespace App\Filament\Resources\Users\Schemas;

use App\Modules\PhoneNumberVerification\Rules\PhoneNumberVerificationRule;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Schemas\Schema;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Hash;

class UserForm
{
    public static function configure(Schema $schema): Schema
    {
        return $schema
            ->columns(6)
            ->components([
                TextInput::make('name')
                    ->label(__('Full Name'))
                    ->required()
                    ->columnSpan(3),

                TextInput::make('username')
                    ->label(__('Username'))
                    ->required()
                    ->unique(ignoreRecord: true)
                    ->columnSpan(3),

                TextInput::make('phone')
                    ->label(__('Phone'))
                    ->unique(ignoreRecord: true)
                    ->mask('99 99 99 99')
                    ->prefix('+993')
                    ->rules([
                        new PhoneNumberVerificationRule,
                    ])
                    ->columnSpan(2),

                TextInput::make('email')
                    ->label(__('Email'))
                    ->email()
                    ->unique(ignoreRecord: true)
                    ->columnSpan(2),

                TextInput::make('password')
                    ->label(__('Password'))
                    ->password()
                    ->dehydrateStateUsing(fn ($state) => Hash::make($state))
                    ->dehydrated(fn ($state) => filled($state))
                    ->required(fn (string $context): bool => $context === 'create')
                    ->columnSpan(2),

                Select::make('roles')
                    ->label(__('Roles'))
                    ->relationship('roles', 'name')
                    ->multiple()
                    ->preload()
                    ->native(false)
                    ->columnSpan(3),

                Select::make('branches')
                    ->label(__('Branches'))
                    ->relationship('branches', 'name', fn (Builder $query) => $query->distinct('id')->orderBy('id'))
                    ->multiple()
                    ->preload()
                    ->native(false)
                    ->columnSpan(3),
            ]);
    }
}
