<?php

namespace App\Filament\Widgets;

use App\Filament\Resources\DeliveryPartners\DeliveryPartnerResource;
use App\Models\DeliveryPartner;
use Filament\Actions\Action;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Widgets\TableWidget as BaseWidget;

/**
 * Reconciliation list: couriers currently holding COD cash or owed earnings.
 * The admin settles each from the courier's record (Pay out / Record COD).
 */
class CodFloatTable extends BaseWidget
{
    protected static ?string $heading = 'Courier balances to reconcile';

    protected static ?int $sort = 4;

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

    public function table(Table $table): Table
    {
        return $table
            ->query(
                DeliveryPartner::query()
                    ->where(fn ($q) => $q->where('pending_cod', '>', 0)->orWhere('wallet_balance', '>', 0))
                    ->orderByDesc('pending_cod')
            )
            ->paginated([10, 25])
            ->columns([
                TextColumn::make('name')->searchable()->weight('semibold'),
                TextColumn::make('phone')->searchable(),
                TextColumn::make('wallet_balance')
                    ->label('Earnings owed')
                    ->money('PKR')
                    ->color('warning'),
                TextColumn::make('pending_cod')
                    ->label('COD held')
                    ->money('PKR')
                    ->color('danger'),
                TextColumn::make('total_deliveries')->label('Deliveries')->sortable(),
            ])
            ->recordActions([
                Action::make('manage')
                    ->label('Manage')
                    ->icon('heroicon-m-banknotes')
                    ->url(fn (DeliveryPartner $r) => DeliveryPartnerResource::getUrl('edit', ['record' => $r])),
            ])
            ->emptyStateHeading('All settled')
            ->emptyStateDescription('No courier is holding COD cash or owed earnings right now.')
            ->emptyStateIcon('heroicon-o-check-badge');
    }
}
