<?php

namespace App\Filament\Central\Widgets;

use App\Filament\Central\Resources\TenantResource;
use App\Models\Central\Tenant;
use Filament\Actions\Action;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;

/**
 * The most recently created tenants, for the master-control dashboard.
 */
class RecentTenantsWidget extends TableWidget
{
    protected static ?int $sort = 2;

    protected int|string|array $columnSpan = 'full';

    public function table(Table $table): Table
    {
        return $table
            ->heading('Recent tenants')
            ->query(
                fn () => Tenant::query()
                    ->live()
                    ->latest('created_at')
                    ->limit(5)
            )
            ->paginated(false)
            ->columns([
                TextColumn::make('name')->searchable(),
                TextColumn::make('slug')->badge(),
                TextColumn::make('status')
                    ->badge()
                    ->color(fn (?string $state): string => match ($state) {
                        Tenant::STATUS_ACTIVE => 'success',
                        Tenant::STATUS_TRIAL => 'info',
                        Tenant::STATUS_SUSPENDED => 'danger',
                        default => 'gray',
                    }),
                TextColumn::make('created_at')->dateTime()->sortable(),
            ])
            ->recordActions([
                Action::make('manage')
                    ->label('Manage')
                    ->url(fn (Tenant $record): string => TenantResource::getUrl('edit', ['record' => $record])),
            ]);
    }
}
