<?php

namespace App\Filament\Resources\Resellers\Tables;

use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Actions\Action;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Filament\Notifications\Notification;

class ResellersTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->columns([
                TextColumn::make('reseller_code')
                    ->label('Reseller ID')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('email')
                    ->label('Email Address')
                    ->searchable()
                    ->sortable(),
                TextColumn::make('resellerPackage.name')
                    ->label('Membership Package')
                    ->placeholder('No Package')
                    ->sortable(),
                TextColumn::make('reseller_orders_count')
                    ->label('Total Orders')
                    ->counts('resellerOrders')
                    ->sortable(),
                TextColumn::make('total_sales')
                    ->label('Total Sales')
                    ->money('BDT')
                    ->getStateUsing(fn ($record) => $record->resellerOrders()->sum('subtotal')),
                TextColumn::make('total_profit')
                    ->label('Total Profit')
                    ->money('BDT')
                    ->getStateUsing(fn ($record) => $record->resellerOrders()->sum('total_reseller_profit')),
                TextColumn::make('wallet_balance')
                    ->label('Wallet Balance')
                    ->money('BDT')
                    ->getStateUsing(fn ($record) => $record->getWalletBalance()),
                TextColumn::make('total_withdrawn')
                    ->label('Withdrawn')
                    ->money('BDT')
                    ->getStateUsing(fn ($record) => $record->withdrawRequests()->where('status', 'approved')->sum('amount')),
                TextColumn::make('reseller_status')
                    ->label('Reseller Status')
                    ->badge()
                    ->color(fn (?string $state): ?string => match ($state) {
                        'pending' => 'gray',
                        'under_review' => 'warning',
                        'active' => 'success',
                        'rejected' => 'danger',
                        'expired' => 'danger',
                        'suspended' => 'danger',
                        default => null,
                    })
                    ->sortable(),
                TextColumn::make('created_at')
                    ->label('Registered At')
                    ->dateTime()
                    ->sortable(),
            ])
            ->filters([
                // Filters can be added here
            ])
            ->actions([
                Action::make('approve')
                    ->label('Approve')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->requiresConfirmation()
                    ->visible(fn ($record) => $record->reseller_status !== 'active')
                    ->action(function ($record) {
                        $record->update([
                            'reseller_status' => 'active',
                            'role' => 'reseller',
                            'reseller_rejection_reason' => null,
                        ]);
                        Notification::make()
                            ->title('Reseller Approved')
                            ->body("{$record->name} has been approved as an active reseller.")
                            ->success()
                            ->send();
                    }),
                Action::make('reject')
                    ->label('Reject')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->form([
                        \Filament\Forms\Components\Textarea::make('reason')
                            ->label('Rejection Reason')
                            ->required()
                            ->placeholder('e.g. NID image is blurry, please re-upload clear photos.'),
                    ])
                    ->visible(fn ($record) => in_array($record->reseller_status, ['pending', 'under_review']))
                    ->action(function ($record, array $data) {
                        $record->update([
                            'reseller_status' => 'rejected',
                            'reseller_rejection_reason' => $data['reason'],
                        ]);
                        Notification::make()
                            ->title('Reseller Rejected')
                            ->body("{$record->name}'s registration has been rejected.")
                            ->danger()
                            ->send();
                    }),
                Action::make('suspend')
                    ->label('Suspend')
                    ->icon('heroicon-o-minus-circle')
                    ->color('danger')
                    ->requiresConfirmation()
                    ->visible(fn ($record) => $record->reseller_status === 'active')
                    ->action(function ($record) {
                        $record->update([
                            'reseller_status' => 'suspended',
                        ]);
                        Notification::make()
                            ->title('Reseller Suspended')
                            ->body("{$record->name} has been suspended.")
                            ->danger()
                            ->send();
                    }),
                EditAction::make(),
            ])
            ->bulkActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                ]),
            ]);
    }
}
