<?php

namespace App\Filament\Resources;

use App\Filament\Resources\PaymentsResource\Pages;
use App\Models\Payment;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;

class PaymentsResource extends Resource
{
    protected static ?string $model = Payment::class;
    protected static ?string $navigationIcon = 'heroicon-o-credit-card';
    protected static ?string $navigationLabel = 'پرداخت‌ها';
    protected static ?string $modelLabel = 'پرداخت';
    protected static ?string $pluralModelLabel = 'پرداخت‌ها';
    protected static ?string $navigationGroup = 'مالی';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Section::make('اطلاعات پرداخت')
                    ->schema([
                        Forms\Components\Select::make('user_id')
                            ->relationship('user', 'tg_id')
                            ->label('کاربر')
                            ->searchable()
                            ->preload()
                            ->required(),
                        Forms\Components\Select::make('plan_id')
                            ->relationship('plan', 'name')
                            ->label('پلن')
                            ->searchable()
                            ->preload(),
                        Forms\Components\Select::make('gateway')
                            ->label('درگاه پرداخت')
                            ->options([
                                'zarinpal' => 'زرین‌پال',
                            ])
                            ->default('zarinpal')
                            ->required(),
                        Forms\Components\TextInput::make('ref')
                            ->label('شماره پیگیری')
                            ->required()
                            ->unique(ignoreRecord: true),
                        Forms\Components\TextInput::make('amount')
                            ->label('مبلغ')
                            ->numeric()
                            ->suffix('ریال')
                            ->required(),
                    ])->columns(2),

                Forms\Components\Section::make('وضعیت و جزئیات')
                    ->schema([
                        Forms\Components\Select::make('status')
                            ->label('وضعیت')
                            ->options([
                                'pending' => 'در حال بررسی',
                                'ok' => 'موفق',
                                'failed' => 'ناموفق',
                            ])
                            ->default('pending')
                            ->required(),
                        Forms\Components\Textarea::make('payload_json')
                            ->label('جزئیات پرداخت')
                            ->rows(4)
                            ->json()
                            ->columnSpanFull(),
                    ]),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('id')
                    ->label('شناسه')
                    ->sortable(),
                Tables\Columns\TextColumn::make('user.tg_id')
                    ->label('کاربر')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('plan.name')
                    ->label('پلن')
                    ->searchable(),
                Tables\Columns\BadgeColumn::make('gateway')
                    ->label('درگاه')
                    ->formatStateUsing(fn (string $state): string => match($state) {
                        'zarinpal' => 'زرین‌پال',
                    })
                    ->color('blue'),
                Tables\Columns\TextColumn::make('ref')
                    ->label('شماره پیگیری')
                    ->searchable()
                    ->copyable(),
                Tables\Columns\TextColumn::make('amount')
                    ->label('مبلغ')
                    ->formatStateUsing(fn (int $state): string => number_format($state) . ' تومان')
                    ->sortable(),
                Tables\Columns\BadgeColumn::make('status')
                    ->label('وضعیت')
                    ->formatStateUsing(fn (string $state): string => match($state) {
                        'pending' => 'در حال بررسی',
                        'ok' => 'موفق',
                        'failed' => 'ناموفق',
                    })
                    ->color(fn (string $state): string => match($state) {
                        'pending' => 'yellow',
                        'ok' => 'green',
                        'failed' => 'red',
                    }),
                Tables\Columns\TextColumn::make('created_at')
                    ->label('تاریخ ایجاد')
                    ->dateTime('Y/m/d H:i')
                    ->sortable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('وضعیت')
                    ->options([
                        'pending' => 'در حال بررسی',
                        'ok' => 'موفق',
                        'failed' => 'ناموفق',
                    ]),
                Tables\Filters\SelectFilter::make('gateway')
                    ->label('درگاه')
                    ->options([
                        'zarinpal' => 'زرین‌پال',
                    ]),
                Tables\Filters\Filter::make('today')
                    ->label('امروز')
                    ->query(fn (Builder $query): Builder => $query->whereDate('created_at', today())),
                Tables\Filters\Filter::make('this_week')
                    ->label('این هفته')
                    ->query(fn (Builder $query): Builder => $query->where('created_at', '>=', now()->startOfWeek())),
                Tables\Filters\Filter::make('successful')
                    ->label('موفق')
                    ->query(fn (Builder $query): Builder => $query->where('status', 'ok')),
                Tables\Filters\Filter::make('failed')
                    ->label('ناموفق')
                    ->query(fn (Builder $query): Builder => $query->where('status', 'failed')),
            ])
            ->actions([
                Tables\Actions\ViewAction::make(),
                Tables\Actions\EditAction::make(),
                Tables\Actions\Action::make('mark_ok')
                    ->label('تأیید پرداخت')
                    ->icon('heroicon-o-check-circle')
                    ->color('success')
                    ->action(function (Payment $record): void {
                        $record->update(['status' => 'ok']);
                    })
                    ->visible(fn (Payment $record): bool => $record->status === 'pending'),
                Tables\Actions\Action::make('mark_failed')
                    ->label('لغو پرداخت')
                    ->icon('heroicon-o-x-circle')
                    ->color('danger')
                    ->action(function (Payment $record): void {
                        $record->update(['status' => 'failed']);
                    })
                    ->visible(fn (Payment $record): bool => $record->status === 'pending'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\BulkAction::make('mark_selected_ok')
                        ->label('تأیید انتخاب شده‌ها')
                        ->icon('heroicon-o-check-circle')
                        ->color('success')
                        ->action(function ($records): void {
                            $records->each(function ($record) {
                                $record->update(['status' => 'ok']);
                            });
                        }),
                    Tables\Actions\BulkAction::make('mark_selected_failed')
                        ->label('لغو انتخاب شده‌ها')
                        ->icon('heroicon-o-x-circle')
                        ->color('danger')
                        ->action(function ($records): void {
                            $records->each(function ($record) {
                                $record->update(['status' => 'failed']);
                            });
                        }),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPayments::route('/'),
            'create' => Pages\CreatePayment::route('/create'),
            'view' => Pages\ViewPayment::route('/{record}'),
            'edit' => Pages\EditPayment::route('/{record}/edit'),
        ];
    }

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::where('status', 'pending')->count();
    }
}

