<?php

namespace App\Filament\Construction\Widgets;

use App\Filament\Concerns\InteractsWithDashboardFilters;
use App\Filament\Construction\Resources\DailyProgressReportResource;
use App\Models\DailyProgressReport;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class ConstructionRecentDprTable extends BaseWidget
{
    use InteractsWithDashboardFilters;

    protected static bool $isDiscovered = false;

    protected static ?int $sort = 7;

    protected static ?string $heading = 'Daily Progress Reports';

    protected int | string | array $columnSpan = ['default' => 'full', 'lg' => 1];

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

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

        $query = DailyProgressReport::query()
            ->with(['project', 'user'])
            ->latest('report_date');

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

        if ($filters->projectId) {
            $query->where('project_id', $filters->projectId);
        } elseif ($filters->projectStatus) {
            $query->whereHas('project', fn ($q) => $q->where('status', $filters->projectStatus));
        }

        return $table
            ->query($query)
            ->columns([
                Tables\Columns\TextColumn::make('report_date')
                    ->label('Date')
                    ->date()
                    ->sortable(),
                Tables\Columns\TextColumn::make('project.name')
                    ->label('Project')
                    ->limit(20),
                Tables\Columns\TextColumn::make('labor_count')
                    ->label('Labor')
                    ->alignCenter(),
                Tables\Columns\TextColumn::make('weather')
                    ->badge()
                    ->color('info')
                    ->placeholder('—'),
                Tables\Columns\TextColumn::make('user.name')
                    ->label('Reported by')
                    ->toggleable(),
            ])
            ->actions([
                Tables\Actions\Action::make('view')
                    ->icon('heroicon-m-eye')
                    ->url(fn (DailyProgressReport $record): string => DailyProgressReportResource::getUrl('edit', ['record' => $record])),
            ])
            ->defaultPaginationPageOption(5)
            ->paginated([5])
            ->emptyStateHeading('No DPRs in this period')
            ->emptyStateDescription('Adjust filters or submit a new daily progress report.');
    }
}
