<?php

namespace App\Filament\Resources\DeliveryPartners\Tables;

use App\Models\DeliveryPartner;
use App\Services\CourierWalletService;
use Filament\Actions\Action;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\ForceDeleteBulkAction;
use Filament\Actions\RestoreBulkAction;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;

class DeliveryPartnersTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('name')->searchable()->weight('semibold'),
                TextColumn::make('phone')->searchable(),
                TextColumn::make('vehicle_type')->label('Vehicle')->badge(),
                IconColumn::make('is_online')->label('Online')->boolean(),
                TextColumn::make('total_deliveries')->label('Deliveries')->numeric()->sortable(),
                TextColumn::make('completion_rate')->label('Completion')->suffix('%')->sortable()->toggleable(),
                TextColumn::make('acceptance_rate')->label('Acceptance')->suffix('%')->sortable()->toggleable(),
                TextColumn::make('rating_average')->label('★')
                    ->formatStateUsing(fn($state) => number_format((float) $state, 1))->sortable(),
                TextColumn::make('wallet_balance')->label('Wallet')->money('PKR')->sortable()->toggleable(),
                TextColumn::make('pending_cod')->label('Pending COD')->money('PKR')->sortable(),
                TextColumn::make('status')->badge()
                    ->color(fn($state) => match ($state) {
                        'active' => 'success', 'suspended' => 'warning',
                        'blacklisted' => 'danger', default => 'gray',
                    }),
                TextColumn::make('created_at')->label('Joined')->dateTime('M j, Y')->sortable()->toggleable(),
            ])
            ->filters([
                SelectFilter::make('status')
                    ->options(fn() => DeliveryPartner::query()->whereNotNull('status')->distinct()->orderBy('status')->pluck('status', 'status')->all())
                    ->multiple(),
                SelectFilter::make('vehicle_type')->label('Vehicle')
                    ->options(fn() => DeliveryPartner::query()->whereNotNull('vehicle_type')->distinct()->pluck('vehicle_type', 'vehicle_type')->all()),
                TernaryFilter::make('is_online')->label('Online now'),
                TrashedFilter::make(),
            ])
            ->recordActions([
                // Pay the courier the delivery earnings the platform owes them.
                Action::make('payout')
                    ->label('Pay out')
                    ->icon('heroicon-o-banknotes')
                    ->color('success')
                    ->visible(fn(DeliveryPartner $r) => (float) $r->wallet_balance > 0)
                    ->schema([
                        TextInput::make('amount')
                            ->label('Payout amount (PKR)')
                            ->numeric()
                            ->required()
                            ->default(fn(DeliveryPartner $r) => (float) $r->wallet_balance)
                            ->helperText(fn(DeliveryPartner $r) => 'Wallet balance: PKR ' . number_format((float) $r->wallet_balance, 2)),
                        TextInput::make('reference')->label('Transaction reference (optional)')->maxLength(150),
                    ])
                    ->action(function (DeliveryPartner $r, array $data): void {
                        app(CourierWalletService::class)->recordPayout(
                            $r, (float) $data['amount'], $data['reference'] ?? null,
                            'Earnings paid via ' . ($r->payout_method ?? 'manual'),
                        );
                        Notification::make()->title('Payout recorded.')->success()->send();
                    }),

                // Record cash the courier handed back (COD collected from customers).
                Action::make('cod_remittance')
                    ->label('Record COD')
                    ->icon('heroicon-o-arrow-down-on-square')
                    ->color('warning')
                    ->visible(fn(DeliveryPartner $r) => (float) $r->pending_cod > 0)
                    ->schema([
                        TextInput::make('amount')
                            ->label('Cash received from courier (PKR)')
                            ->numeric()
                            ->required()
                            ->default(fn(DeliveryPartner $r) => (float) $r->pending_cod)
                            ->helperText(fn(DeliveryPartner $r) => 'Outstanding COD: PKR ' . number_format((float) $r->pending_cod, 2)),
                        TextInput::make('reference')->label('Note / reference (optional)')->maxLength(150),
                    ])
                    ->action(function (DeliveryPartner $r, array $data): void {
                        app(CourierWalletService::class)->recordCodRemittance(
                            $r, (float) $data['amount'], $data['reference'] ?? null, 'COD cash received',
                        );
                        Notification::make()->title('COD remittance recorded.')->success()->send();
                    }),

                EditAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }
}
