<?php

namespace App\Filament\Widgets;

use App\Models\Task;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;
use Illuminate\Database\Eloquent\Builder;

class TodayTasksWidget extends BaseWidget
{
    protected static ?string $heading = 'تسک‌های امروز و عقب‌افتاده';
    protected int|string|array $columnSpan = 'full';
    protected static ?int $sort = 2;

    public function table(Table $table): Table
    {
        return $table
            ->query(
                Task::query()
                    ->forUser(auth()->user())
                    ->open()
                    ->where(fn (Builder $q) => $q->whereDate('due_date', '<=', today()))
                    ->orderBy('due_date')
            )
            ->columns([
                Tables\Columns\TextColumn::make('title')->label('عنوان'),
                Tables\Columns\TextColumn::make('priority')->label('اولویت')->badge()
                    ->color(fn ($state) => ['low' => 'gray', 'medium' => 'warning', 'high' => 'danger'][$state] ?? 'gray')
                    ->formatStateUsing(fn ($state) => ['low' => 'کم', 'medium' => 'متوسط', 'high' => 'زیاد'][$state] ?? $state),
                Tables\Columns\TextColumn::make('due_date')->label('سررسید')->jalaliDateTime()
                    ->color(fn (Task $r) => $r->due_date && $r->due_date->isPast() ? 'danger' : null),
                Tables\Columns\TextColumn::make('customer.display_name')->label('مشتری'),
            ])
            ->actions([
                Tables\Actions\Action::make('done')->label('انجام شد')->icon('heroicon-o-check')->color('success')
                    ->action(function (Task $r) {
                        $r->update(['status' => 'done']);
                        $r->spawnNextOccurrence();
                    }),
            ])
            ->paginated([5, 10]);
    }
}
