<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SystemSettingResource\Pages;
use App\Models\SystemSetting;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class SystemSettingResource extends Resource
{
    protected static ?string $model = SystemSetting::class;

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

    protected static ?string $navigationLabel = '配置项管理';

    protected static ?string $modelLabel = '系统配置项';

    protected static ?string $pluralModelLabel = '系统配置项';

    protected static ?int $navigationSort = 1;

    protected static ?string $navigationGroup = '系统管理';

    /**
     * 控制导航菜单是否显示
     */
    public static function shouldRegisterNavigation(): bool
    {
        return auth()->user()?->can('system-setting.view') ?? false;
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\Tabs::make('配置表单')
                    ->tabs([
                        // 基本信息标签页
                        Forms\Components\Tabs\Tab::make('基本信息')
                            ->icon('heroicon-o-information-circle')
                            ->schema([
                                Forms\Components\TextInput::make('key')
                                    ->label('配置键')
                                    ->required()
                                    ->unique(ignoreRecord: true)
                                    ->maxLength(255)
                                    ->minLength(3)
                                    ->regex('/^[a-z0-9_\.]+$/')
                                    ->helperText('配置的唯一标识符，只能包含小写字母、数字、下划线和点，例如: embedding.model_name')
                                    ->placeholder('例如: system.name')
                                    ->validationMessages([
                                        'regex' => '配置键只能包含小写字母、数字、下划线和点',
                                    ]),
                                
                                Forms\Components\Select::make('group')
                                    ->label('配置分组')
                                    ->required()
                                    ->options([
                                        'embedding' => '嵌入模型',
                                        'chunking' => '分块参数',
                                        'system' => '系统配置',
                                        'search' => '搜索配置',
                                    ])
                                    ->native(false)
                                    ->helperText('选择配置所属的分组'),
                                
                                Forms\Components\Textarea::make('description')
                                    ->label('配置说明')
                                    ->rows(3)
                                    ->maxLength(65535)
                                    ->minLength(5)
                                    ->helperText('描述此配置项的用途（至少5个字符）')
                                    ->columnSpanFull(),
                                
                                Forms\Components\Toggle::make('is_public')
                                    ->label('公开配置')
                                    ->helperText('公开配置可以被前端访问')
                                    ->default(false)
                                    ->inline(false),
                            ]),
                        
                        // 配置值标签页
                        Forms\Components\Tabs\Tab::make('配置值')
                            ->icon('heroicon-o-cog-6-tooth')
                            ->schema([
                                Forms\Components\KeyValue::make('value')
                                    ->label('配置值')
                                    ->required()
                                    ->helperText('以键值对形式输入配置内容。键名应与配置键的最后一部分匹配。')
                                    ->addActionLabel('添加配置项')
                                    ->keyLabel('配置项名称')
                                    ->valueLabel('配置项值')
                                    ->reorderable(false)
                                    ->columnSpanFull(),
                            ]),
                    ])
                    ->columnSpanFull()
                    ->contained(false),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('key')
                    ->label('配置键')
                    ->searchable()
                    ->sortable()
                    ->copyable()
                    ->tooltip('点击复制'),
                
                Tables\Columns\TextColumn::make('group')
                    ->label('配置分组')
                    ->badge()
                    ->color(fn (string $state): string => match ($state) {
                        'embedding' => 'info',
                        'chunking' => 'success',
                        'system' => 'warning',
                        'search' => 'primary',
                        default => 'gray',
                    })
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'embedding' => '嵌入模型',
                        'chunking' => '分块参数',
                        'system' => '系统配置',
                        'search' => '搜索配置',
                        default => $state,
                    })
                    ->sortable(),
                
                Tables\Columns\TextColumn::make('description')
                    ->label('说明')
                    ->limit(50)
                    ->tooltip(function (Tables\Columns\TextColumn $column): ?string {
                        $state = $column->getState();
                        if (strlen($state) > 50) {
                            return $state;
                        }
                        return null;
                    }),
                
                Tables\Columns\IconColumn::make('is_public')
                    ->label('公开')
                    ->boolean()
                    ->trueIcon('heroicon-o-check-circle')
                    ->falseIcon('heroicon-o-x-circle')
                    ->trueColor('success')
                    ->falseColor('danger')
                    ->tooltip(fn (bool $state): string => $state ? '公开配置' : '私有配置'),
                
                Tables\Columns\TextColumn::make('updated_at')
                    ->label('更新时间')
                    ->dateTime('Y-m-d H:i:s')
                    ->sortable()
                    ->toggleable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('group')
                    ->label('配置分组')
                    ->options([
                        'embedding' => '嵌入模型',
                        'chunking' => '分块参数',
                        'system' => '系统配置',
                        'search' => '搜索配置',
                    ]),
                
                Tables\Filters\TernaryFilter::make('is_public')
                    ->label('公开状态')
                    ->placeholder('全部')
                    ->trueLabel('公开')
                    ->falseLabel('私有'),
            ])
            ->actions([
                Tables\Actions\ViewAction::make()
                    ->label('查看'),
                Tables\Actions\EditAction::make()
                    ->label('编辑'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->label('批量删除'),
                ]),
            ])
            ->defaultSort('group', 'asc');
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ListSystemSettings::route('/'),
            'create' => Pages\CreateSystemSetting::route('/create'),
            'edit' => Pages\EditSystemSetting::route('/{record}/edit'),
            'view' => Pages\ViewSystemSetting::route('/{record}'),
        ];
    }
}
