<?php

namespace App\Filament\Construction\Widgets;

use App\Filament\Concerns\InteractsWithDashboardFilters;
use App\Models\Milestone;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class ConstructionUpcomingMilestonesTable extends BaseWidget
{
    use InteractsWithDashboardFilters;

    protected static bool $isDiscovered = false;

    protected static ?int $sort = 8;

    protected static ?string $heading = 'Upcoming & Overdue Milestones';

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

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

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

        $query = Milestone::query()
            ->with('project')
            ->whereNull('completed_at')
            ->orderBy('target_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('name')
                    ->weight('bold')
                    ->limit(25),
                Tables\Columns\TextColumn::make('project.name')
                    ->label('Project')
                    ->limit(20),
                Tables\Columns\TextColumn::make('target_date')
                    ->label('Due')
                    ->date()
                    ->color(fn (Milestone $record): string => $record->target_date?->isPast() ? 'danger' : 'gray'),
                Tables\Columns\TextColumn::make('completion_percentage')
                    ->label('Progress')
                    ->suffix('%')
                    ->badge()
                    ->color(fn ($state) => (int) $state >= 75 ? 'success' : 'warning'),
                Tables\Columns\TextColumn::make('stage')
                    ->badge()
                    ->color('info'),
            ])
            ->defaultPaginationPageOption(5)
            ->paginated([5])
            ->emptyStateHeading('No pending milestones')
            ->emptyStateDescription('All milestones are completed for the selected filters.');
    }
}
