<?php

namespace App\Filament\Resources\Orders\Tables;

use App\Services\OrderFulfilmentService;
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\DatePicker;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TrashedFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class OrdersTable
{
    public static function configure(Table $table): Table
    {
        return $table
            ->defaultSort('created_at', 'desc')
            ->columns([
                TextColumn::make('order_number')->label('Order #')->searchable()->weight('semibold'),
                TextColumn::make('user.name')->label('Customer')->searchable()->toggleable(),
                TextColumn::make('delivery_locality')->label('Area')->toggleable(),
                TextColumn::make('items_count')->counts('items')->label('Items')->alignCenter()->toggleable(),
                TextColumn::make('grand_total')->label('Total')->money('PKR')->sortable(),
                TextColumn::make('payment_method')->label('Payment')->badge()
                    ->formatStateUsing(fn($state) => strtoupper((string) $state))
                    ->color(fn($state) => $state === 'cod' ? 'gray' : 'info'),
                TextColumn::make('payment_status')->label('Paid?')->badge()
                    ->color(fn($state) => match ($state) {
                        'paid' => 'success', 'pending' => 'warning', 'failed' => 'danger',
                        'refunded' => 'info', default => 'gray',
                    }),
                TextColumn::make('status')->badge()
                    ->formatStateUsing(fn($state) => ucwords(str_replace('_', ' ', (string) $state)))
                    ->color(fn($state) => match ($state) {
                        'delivered' => 'success',
                        'cancelled', 'returned' => 'danger',
                        'on_the_way' => 'primary',
                        'preparing' => 'warning',
                        'confirmed' => 'info',
                        default => 'gray',
                    }),
                TextColumn::make('created_at')->label('Placed')->dateTime('M j, Y g:i A')->sortable(),
                TextColumn::make('delivered_at')->dateTime('M j, Y')->sortable()->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('status')->multiple()->options([
                    'pending'    => 'Pending',
                    'confirmed'  => 'Confirmed',
                    'preparing'  => 'Preparing',
                    'on_the_way' => 'On the way',
                    'delivered'  => 'Delivered',
                    'cancelled'  => 'Cancelled',
                    'returned'   => 'Returned',
                ]),
                SelectFilter::make('payment_method')->label('Payment method')->options([
                    'cod'       => 'Cash on Delivery',
                    'easypaisa' => 'EasyPaisa',
                    'jazzcash'  => 'JazzCash',
                ]),
                SelectFilter::make('payment_status')->label('Payment status')->options([
                    'pending'  => 'Pending',
                    'paid'     => 'Paid',
                    'failed'   => 'Failed',
                    'refunded' => 'Refunded',
                ]),
                Filter::make('created_at')
                    ->schema([
                        DatePicker::make('from')->label('Placed from'),
                        DatePicker::make('until')->label('Placed until'),
                    ])
                    ->query(fn(Builder $query, array $data) => $query
                        ->when($data['from'] ?? null, fn($q, $d) => $q->whereDate('created_at', '>=', $d))
                        ->when($data['until'] ?? null, fn($q, $d) => $q->whereDate('created_at', '<=', $d)))
                    ->indicateUsing(function (array $data) {
                        $out = [];
                        if ($data['from'] ?? null) $out[] = 'From ' . $data['from'];
                        if ($data['until'] ?? null) $out[] = 'Until ' . $data['until'];
                        return $out;
                    }),
                TrashedFilter::make(),
            ])
            ->recordActions([
                Action::make('markPaid')
                    ->label('Mark paid')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->visible(fn($record) => $record->payment_status !== 'paid')
                    ->requiresConfirmation()
                    ->modalDescription('Confirm the payment was received (e.g. the wallet transaction ID checks out), then mark this order as paid.')
                    ->action(fn($record) => $record->update(['payment_status' => 'paid'])),
                Action::make('refund')
                    ->label('Refund')
                    ->icon('heroicon-o-arrow-uturn-left')
                    ->color('warning')
                    ->visible(fn($record) => $record->payment_status === 'paid')
                    ->requiresConfirmation()
                    ->modalDescription('This credits the full order total back to the customer\'s in-app wallet and marks the order as refunded.')
                    ->action(function ($record) {
                        $refunded = app(OrderFulfilmentService::class)->refundOrder($record, 'Refunded by admin.');
                        Notification::make()
                            ->title($refunded ? 'Refunded to the customer\'s wallet.' : 'Nothing to refund.')
                            ->color($refunded ? 'success' : 'warning')
                            ->send();
                    }),
                EditAction::make(),
            ])
            ->toolbarActions([
                BulkActionGroup::make([
                    DeleteBulkAction::make(),
                    ForceDeleteBulkAction::make(),
                    RestoreBulkAction::make(),
                ]),
            ]);
    }
}
