<?php

namespace App\Filament\Central\Widgets;

use App\Filament\Central\Resources\SubscriptionResource;
use App\Models\Central\Subscription;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

class PendingPayments extends BaseWidget
{
    protected static ?int $sort = 4;

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

    public function table(Table $table): Table
    {
        return $table
            ->heading('Facturi pending / overdue')
            ->query(
                Subscription::query()
                    ->whereIn('status', ['pending', 'overdue'])
                    ->with(['company', 'plan'])
                    ->latest('due_at')
                    ->limit(10)
            )
            ->columns([
                Tables\Columns\TextColumn::make('invoice_number')
                    ->label('Factură')
                    ->copyable()
                    ->url(fn ($record) => SubscriptionResource::getUrl('edit', ['record' => $record])),
                Tables\Columns\TextColumn::make('company.name')->label('Companie'),
                Tables\Columns\TextColumn::make('plan.name')->placeholder('—'),
                Tables\Columns\TextColumn::make('amount')->money(fn ($record) => $record->currency)->weight('bold'),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn ($s) => $s === 'overdue' ? 'danger' : 'warning')
                    ->formatStateUsing(fn ($s) => Subscription::STATUSES[$s] ?? $s),
                Tables\Columns\TextColumn::make('due_at')
                    ->label('Scadent')
                    ->dateTime()
                    ->color(fn ($record) => $record->due_at && $record->due_at->isPast() ? 'danger' : null),
            ])
            ->emptyStateHeading('🎉 Toate facturile sunt plătite')
            ->paginated(false);
    }
}
