<?php

namespace App\Filament\Resources\UserEngagementEvents;

use App\Filament\Resources\UserEngagementEvents\Pages\ListUserEngagementEvents;
use App\Models\UserEngagementEvent;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class UserEngagementEventResource extends Resource
{
    protected static ?string $model = UserEngagementEvent::class;

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

    protected static ?string $navigationLabel = 'Engagement Timeline';

    protected static string|\UnitEnum|null $navigationGroup = 'Operations';

    protected static ?int $navigationSort = 20;

    public static function form(Schema $schema): Schema
    {
        return $schema;
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('occurred_at')
                    ->dateTime()
                    ->sortable(),

                TextColumn::make('user.email')
                    ->label('User')
                    ->searchable()
                    ->sortable(),

                TextColumn::make('event_type')
                    ->badge()
                    ->searchable()
                    ->sortable(),

                TextColumn::make('description')
                    ->searchable()
                    ->limit(70),

                TextColumn::make('subject_type')
                    ->label('Subject')
                    ->formatStateUsing(fn (?string $state): string => $state ? class_basename($state) : '-')
                    ->toggleable(),

                TextColumn::make('metadata')
                    ->formatStateUsing(fn (mixed $state): string => is_array($state) ? str(json_encode($state, JSON_UNESCAPED_SLASHES))->limit(90)->toString() : '-')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('event_type')
                    ->options(fn (): array => UserEngagementEvent::query()
                        ->select('event_type')
                        ->distinct()
                        ->orderBy('event_type')
                        ->pluck('event_type', 'event_type')
                        ->all()),
            ])
            ->defaultSort('occurred_at', 'desc');
    }

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