<?php

namespace App\Filament\System\Resources;

use App\Filament\System\Resources\SubscriptionPlanResource\Pages;
use App\Models\SubscriptionPlan;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class SubscriptionPlanResource extends Resource
{
    protected static ?string $model = SubscriptionPlan::class;

    protected static ?string $navigationIcon = 'heroicon-o-credit-card';

    protected static ?string $navigationGroup = 'Subscriptions';

    protected static ?int $navigationSort = 1;

    protected static ?string $navigationLabel = 'Plans';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Tabs::make('Plan Details')
                    ->tabs([
                        Forms\Components\Tabs\Tab::make('General')
                            ->schema([
                                Forms\Components\TextInput::make('name')
                                    ->required()
                                    ->maxLength(255)
                                    ->live(onBlur: true)
                                    ->afterStateUpdated(fn (Forms\Set $set, ?string $state) => $set('slug', \Illuminate\Support\Str::slug($state))),
                                Forms\Components\TextInput::make('slug')
                                    ->required()
                                    ->unique(SubscriptionPlan::class, 'slug', ignoreRecord: true)
                                    ->maxLength(255),
                                Forms\Components\Textarea::make('description')
                                    ->maxLength(1000)
                                    ->columnSpanFull(),
                                Forms\Components\Toggle::make('is_active')
                                    ->default(true)
                                    ->label('Active'),
                                Forms\Components\TextInput::make('sort_order')
                                    ->numeric()
                                    ->default(0)
                                    ->label('Display Order'),
                            ])->columns(2),

                        Forms\Components\Tabs\Tab::make('Pricing')
                            ->schema([
                                Forms\Components\TextInput::make('price')
                                    ->required()
                                    ->numeric()
                                    ->prefix('NGN')
                                    ->minValue(0),
                                Forms\Components\Select::make('billing_cycle')
                                    ->required()
                                    ->options([
                                        'monthly' => 'Monthly',
                                        'quarterly' => 'Quarterly',
                                        'annually' => 'Annually',
                                    ])
                                    ->default('monthly'),
                                Forms\Components\TextInput::make('trial_duration_days')
                                    ->required()
                                    ->numeric()
                                    ->default(14)
                                    ->minValue(0)
                                    ->suffix('days')
                                    ->label('Trial Period'),
                            ])->columns(3),

                        Forms\Components\Tabs\Tab::make('Limits')
                            ->schema([
                                Forms\Components\TextInput::make('member_limit')
                                    ->required()
                                    ->numeric()
                                    ->default(50)
                                    ->minValue(-1)
                                    ->helperText('Set to -1 for unlimited members'),
                                Forms\Components\TextInput::make('storage_limit_mb')
                                    ->required()
                                    ->numeric()
                                    ->default(1000)
                                    ->suffix('MB')
                                    ->label('Storage Limit'),
                                Forms\Components\Toggle::make('custom_branding')
                                    ->default(false)
                                    ->label('Custom Branding'),
                                Forms\Components\Toggle::make('api_access')
                                    ->default(false)
                                    ->label('API Access'),
                            ])->columns(2),

                        Forms\Components\Tabs\Tab::make('Modules')
                            ->schema([
                                Forms\Components\CheckboxList::make('allowed_modules')
                                    ->options([
                                        'projects' => 'Projects & Causes',
                                        'elections' => 'Elections & Voting',
                                        'committees' => 'Committees',
                                        'gallery' => 'Gallery',
                                        'learning' => 'Learning Center',
                                        'polls' => 'Polls & Surveys',
                                        'work_profiles' => 'Work Profiles',
                                    ])
                                    ->label('Advanced Modules Included')
                                    ->helperText('Select which advanced modules are available in this plan. Core modules (Dashboard, Profile, Directory, Events, Payments, Notifications, Notices, Executives, Help, Recognitions) are always included.')
                                    ->columns(2)
                                    ->columnSpanFull(),
                            ]),

                        Forms\Components\Tabs\Tab::make('Features')
                            ->schema([
                                Forms\Components\Repeater::make('features')
                                    ->simple(
                                        Forms\Components\TextInput::make('feature')
                                            ->required()
                                            ->maxLength(255)
                                            ->placeholder('e.g. Unlimited events, Priority support'),
                                    )
                                    ->label('Marketing Features')
                                    ->helperText('Feature bullet points displayed on plan cards')
                                    ->defaultItems(0)
                                    ->addActionLabel('Add Feature')
                                    ->columnSpanFull(),
                            ]),
                    ])->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable()
                    ->weight('bold'),
                Tables\Columns\TextColumn::make('price')
                    ->money('NGN')
                    ->sortable(),
                Tables\Columns\TextColumn::make('billing_cycle')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'monthly' => 'info',
                        'quarterly' => 'warning',
                        'annually' => 'success',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('member_limit')
                    ->label('Members')
                    ->formatStateUsing(fn (int $state): string => $state === -1 ? 'Unlimited' : number_format($state)),
                Tables\Columns\TextColumn::make('allowed_modules')
                    ->label('Modules')
                    ->formatStateUsing(function ($state, $record): string {
                        $modules = $record->allowed_modules ?? [];
                        return count($modules) ? count($modules) . ' modules' : '0 modules';
                    })
                    ->color('primary'),
                Tables\Columns\TextColumn::make('trial_duration_days')
                    ->label('Trial')
                    ->suffix(' days'),
                Tables\Columns\IconColumn::make('is_active')
                    ->boolean()
                    ->label('Active'),
                Tables\Columns\TextColumn::make('associations_count')
                    ->counts('associations')
                    ->label('Associations')
                    ->sortable(),
                Tables\Columns\TextColumn::make('sort_order')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->defaultSort('sort_order')
            ->filters([
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Active'),
                Tables\Filters\SelectFilter::make('billing_cycle')
                    ->options([
                        'monthly' => 'Monthly',
                        'quarterly' => 'Quarterly',
                        'annually' => 'Annually',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\Action::make('duplicate')
                    ->icon('heroicon-o-document-duplicate')
                    ->action(function (SubscriptionPlan $record) {
                        $new = $record->replicate();
                        $new->name = $record->name . ' (Copy)';
                        $new->slug = \Illuminate\Support\Str::slug($new->name);
                        $new->is_active = false;
                        $new->uuid = null;
                        $new->save();
                    })
                    ->requiresConfirmation()
                    ->color('gray'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListSubscriptionPlans::route('/'),
            'create' => Pages\CreateSubscriptionPlan::route('/create'),
            'edit' => Pages\EditSubscriptionPlan::route('/{record}/edit'),
        ];
    }
}
