<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SettingResource\Pages;
use App\Models\Setting;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Tables\Filters\SelectFilter;
use Filament\Forms\Components\Section;
use Filament\Forms\Components\Tabs;
use Filament\Forms\Components\Grid;
use Filament\Forms\Components\Fieldset;
use Illuminate\Database\Eloquent\Builder;

class SettingResource extends Resource
{
    protected static ?string $model = Setting::class;

    protected static ?string $navigationIcon = 'heroicon-o-cog-6-tooth';

    protected static ?string $navigationGroup = 'System';

    protected static ?int $navigationSort = 1;

    protected static ?string $navigationLabel = 'Settings';

    protected static ?string $pluralLabel = 'Settings';

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Section::make('Setting Details')
                    ->schema([
                        Grid::make(2)
                            ->schema([
                                Forms\Components\TextInput::make('key')
                                    ->required()
                                    ->unique(ignoreRecord: true)
                                    ->maxLength(255)
                                    ->helperText('Unique identifier for this setting'),
                                
                                Forms\Components\Select::make('category')
                                    ->required()
                                    ->options([
                                        'general' => 'General',
                                        'telegram' => 'Telegram Bot',
                                        'payment' => 'Payment',
                                        'notification' => 'Notifications',
                                        'analytics' => 'Analytics',
                                        'security' => 'Security',
                                        'localization' => 'Localization',
                                        'module' => 'Module Configuration',
                                        'system' => 'System',
                                    ])
                                    ->default('general')
                                    ->searchable(),
                            ]),
                        
                        Forms\Components\TextInput::make('description')
                            ->maxLength(500)
                            ->helperText('Description of what this setting controls'),
                        
                        Grid::make(3)
                            ->schema([
                                Forms\Components\Select::make('type')
                                    ->required()
                                    ->options([
                                        'string' => 'String',
                                        'integer' => 'Integer',
                                        'boolean' => 'Boolean',
                                        'json' => 'JSON',
                                        'array' => 'Array',
                                        'float' => 'Float',
                                    ])
                                    ->default('string')
                                    ->live()
                                    ->afterStateUpdated(function ($state, callable $set) {
                                        // Clear value when type changes
                                        $set('value', null);
                                    }),
                                
                                Forms\Components\Toggle::make('is_active')
                                    ->default(true)
                                    ->helperText('Enable/disable this setting'),
                                
                                Forms\Components\Toggle::make('is_encrypted')
                                    ->default(false)
                                    ->helperText('Encrypt sensitive values'),
                            ]),
                    ]),

                Section::make('Value Configuration')
                    ->schema([
                        // String value
                        Forms\Components\TextInput::make('value')
                            ->label('Value')
                            ->visible(fn (Forms\Get $get): bool => $get('type') === 'string')
                            ->maxLength(1000),
                        
                        // Integer value
                        Forms\Components\TextInput::make('value')
                            ->label('Value')
                            ->visible(fn (Forms\Get $get): bool => $get('type') === 'integer')
                            ->numeric()
                            ->integer(),
                        
                        // Float value
                        Forms\Components\TextInput::make('value')
                            ->label('Value')
                            ->visible(fn (Forms\Get $get): bool => $get('type') === 'float')
                            ->numeric(),
                        
                        // Boolean value
                        Forms\Components\Toggle::make('value')
                            ->label('Value')
                            ->visible(fn (Forms\Get $get): bool => $get('type') === 'boolean'),
                        
                        // JSON/Array value
                        Forms\Components\Textarea::make('value')
                            ->label('Value (JSON format)')
                            ->visible(fn (Forms\Get $get): bool => in_array($get('type'), ['json', 'array']))
                            ->rows(5)
                            ->helperText('Enter valid JSON format'),
                    ]),

                Section::make('Advanced Options')
                    ->schema([
                        Forms\Components\Textarea::make('validation_rules')
                            ->label('Validation Rules (JSON)')
                            ->rows(3)
                            ->helperText('Laravel validation rules in JSON format, e.g., ["required", "min:1"]'),
                        
                        Forms\Components\Textarea::make('options')
                            ->label('Options (JSON)')
                            ->rows(3)
                            ->helperText('Options for select fields in JSON format, e.g., {"option1": "Label 1", "option2": "Label 2"}'),
                        
                        Forms\Components\TextInput::make('sort_order')
                            ->numeric()
                            ->default(0)
                            ->helperText('Order for displaying settings (lower numbers first)'),
                    ])
                    ->collapsible()
                    ->collapsed(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('key')
                    ->searchable()
                    ->sortable()
                    ->copyable()
                    ->weight('medium'),
                
                Tables\Columns\TextColumn::make('category')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'general' => 'gray',
                        'telegram' => 'blue',
                        'payment' => 'green',
                        'notification' => 'yellow',
                        'analytics' => 'purple',
                        'security' => 'red',
                        'localization' => 'orange',
                        'module' => 'indigo',
                        'system' => 'pink',
                        default => 'gray',
                    })
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('type')
                    ->badge()
                    ->color('info')
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('value')
                    ->limit(50)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        $state = $column->getState();
                        return is_string($state) && strlen($state) > 50 ? $state : null;
                    })
                    ->formatStateUsing(function ($state, Setting $record) {
                        if ($record->is_encrypted) {
                            return '••••••••';
                        }
                        
                        if (is_array($state) || is_object($state)) {
                            return json_encode($state);
                        }
                        
                        return $state;
                    }),
                
                Tables\Columns\IconColumn::make('is_active')
                    ->boolean()
                    ->trueColor('success')
                    ->falseColor('danger'),
                
                Tables\Columns\IconColumn::make('is_encrypted')
                    ->boolean()
                    ->trueIcon('heroicon-m-lock-closed')
                    ->falseIcon('heroicon-m-lock-open')
                    ->trueColor('warning')
                    ->falseColor('gray'),
                
                Tables\Columns\TextColumn::make('description')
                    ->limit(30)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        return $column->getState();
                    })
                    ->toggleable(),
                
                Tables\Columns\TextColumn::make('sort_order')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
                
                Tables\Columns\TextColumn::make('updated_at')
                    ->dateTime()
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                SelectFilter::make('category')
                    ->options([
                        'general' => 'General',
                        'telegram' => 'Telegram Bot',
                        'payment' => 'Payment',
                        'notification' => 'Notifications',
                        'analytics' => 'Analytics',
                        'security' => 'Security',
                        'localization' => 'Localization',
                        'module' => 'Module Configuration',
                        'system' => 'System',
                    ]),
                
                SelectFilter::make('type')
                    ->options([
                        'string' => 'String',
                        'integer' => 'Integer',
                        'boolean' => 'Boolean',
                        'json' => 'JSON',
                        'array' => 'Array',
                        'float' => 'Float',
                    ]),
                
                Tables\Filters\TernaryFilter::make('is_active')
                    ->label('Active Status'),
                
                Tables\Filters\TernaryFilter::make('is_encrypted')
                    ->label('Encrypted'),
            ])
            ->actions([
                Tables\Actions\EditAction::make(),
                Tables\Actions\DeleteAction::make(),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make(),
                ]),
            ])
            ->defaultSort('category')
            ->defaultSort('sort_order');
    }

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

    public static function getNavigationBadge(): ?string
    {
        return static::getModel()::count();
    }
}