<?php

namespace App\Filament\Resources\Settlements\Tables;

use App\Models\Settlement;
use App\Models\WalletTransaction;
use Filament\Actions\Action;
use Filament\Actions\EditAction;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class SettlementsTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('reference')->label('Ref')->searchable()->weight('semibold'),
                TextColumn::make('vendor.store_name')->label('Vendor')->searchable()->limit(28),
                TextColumn::make('net_amount')->money('PKR')->sortable(),
                TextColumn::make('commission_deducted')->label('Comm')->money('PKR')->toggleable(),
                TextColumn::make('method')->badge()->toggleable(),
                TextColumn::make('status')
                    ->badge()
                    ->color(fn(string $state) => match ($state) {
                        'pending'   => 'warning',
                        'approved'  => 'info',
                        'processing'=> 'info',
                        'paid'      => 'success',
                        'failed'    => 'danger',
                        default     => 'gray',
                    }),
                TextColumn::make('period_to')->date()->label('Up to')->sortable(),
                TextColumn::make('created_at')->dateTime('M d, H:i')->sortable()->toggleable(),
            ])
            ->defaultSort('created_at', 'desc')
            ->filters([
                SelectFilter::make('status')
                    ->options([
                        'pending'    => 'Pending',
                        'approved'   => 'Approved',
                        'processing' => 'Processing',
                        'paid'       => 'Paid',
                        'failed'     => 'Failed',
                    ])
                    ->multiple(),
                SelectFilter::make('vendor')->relationship('vendor', 'store_name')->searchable()->preload(),
                SelectFilter::make('method')
                    ->options(fn() => Settlement::query()->whereNotNull('method')->distinct()->pluck('method', 'method')->all()),
                Filter::make('period')
                    ->schema([
                        DatePicker::make('from')->label('Period from'),
                        DatePicker::make('until')->label('Period to'),
                    ])
                    ->query(fn(Builder $query, array $data) => $query
                        ->when($data['from'] ?? null, fn($q, $d) => $q->whereDate('period_to', '>=', $d))
                        ->when($data['until'] ?? null, fn($q, $d) => $q->whereDate('period_to', '<=', $d))),
            ])
            ->recordActions([
                EditAction::make()->label('View')->icon('heroicon-o-eye'),

                Action::make('approve')
                    ->label('Approve')
                    ->icon('heroicon-o-check')
                    ->color('info')
                    ->requiresConfirmation()
                    ->visible(fn(Settlement $r) => $r->status === 'pending')
                    ->action(function (Settlement $r): void {
                        $r->update([
                            'status'      => 'approved',
                            'approved_by' => Auth::guard('web')->id(),
                            'approved_at' => now(),
                        ]);
                        Notification::make()->title('Settlement approved.')->success()->send();
                    }),

                Action::make('mark_paid')
                    ->label('Mark paid')
                    ->icon('heroicon-o-banknotes')
                    ->color('success')
                    ->visible(fn(Settlement $r) => in_array($r->status, ['approved', 'processing']))
                    ->schema([
                        TextInput::make('payment_proof')
                            ->label('Transaction reference (optional)')
                            ->maxLength(150),
                    ])
                    ->action(function (Settlement $r, array $data): void {
                        DB::transaction(function () use ($r, $data) {
                            $r->update([
                                'status'        => 'paid',
                                'paid_at'       => now(),
                                'payment_proof' => $data['payment_proof'] ?? null,
                            ]);
                            WalletTransaction::create([
                                'owner_type'    => $r->vendor::class,
                                'owner_id'      => $r->vendor_id,
                                'type'          => 'debit',
                                'purpose'       => 'settlement',
                                'amount'        => $r->net_amount,
                                'balance_before'=> 0,
                                'balance_after' => 0,
                                'reference'     => $r->reference,
                                'description'   => "Paid via {$r->method} to {$r->account_number}",
                            ]);
                        });
                        Notification::make()->title('Marked as paid.')->success()->send();
                    }),

                Action::make('reject')
                    ->label('Reject')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->visible(fn(Settlement $r) => in_array($r->status, ['pending', 'approved']))
                    ->requiresConfirmation()
                    ->action(function (Settlement $r): void {
                        DB::transaction(function () use ($r) {
                            $r->vendor->increment('pending_settlement', (float) $r->net_amount);
                            $r->update(['status' => 'failed']);
                        });
                        Notification::make()->title('Settlement rejected, funds returned to vendor pending.')->warning()->send();
                    }),
            ])
            ->toolbarActions([]);
    }
}
