<?php

namespace App\Filament\Resources\PaymentAnalytics;

use App\Filament\Resources\PaymentAnalytics\Pages;
use App\Models\Payment;
use App\Models\TravelAgent;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Actions;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use BackedEnum;

class PaymentAnalyticsResource extends Resource
{
    protected static ?string $model = Payment::class;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-currency-rupee';

    protected static ?string $navigationLabel = 'Payment Analytics';

    protected static ?string $modelLabel = 'Payment Analytics';

    protected static ?string $pluralModelLabel = 'Payment Analytics';

    public static function getNavigationGroup(): ?string
    {
        return 'Analytics';
    }

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

    public static function getNavigationBadgeColor(): ?string
    {
        return 'success';
    }

   public static function form(Schema $schema): Schema
    {
        return $schema
            ->schema([
                \Filament\Schemas\Components\Section::make('Payment Information')
                ->schema([
                    \Filament\Forms\Components\Select::make('travel_agent_id')
                        ->label('Travel Agent')
                        ->relationship('travelAgent', 'name')
                        ->disabled()
                        ->dehydrated(false),
                        
                    
                    \Filament\Forms\Components\TextInput::make('razorpay_payment_id')
                        ->label('Payment ID')
                        ->disabled(),
                    
                    \Filament\Forms\Components\TextInput::make('amount')
                        ->label('Amount')
                        ->disabled()
                        ->prefix('₹'),
                    
                    \Filament\Forms\Components\TextInput::make('currency')
                        ->label('Currency')
                        ->disabled(),
                    
                    \Filament\Forms\Components\TextInput::make('status')
                        ->label('Status')
                        ->disabled(),
                    
                    \Filament\Forms\Components\TextInput::make('entity_type')
                        ->label('Payment For')
                        ->formatStateUsing(fn ($state) => match($state) {
                            'plan' => 'Subscription',
                            'top_up' => 'Top-up',
                            default => ucfirst($state)
                        })
                        ->disabled(),
                    
                    \Filament\Forms\Components\TextInput::make('created_at')
                        ->label('Payment Date')
                        ->disabled(),
                ])
                ->columns(2),
            
            \Filament\Schemas\Components\Section::make('Additional Details')
                ->schema([
                    \Filament\Forms\Components\TextInput::make('razorpay_order_id')
                        ->label('Order ID')
                        ->disabled()
                        ->hidden(fn ($get) => true), // Alternative to toggleable
                    
                    \Filament\Forms\Components\TextInput::make('method')
                        ->label('Payment Method')
                        ->disabled()
                        ->hidden(fn ($get) => true), // Alternative to toggleable
                    
                    \Filament\Forms\Components\TextInput::make('bank')
                        ->label('Bank')
                        ->disabled()
                        ->hidden(fn ($get) => true), // Alternative to toggleable
                    
                    \Filament\Forms\Components\TextInput::make('wallet')
                        ->label('Wallet')
                        ->disabled()
                        ->hidden(fn ($get) => true), // Alternative to toggleable
                    
                    \Filament\Forms\Components\TextInput::make('card_id')
                        ->label('Card ID')
                        ->disabled()
                        ->hidden(fn ($get) => true), // Alternative to toggleable
                    
                    \Filament\Forms\Components\TextInput::make('vpa')
                        ->label('UPI ID')
                        ->disabled()
                        ->hidden(fn ($get) => true), // Alternative to toggleable
                ])
                ->columns(2)
                
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('travelAgent.name')
                    ->label('Travel Agent')
                    ->searchable()
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('razorpay_payment_id')
                    ->label('Payment ID')
                    ->searchable()
                    ->copyable()
                    ->copyMessage('Payment ID copied!')
                    ->toggleable(isToggledHiddenByDefault: true),
                
                Tables\Columns\TextColumn::make('amount')
                    ->label('Amount')
                    ->money('INR')
                    ->sortable()
                    ->alignCenter(),
                
                Tables\Columns\TextColumn::make('currency')
                    ->label('Currency')
                    ->badge()
                    ->alignCenter(),
                
                Tables\Columns\TextColumn::make('status')
                    ->label('Status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'captured' => 'success',
                        'created' => 'warning',
                        'failed' => 'danger',
                        'refunded' => 'info',
                        default => 'gray',
                    })
                    ->sortable()
                    ->alignCenter(),
                
                Tables\Columns\TextColumn::make('entity_type')
                    ->label('Payment For')
                    ->formatStateUsing(fn ($state) => match($state) {
                        'plan' => 'Subscription',
                        'top_up' => 'Top-up',
                        default => ucfirst($state)
                    })
                    ->badge()
                    ->color(fn ($state) => match($state) {
                        'plan' => 'primary',
                        'top_up' => 'success',
                        default => 'gray'
                    })
                    ->alignCenter(),
                
                Tables\Columns\TextColumn::make('created_at')
                    ->label('Payment Date')
                    ->dateTime()
                    ->sortable()
                    ->alignCenter(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('travel_agent_id')
                    ->label('Travel Agent')
                    ->options(TravelAgent::pluck('name', 'id'))
                    ->searchable(),
                
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        'created' => 'Created',
                        'captured' => 'Success',
                        'failed' => 'Failed',
                        'refunded' => 'Refunded',
                    ]),
                
                Tables\Filters\SelectFilter::make('entity_type')
                    ->label('Payment Type')
                    ->options([
                        'plan' => 'Subscription',
                        'top_up' => 'Top-up',
                    ]),
                
                Tables\Filters\Filter::make('created_at')
                    ->form([
                        DatePicker::make('created_from')
                            ->label('From Date'),
                        DatePicker::make('created_until')
                            ->label('To Date'),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['created_from'],
                                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '>=', $date),
                            )
                            ->when(
                                $data['created_until'],
                                fn (Builder $query, $date): Builder => $query->whereDate('created_at', '<=', $date),
                            );
                    }),
                
                Tables\Filters\Filter::make('amount_range')
                    ->form([
                        \Filament\Forms\Components\TextInput::make('min_amount')
                            ->label('Min Amount (₹)')
                            ->numeric(),
                        \Filament\Forms\Components\TextInput::make('max_amount')
                            ->label('Max Amount (₹)')
                            ->numeric(),
                    ])
                    ->query(function (Builder $query, array $data): Builder {
                        return $query
                            ->when(
                                $data['min_amount'],
                                fn (Builder $query, $amount): Builder => $query->where('amount', '>=', $amount),
                            )
                            ->when(
                                $data['max_amount'],
                                fn (Builder $query, $amount): Builder => $query->where('amount', '<=', $amount),
                            );
                    }),
            ])
            ->actions([
                Actions\ViewAction::make(),
            ])
            ->bulkActions([
                Actions\BulkActionGroup::make([
                    Actions\ExportBulkAction::make(),
                ]),
            ])
            ->defaultSort('created_at', 'desc')
            ->deferFilters();
    }

    public static function getRelations(): array
    {
        return [];
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListPaymentAnalytics::route('/'),
            'view' => Pages\ViewPaymentAnalytics::route('/{record}'),
        ];
    }
}