<?php

namespace App\Filament\Resources\Master\Users\Tables;

use App\Enums\IsActive;
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\RowIndexColumn;
use App\Filament\Columns\TimestampColumns;
use App\Filament\Resources\Master\Users\Actions\ChangePasswordAction;
use App\Filament\Support\CheerfulNotification;
use App\Models\User;
use Filament\Actions\BulkActionGroup;
use Filament\Support\Enums\Width;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\ToggleColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;

class UserTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                ...RowIndexColumn::make(),

                TextColumn::make('name')
                    ->label('Nama Lengkap')
                    ->searchable()
                    ->sortable(),

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

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

                ToggleColumn::make('is_active')
                    ->label('Status')
                    ->sortable()
                    ->getStateUsing(fn (User $record): bool => $record->is_active === IsActive::ACTIVE)
                    ->updateStateUsing(function (User $record, bool $state): void {
                        $record->is_active = $state ? IsActive::ACTIVE : IsActive::INACTIVE;
                        $record->save();

                        if ($record->is_active === IsActive::INACTIVE) {
                            DB::table('sessions')
                                ->where('user_id', $record->id)
                                ->delete();
                        }

                        CheerfulNotification::success(
                            $state ? CheerfulNotification::getByKey('user.activated') : CheerfulNotification::getByKey('user.deactivated'),
                            $state ? CheerfulNotification::getByKey('user.status_activated_success') : CheerfulNotification::getByKey('user.status_activated_success')
                        )->send();
                    }),

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

                ...TimestampColumns::make(),
            ])
            ->filters([
                SelectFilter::make('is_active')
                    ->label('Status')
                    ->options(IsActive::class)
                    ->native(false),

                SelectFilter::make('roles')
                    ->label('Peran')
                    ->relationship('roles', 'name', function (Builder $query): Builder {
                        return $query->whereNotIn('name', [RoleEnum::DEVELOPER, RoleEnum::PERUSAHAAN]);
                    })
                    ->multiple()
                    ->preload()
                    ->searchable()
                    ->native(false),

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

                DeleteAction::make(),

                ForceDeleteAction::make(),

                RestoreAction::make(),

                ChangePasswordAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Pengguna'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::OutlinedUserGroup)
            ->emptyStateHeading(fn () => CheerfulNotification::getByKey('user.empty_state_heading'))
            ->emptyStateDescription(fn () => CheerfulNotification::getByKey('user.empty_state'))
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false)
            ->paginated([25, 50, 100, 'all'])
            ->deferLoading();
    }
}
