<?php

namespace App\Filament\Resources\Payments\Tables;

use App\Models\Payment;
use Filament\Actions\ViewAction;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;

class PaymentsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('reference')
                    ->label('Reference')
                    ->description(fn (Payment $record) => $record->created_at->diffForHumans())
                    ->searchable()
                    ->copyable()
                    ->weight('bold'),
                TextColumn::make('user.name')
                    ->label('Member')
                    ->description(fn (Payment $record) => $record->email)
                    ->searchable(['users.name', 'users.email'])
                    ->placeholder('Guest'),
                TextColumn::make('purpose')
                    ->label('Product')
                    ->formatStateUsing(fn ($state, Payment $record) => $record->productLabel())
                    ->wrap(),
                TextColumn::make('status')
                    ->badge()
                    ->color(fn (string $state) => match ($state) {
                        'paid' => 'success',
                        'pending' => 'warning',
                        'failed' => 'danger',
                        default => 'gray',
                    }),
                TextColumn::make('amount')
                    ->label('Amount')
                    ->formatStateUsing(fn ($state, Payment $record) => $record->currency.' '.number_format(((int) $state) / 100, 2))
                    ->weight('bold')
                    ->sortable(),
                TextColumn::make('gateway')->badge()->color('info'),
                TextColumn::make('paid_at')->label('Paid')->since()->placeholder('-')->sortable(),
            ])
            ->filters([
                SelectFilter::make('status')->options([
                    'pending' => 'Pending',
                    'paid' => 'Paid',
                    'failed' => 'Failed',
                    'cancelled' => 'Cancelled',
                ]),
                SelectFilter::make('gateway')->options([
                    'mpesa' => 'M-Pesa',
                    'paystack' => 'Paystack',
                    'flutterwave' => 'Flutterwave',
                ]),
                SelectFilter::make('currency')->options(['KES' => 'KES', 'USD' => 'USD']),
            ])
            ->recordActions([ViewAction::make()]);
    }
}
