<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\Applications\ApplicationResource;
use App\Models\Application;
use Filament\Actions\Action;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;
use Illuminate\Database\Eloquent\Builder;

class RecentApplicationsWidget extends TableWidget
{
    protected static bool $isLazy = false;

    protected static ?int $sort = 5;

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

    public function table(Table $table): Table
    {
        return $table
            ->heading('Recent application activity')
            ->description('Latest apply redirects with applicant, job, source, and current status.')
            ->query($this->query())
            ->columns([
                TextColumn::make('user.email')
                    ->label('Applicant')
                    ->searchable(),

                TextColumn::make('importedJob.title')
                    ->label('Job')
                    ->limit(36)
                    ->searchable(),

                TextColumn::make('importedJob.company')
                    ->label('Company')
                    ->limit(28),

                TextColumn::make('source.name')
                    ->label('Source')
                    ->badge(),

                TextColumn::make('status')
                    ->badge(),

                TextColumn::make('applied_at')
                    ->dateTime()
                    ->sortable(),
            ])
            ->recordActions([
                Action::make('view')
                    ->label('View')
                    ->icon(Heroicon::Eye)
                    ->url(fn (Application $record): string => ApplicationResource::getUrl('view', ['record' => $record])),
            ])
            ->defaultSort('applied_at', 'desc');
    }

    /**
     * @return Builder<Application>
     */
    private function query(): Builder
    {
        return Application::query()
            ->with(['user', 'importedJob', 'source'])
            ->latest('applied_at')
            ->limit(8);
    }
}
