<?php

namespace App\Filament\Resources\Master\Locations\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\Support\CheerfulNotification;
use App\Models\Location;
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;

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

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

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

                        CheerfulNotification::statusUpdated()->send();
                    }),

                ...TimestampColumns::make(),
            ])
            ->filters([
                SelectFilter::make('is_active')
                    ->label('Status')
                    ->options(IsActive::class)
                    ->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(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    ...DefaultBulkActions::make('Lokus'),
                ]),
            ])
            ->emptyStateIcon(Heroicon::OutlinedMapPin)
            ->emptyStateHeading(fn () => CheerfulNotification::getByKey('locus.empty_state_heading'))
            ->emptyStateDescription(fn () => CheerfulNotification::getByKey('locus.empty_state'))
            ->defaultSort('created_at', 'desc')
            ->deferFilters(false)
            ->paginated([25, 50, 100, 'all'])
            ->deferLoading();
    }
}
