<?php

namespace App\Filament\Widgets;

use App\Enums\BookingStatus;
use App\Models\Booking;
use Filament\Tables;
use Filament\Tables\Concerns\InteractsWithTable;
use Filament\Tables\Contracts\HasTable;
use Filament\Tables\Table;
use Filament\Widgets\Concerns\InteractsWithPageFilters;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Database\Eloquent\Builder;

class RecentBookingsTable extends BaseWidget implements HasTable
{
    use InteractsWithTable;
    use InteractsWithPageFilters;

    protected int | string | array $columnSpan = [
        'md' => '50%',
        'xl' => '50%',
    ];

    public function getHeading(): string
    {
        return __('Recent Bookings');
    }

    public function table(Table $table): Table
    {
        return $table
            ->query($this->getTableQuery())
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label(__('Booking ID'))
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('user.name')
                    ->label(__('Customer'))
                    ->sortable()
                    ->searchable(),
                Tables\Columns\TextColumn::make('serviceProvider.name')
                    ->label(__('Service Provider'))
                    ->sortable()
                    ->searchable(),
                Tables\Columns\BadgeColumn::make('status')
                    ->label(__('Status'))
                    ->colors([
                        BookingStatus::PENDING->value => 'warning',
                        BookingStatus::PAID->value => 'success',
                        BookingStatus::CANCELED->value => 'danger',
                    ])
                    ->sortable(),
                Tables\Columns\TextColumn::make('total_amount')
                    ->label(__('Total Amount'))
                    ->money('SAR')
                    ->sortable(),
                Tables\Columns\TextColumn::make('created_at')
                    ->label(__('Created At'))
                    ->dateTime()
                    ->sortable(),
            ])
            ->defaultSort('created_at', 'desc')
            ->paginated([10])
            ->poll('30s');
    }

    protected function getTableQuery(): Builder
    {
        $query = Booking::query()
            ->with(['user', 'serviceProvider'])
            ->orderBy('created_at', 'desc');

        $dateFrom = $this->filters['date_from'] ?? null;
        $dateUntil = $this->filters['date_until'] ?? null;

        if ($dateFrom) {
            $query->whereDate('created_at', '>=', $dateFrom);
        }

        if ($dateUntil) {
            $query->whereDate('created_at', '<=', $dateUntil);
        }

        return $query;
    }
}
