<?php

namespace App\Filament\System\Resources;

use App\Filament\System\Resources\AssociationResource\Pages;
use App\Filament\System\Resources\AssociationResource\RelationManagers;
use App\Models\Association;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletingScope;

class AssociationResource extends Resource
{
    protected static ?string $model = Association::class;

    protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Tabs::make('Association Details')
                    ->tabs([
                        Forms\Components\Tabs\Tab::make('General Info')
                            ->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(Association::class, 'slug', ignoreRecord: true)
                                    ->maxLength(255),
                                Forms\Components\Select::make('association_type_id')
                                    ->relationship('type', 'name')
                                    ->required()
                                    ->preload()
                                    ->searchable(),
                                Forms\Components\TextInput::make('founded_year')
                                    ->numeric()
                                    ->minValue(1800)
                                    ->maxValue(date('Y')),
                                Forms\Components\Textarea::make('description')
                                    ->maxLength(65535)
                                    ->columnSpanFull(),
                                Forms\Components\Textarea::make('mission_statement')
                                    ->maxLength(65535)
                                    ->columnSpanFull(),
                            ])->columns(2),

                        Forms\Components\Tabs\Tab::make('Branding')
                            ->schema([
                                Forms\Components\FileUpload::make('logo_path')
                                    ->image()
                                    ->directory('associations/logos')
                                    ->label('Logo'),
                                Forms\Components\FileUpload::make('cover_image_path')
                                    ->image()
                                    ->directory('associations/covers')
                                    ->label('Cover Image'),
                                Forms\Components\ColorPicker::make('primary_color')
                                    ->default('#3b82f6'),
                                Forms\Components\ColorPicker::make('secondary_color')
                                    ->default('#1e293b'),
                            ])->columns(2),

                        Forms\Components\Tabs\Tab::make('Contact & Social')
                            ->schema([
                                Forms\Components\TextInput::make('email')->email()->maxLength(255),
                                Forms\Components\TextInput::make('phone')->tel()->maxLength(255),
                                Forms\Components\TextInput::make('phone_alt')->tel()->maxLength(255),
                                Forms\Components\TextInput::make('website')->url()->maxLength(255),
                                Forms\Components\TextInput::make('address')->maxLength(500)->columnSpanFull(),
                                Forms\Components\TextInput::make('city')->maxLength(255),
                                Forms\Components\TextInput::make('state')->maxLength(255),
                                Forms\Components\TextInput::make('country')->maxLength(255),
                                Forms\Components\Section::make('Social Links')
                                    ->schema([
                                        Forms\Components\TextInput::make('facebook')->url(),
                                        Forms\Components\TextInput::make('twitter')->url(),
                                        Forms\Components\TextInput::make('instagram')->url(),
                                        Forms\Components\TextInput::make('linkedin')->url(),
                                    ])->columns(2),
                            ])->columns(3),

                        Forms\Components\Tabs\Tab::make('Membership & Fees')
                            ->schema([
                                Forms\Components\Select::make('membership_mode')
                                    ->options([
                                        'free' => 'Free',
                                        'paid' => 'Paid',
                                    ])->required(),
                                Forms\Components\TextInput::make('membership_fee')
                                    ->numeric()
                                    ->prefix('NGN'),
                                Forms\Components\Select::make('membership_billing_cycle')
                                    ->options([
                                        'monthly' => 'Monthly',
                                        'quarterly' => 'Quarterly',
                                        'annually' => 'Annually',
                                    ]),
                            ])->columns(3),

                        Forms\Components\Tabs\Tab::make('Subscription & Limits')
                            ->schema([
                                Forms\Components\Select::make('status')
                                    ->options([
                                        'active' => 'Active',
                                        'suspended' => 'Suspended',
                                        'archived' => 'Archived',
                                    ])->required(),
                                Forms\Components\Select::make('subscription_status')
                                    ->options([
                                        'trial' => 'Trial',
                                        'active' => 'Active',
                                        'past_due' => 'Past Due',
                                        'suspended' => 'Suspended',
                                        'cancelled' => 'Cancelled',
                                        'expired' => 'Expired',
                                    ]),
                                Forms\Components\Select::make('subscription_plan_id')
                                    ->relationship('subscriptionPlan', 'name')
                                    ->label('Current Plan')
                                    ->preload()
                                    ->placeholder('No plan assigned')
                                    ->disabled()
                                    ->dehydrated(false)
                                    ->helperText('Plans are assigned via the subscription workflow.'),
                                Forms\Components\TextInput::make('max_members')
                                    ->numeric()
                                    ->default(100)
                                    ->helperText('Override: set by plan, but can be adjusted here.'),
                                Forms\Components\TextInput::make('storage_limit_mb')
                                    ->numeric()
                                    ->default(1024)
                                    ->label('Storage Limit (MB)')
                                    ->helperText('Override: set by plan, but can be adjusted here.'),
                                Forms\Components\DateTimePicker::make('subscription_ends_at')
                                    ->disabled()
                                    ->dehydrated(false),
                                Forms\Components\DateTimePicker::make('trial_ends_at')
                                    ->disabled()
                                    ->dehydrated(false),
                            ])->columns(3),
                    ])->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\ImageColumn::make('logo_path')
                    ->label('Logo')
                    ->circular(),
                Tables\Columns\TextColumn::make('name')
                    ->searchable()
                    ->sortable(),
                Tables\Columns\TextColumn::make('type.name')
                    ->sortable(),
                Tables\Columns\TextColumn::make('status')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'active' => 'success',
                        'suspended' => 'danger',
                        'archived' => 'warning',
                        default => 'gray',
                    }),
                Tables\Columns\TextColumn::make('current_member_count')
                    ->label('Members')
                    ->numeric()
                    ->sortable(),
                Tables\Columns\TextColumn::make('subscriptionPlan.name')
                    ->label('Plan')
                    ->placeholder('None')
                    ->sortable(),
                Tables\Columns\TextColumn::make('subscription_status')
                    ->badge()
                    ->color(fn (?string $state): string => match ($state) {
                        'active' => 'success',
                        'trial' => 'info',
                        'past_due', 'suspended' => 'danger',
                        'cancelled', 'expired' => 'gray',
                        default => 'warning',
                    }),
                Tables\Columns\TextColumn::make('created_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('association_type_id')
                    ->relationship('type', 'name')
                    ->label('Type'),
                Tables\Filters\SelectFilter::make('status')
                    ->options([
                        'active' => 'Active',
                        'suspended' => 'Suspended',
                        'pending_approval' => 'Pending Approval',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ]);
    }

    public static function getRelations(): array
    {
        return [
            RelationManagers\MembersRelationManager::class,
        ];
    }

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