<?php

namespace App\Filament\Widgets;

use App\Enums\RenewalStatus;
use App\Filament\Resources\RenewalResource;
use App\Models\Renewal;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class UpcomingRenewalsWidget extends BaseWidget
{
    protected static ?string $heading = '🔔 Renovaciones próximas (≤ 30 días)';
    protected static ?int $sort = 6;
    protected int | string | array $columnSpan = 1;

    public function table(Table $table): Table
    {
        return $table
            ->query(
                Renewal::query()
                    ->whereDate('next_due_date', '<=', now()->addDays(30))
                    ->whereNotIn('status', [RenewalStatus::Paid->value, RenewalStatus::Cancelled->value])
                    ->orderBy('next_due_date')
            )
            ->columns([
                Tables\Columns\TextColumn::make('next_due_date')
                    ->label('Vence')
                    ->date('d/m/Y')
                    ->color(fn (Renewal $r) => $r->next_due_date->isPast() ? 'danger' : 'warning'),

                Tables\Columns\TextColumn::make('client.name')
                    ->label('Cliente')
                    ->limit(20),

                Tables\Columns\TextColumn::make('days_until_due')
                    ->label('Días')
                    ->getStateUsing(fn (Renewal $r) => $r->days_until_due . 'd')
                    ->color(fn (Renewal $r) => $r->days_until_due < 0 ? 'danger' : 'warning'),

                Tables\Columns\TextColumn::make('total_amount')
                    ->label('Total')
                    ->getStateUsing(fn (Renewal $r) => '$' . number_format($r->total_amount, 2)),
            ])
            ->actions([
                Tables\Actions\Action::make('editar')
                    ->icon('heroicon-o-pencil')
                    ->url(fn (Renewal $r) => RenewalResource::getUrl('edit', ['record' => $r])),
            ])
            ->paginated([5]);
    }
}
