<?php

namespace App\Filament\Resources\Payments\Tables;

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

class PaymentsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->modifyQueryUsing(fn ($query) =>
                $query->select([
                    'id', 'invoice_id', 'consignment_id',
                    'receipt_number', 'amount_kes', 'method',
                    'reference', 'cashier_id',
                    'receipt_printed_at', 'created_at',
                ])
                ->with([
                    'consignment:id,customer_name,phone,house_waybill_no,container_no',
                    'invoice:id,payment_status,outstanding_kes',
                ])
                ->latest()
            )
            ->paginated([15, 25, 50])
            ->columns([
                TextColumn::make('receipt_number')
                    ->label('Receipt No.')
                    ->weight('bold')
                    ->copyable()
                    ->searchable(),

                TextColumn::make('consignment.customer_name')
                    ->label('Client')
                    ->searchable(),

                TextColumn::make('consignment.phone')
                    ->label('Phone')
                    ->searchable()
                    ->toggleable(),

                TextColumn::make('amount_kes')
                    ->label('Amount (KES)')
                    ->formatStateUsing(fn ($state) =>
                        'KES ' . number_format($state, 2)
                    )
                    ->weight('bold'),

                TextColumn::make('method')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'mpesa'  => 'success',
                        'cash'   => 'info',
                        'bank'   => 'primary',
                        'cheque' => 'warning',
                        default  => 'gray',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'mpesa'  => 'M-Pesa',
                        'cheque' => 'Cheque',
                        'bank'   => 'Bank',
                        default  => ucfirst($state),
                    }),

                TextColumn::make('reference')
                    ->placeholder('—')
                    ->toggleable(),

                TextColumn::make('invoice.payment_status')
                    ->label('Invoice Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'paid'    => 'success',
                        'partial' => 'warning',
                        'unpaid'  => 'danger',
                        default   => 'gray',
                    })
                    ->formatStateUsing(fn (string $state): string =>
                        ucfirst($state)
                    ),

                IconColumn::make('receipt_printed_at')
                    ->label('Printed')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-clock')
                    ->trueColor('success')
                    ->falseColor('gray'),

                TextColumn::make('created_at')
                    ->label('Time')
                    ->dateTime('M d, H:i')
                    ->sortable(),
            ])
            ->filters([
                SelectFilter::make('method')
                    ->options([
                        'cash'   => 'Cash',
                        'mpesa'  => 'M-Pesa',
                        'bank'   => 'Bank Transfer',
                        'cheque' => 'Cheque',
                    ]),

                Filter::make('today')
                    ->label('Today only')
                    ->query(fn ($query) =>
                        $query->whereDate('created_at', today())
                    )
                    ->default(),
            ])
            ->actions([
                Action::make('print_receipt')
                    ->label('Print Receipt')
                    ->icon('heroicon-o-printer')
                    ->color('primary')
                    ->action(function (Payment $record): void {
                        if (! $record->receipt_printed_at) {
                            $record->update([
                                'receipt_printed_at' => now(),
                            ]);
                        }
                    })
                    ->url(fn (Payment $record): string =>
                        route('documents.print', ['receipt', $record->id])
                    )
                    ->openUrlInNewTab(),

                ViewAction::make(),
            ])
            ->defaultSort('created_at', 'desc');
    }
}