<?php

declare(strict_types=1);

namespace App\Filament\Widgets;

use App\Enums\BookingStatus;
use App\Models\Booking;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget;
use Illuminate\Database\Eloquent\Builder;

/**
 * What is actually happening in the building today.
 *
 * Ordered by start time rather than by room, because the question this
 * answers is "who is walking through the door next", not "what is Studio B
 * doing". Cancelled and expired bookings are excluded — this is a run sheet,
 * not an audit log.
 */
class TodaySchedule extends TableWidget
{
    protected static ?string $heading = 'Today in the studio';

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

    protected ?string $pollingInterval = '60s';

    protected static bool $isLazy = false;

    public function table(Table $table): Table
    {
        return $table
            ->query(
                Booking::query()
                    ->with(['room', 'user.profile', 'assignedEngineer'])
                    ->whereBetween('starts_at', self::todayWindow())
                    ->whereIn('status', [
                        BookingStatus::Confirmed->value,
                        BookingStatus::Completed->value,
                        BookingStatus::PaymentSubmitted->value,
                    ])
                    ->orderBy('starts_at')
            )
            ->emptyStateHeading('Nothing booked today')
            ->emptyStateDescription('Confirmed sessions for today will appear here.')
            ->emptyStateIcon('heroicon-o-moon')
            ->paginated(false)
            ->columns([
                TextColumn::make('starts_at')
                    ->label('Time')
                    ->formatStateUsing(fn ($state, Booking $record) => $record->starts_at
                        ->setTimezone(config('studio.timezone'))->format('H:i')
                        .' – '.
                        $record->ends_at->setTimezone(config('studio.timezone'))->format('H:i'))
                    ->weight('bold'),

                TextColumn::make('room.name')->label('Room')->badge()->color('gray'),

                TextColumn::make('user.profile.artist_name')
                    ->label('Artist')
                    ->description(fn (Booking $record) => $record->user->profile?->phone)
                    ->placeholder('—'),

                TextColumn::make('type')->label('Kind')->badge(),

                TextColumn::make('assignedEngineer.name')
                    ->label('Engineer')
                    ->placeholder(fn (Booking $record) => $record->staff_required > 0 ? 'Unassigned' : '—')
                    ->color(fn (Booking $record) => $record->staff_required > 0 && $record->assigned_engineer_id === null
                        ? 'warning'
                        : null),

                TextColumn::make('status')->badge(),
            ])
            ->recordActions([
                Action::make('open')
                    ->label('Open')
                    ->icon('heroicon-m-arrow-top-right-on-square')
                    ->url(fn (Booking $record) => route('filament.admin.resources.bookings.view', $record)),
            ]);
    }

    /** @return array{0: CarbonImmutable, 1: CarbonImmutable} */
    private static function todayWindow(): array
    {
        $start = CarbonImmutable::now(config('studio.timezone'))->startOfDay();

        return [$start->setTimezone('UTC'), $start->addDay()->setTimezone('UTC')];
    }

    protected function getTableQuery(): ?Builder
    {
        return null;
    }
}
