<?php

namespace App\Filament\Widgets;

use App\Models\MemberPoint;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;
use Illuminate\Database\Eloquent\Builder;

class LeaderboardWidget extends TableWidget
{
    protected static ?string $heading = 'Leaderboard Poin Anggota';
    protected int | string | array $columnSpan = 'full';
    protected static ?int $sort = 3;

    public function getTableRecordKey(\Illuminate\Database\Eloquent\Model|array $record): string
    {
        return (string) (is_array($record) ? $record['user_id'] : $record->user_id);
    }

    public function table(Table $table): Table
    {
        return $table
            ->query(
                MemberPoint::query()
                    ->selectRaw('user_id, SUM(points) as total_points')
                    ->groupBy('user_id')
                    ->orderByDesc('total_points')
                    ->limit(10)
                    ->with('user')
            )
            ->columns([
                TextColumn::make('user.name')->label('Anggota'),
                TextColumn::make('total_points')->label('Total Poin')
                    ->badge()->color('success'),
            ])
            ->paginated(false);
    }
}
