<?php

namespace App\Filament\RealEstate\Widgets;

use App\Filament\Concerns\InteractsWithDashboardFilters;
use App\Filament\RealEstate\Resources\BookingResource;
use App\Models\Booking;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class RealEstateRecentBookingsTable extends BaseWidget
{
    use InteractsWithDashboardFilters;

    protected static bool $isDiscovered = false;

    protected static ?int $sort = 8;

    protected static ?string $heading = 'Bookings';

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

    public static function canView(): bool
    {
        return auth()->user()?->can('re_view_bookings') ?? false;
    }

    public function table(Table $table): Table
    {
        $filters = $this->filters();

        $query = Booking::query()
            ->with(['client', 'property'])
            ->latest('booking_date');

        $filters->applyDateRange($query, 'booking_date');

        if ($filters->propertyType || $filters->propertyStatus || $filters->projectId) {
            $query->whereHas('property', fn ($q) => $filters->applyProperty($q));
        }

        return $table
            ->query($query)
            ->columns([
                Tables\Columns\TextColumn::make('booking_number')
                    ->label('Booking #')
                    ->searchable()
                    ->weight('bold'),
                Tables\Columns\TextColumn::make('client.name')
                    ->label('Client'),
                Tables\Columns\TextColumn::make('property.title')
                    ->label('Property')
                    ->limit(25),
                Tables\Columns\TextColumn::make('booking_date')
                    ->label('Date')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('amount')
                    ->money('PKR')
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'active' => 'success',
                        'cancelled' => 'danger',
                        default => 'warning',
                    }),
            ])
            ->actions([
                Tables\Actions\Action::make('view')
                    ->icon('heroicon-m-eye')
                    ->url(fn (Booking $record): string => BookingResource::getUrl('edit', ['record' => $record])),
            ])
            ->defaultPaginationPageOption(5)
            ->paginated([5, 10])
            ->emptyStateHeading('No bookings in this period')
            ->emptyStateDescription('Adjust filters or create a new booking.');
    }
}
