<?php

namespace App\Filament\Resources\WatchedEvents\Tables;

use App\Models\WatchedEvent;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteAction;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class WatchedEventsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('label')
                    ->searchable()
                    ->sortable()
                    ->limit(60)
                    ->tooltip(fn (WatchedEvent $record) => strlen($record->label) > 60 ? $record->label : null),
                TextColumn::make('starts_at')
                    ->dateTime('d M Y H:i')
                    ->sortable(),
                TextColumn::make('ends_at')
                    ->dateTime('d M Y H:i')
                    ->sortable(),
                TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->state(fn (WatchedEvent $record): string => self::isActive($record) ? 'Active' : 'Inactive')
                    ->color(fn (string $state) => $state === 'Active' ? 'success' : 'gray'),
                TextColumn::make('notes')
                    ->limit(50)
                    ->placeholder('—')
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('starts_at', 'desc')
            ->filters([
                Filter::make('currently_active')
                    ->label('Currently active')
                    ->toggle()
                    ->query(fn (Builder $query) => $query
                        ->where('starts_at', '<=', now())
                        ->where('ends_at', '>=', now())),
            ])
            ->recordActions([
                EditAction::make(),
                DeleteAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }

    protected static function isActive(WatchedEvent $record): bool
    {
        $now = now();

        return $record->starts_at !== null
            && $record->ends_at !== null
            && $record->starts_at->lessThanOrEqualTo($now)
            && $record->ends_at->greaterThanOrEqualTo($now);
    }
}
