<?php

namespace App\Filament\Resources\Master\Users;

use App\Enums\RoleEnum;
use App\Filament\Actions\Cheerful\DeleteAction;
use App\Filament\Actions\Cheerful\EditAction;
use App\Filament\Actions\Cheerful\ForceDeleteAction;
use App\Filament\Actions\Cheerful\RestoreAction;
use App\Filament\Actions\DefaultBulkActions;
use App\Filament\Columns\TimestampColumns;
use App\Filament\Resources\Master\Users\Actions\ChangePasswordAction;
use App\Filament\Resources\Master\Users\Pages\ManageUsers;
use App\Models\User;
use BackedEnum;
use Filament\Actions\BulkActionGroup;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Placeholder;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use UnitEnum;

class UserResource extends Resource
{
    protected static ?string $model = User::class;

    protected static string|UnitEnum|null $navigationGroup = 'Master';

    protected static string|BackedEnum|null $navigationIcon = Heroicon::UserGroup;

    protected static ?string $navigationLabel = 'Pengguna';

    protected static ?int $navigationSort = 1;

    protected static ?string $recordTitleAttribute = 'name';

    protected static ?string $slug = 'master/users';

    public static function form(Schema $schema): Schema
    {
        return $schema
            ->components([
                TextInput::make('name')
                    ->label('Nama')
                    ->placeholder('John Doe')
                    ->autocomplete(false)
                    ->autofocus()
                    ->required()
                    ->maxLength(100),

                TextInput::make('email')
                    ->label('Alamat Surel')
                    ->placeholder('johndoe@example.com')
                    ->autocomplete(false)
                    ->required()
                    ->maxLength(254)
                    ->email()
                    ->unique(ignoreRecord: true),

                TextInput::make('username')
                    ->label('Nama Pengguna')
                    ->placeholder('johndoe')
                    ->autocomplete(false)
                    ->required()
                    ->minLength(5)
                    ->maxLength(20)
                    ->regex('/^[a-zA-Z0-9_.-]+$/')
                    ->unique(ignoreRecord: true),

                Select::make('roles')
                    ->label('Peran')
                    ->required()
                    ->relationship('roles', 'name', function (Builder $query): Builder {
                        return $query->whereNot('name', RoleEnum::DEVELOPER);
                    })
                    ->multiple()
                    ->preload()
                    ->searchable(),

                TextInput::make('base_salary')
                    ->label('Gaji Pokok')
                    ->numeric()
                    ->prefix('Rp')
                    ->currencyMask(thousandSeparator: '.', decimalSeparator: ',', precision: 0)
                    ->required(),

                Hidden::make('password')
                    ->default(fn (): string => config('auth.password_default'))
                    ->visibleOn('create'),

                Placeholder::make('default_password_info')
                    ->label('Informasi Kata Sandi')
                    ->content(
                        'Kata sandi bawaan untuk pengguna baru adalah: 
        <code class="px-2 py-1 bg-gray-100 rounded font-semibold text-red-500">'
                            .config('auth.password_default').
                            '</code>'
                    )
                    ->html()
                    ->visibleOn('create'),
            ])
            ->columns(1);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('name')
                    ->label('Nama')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('email')
                    ->label('Alamat Surel')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('username')
                    ->label('Nama Pengguna')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('roles.name')
                    ->label('Peran')
                    ->searchable()
                    ->sortable()
                    ->badge()
                    ->getStateUsing(fn (User $record): array => $record->roles->pluck('name', 'id')->toArray()),

                TextColumn::make('base_salary')
                    ->label('Gaji Pokok')
                    ->money('IDR', decimalPlaces: 0)
                    ->sortable(),

                ...TimestampColumns::make(),
            ])
            ->filters([
                TrashedFilter::make()
                    ->native(false)
                    ->visible(fn (): bool => auth()->user()->hasRole(RoleEnum::DEVELOPER)),
            ])
            ->recordActions([
                EditAction::make()
                    ->modalWidth(Width::Large),

                DeleteAction::make(),

                ForceDeleteAction::make(),

                RestoreAction::make(),

                ChangePasswordAction::make('changePassword'),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Pengguna'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::UserGroup)
            ->emptyStateDescription('Setelah Anda membubat data pertama, maka akan muncul disini.')
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false);
    }

    public static function getPages(): array
    {
        return [
            'index' => ManageUsers::route('/'),
        ];
    }

    public static function getRecordRouteBindingEloquentQuery(): Builder
    {
        return parent::getRecordRouteBindingEloquentQuery()
            ->withoutGlobalScopes([
                SoftDeletingScope::class,
            ]);
    }

    public static function getEloquentQuery(): Builder
    {
        return static::getModel()::query()->withoutDeveloper();
    }
}
