<?php

namespace App\Filament\Resources;

use App\Filament\Resources\KnowledgeBaseResource\Pages;
use App\Models\KnowledgeBase;
use Filament\Forms;
use Filament\Forms\Form;
use Filament\Resources\Resource;
use Filament\Tables;
use Filament\Tables\Table;

class KnowledgeBaseResource extends Resource
{
    protected static ?string $model = KnowledgeBase::class;

    protected static ?string $navigationIcon = 'heroicon-o-book-open';

    protected static ?string $navigationLabel = '知识库管理';

    protected static ?string $modelLabel = '知识库';

    protected static ?string $pluralModelLabel = '知识库';

    protected static ?int $navigationSort = 1;

    protected static ?string $navigationGroup = '知识管理';

    public static function getEloquentQuery(): \Illuminate\Database\Eloquent\Builder
    {
        $query = parent::getEloquentQuery();
        $user = auth()->user();

        if ($user && $user->hasStationRestriction()) {
            $query->accessibleBy($user);
        }

        return $query;
    }

    public static function form(Form $form): Form
    {
        return $form
            ->schema([
                Forms\Components\TextInput::make('name')
                    ->label('知识库名称')
                    ->required()
                    ->maxLength(255)
                    ->placeholder('请输入知识库名称'),

                Forms\Components\Select::make('status')
                    ->label('状态')
                    ->options([
                        'active' => '启用',
                        'inactive' => '停用',
                    ])
                    ->default('active')
                    ->required(),

                Forms\Components\Textarea::make('description')
                    ->label('描述')
                    ->rows(3)
                    ->maxLength(65535)
                    ->placeholder('请输入知识库描述（可选）')
                    ->columnSpanFull(),

                Forms\Components\Select::make('stations')
                    ->label('关联线站')
                    ->relationship('stations', 'name')
                    ->multiple()
                    ->searchable()
                    ->preload()
                    ->helperText('选择知识库对哪些线站可用')
                    ->columnSpanFull(),
            ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('name')
                    ->label('知识库名称')
                    ->searchable()
                    ->sortable(),

                Tables\Columns\BadgeColumn::make('status')
                    ->label('状态')
                    ->colors([
                        'success' => 'active',
                        'danger' => 'inactive',
                    ])
                    ->formatStateUsing(fn(string $state): string => match ($state) {
                        'active' => '启用',
                        'inactive' => '停用',
                        default => $state,
                    })
                    ->sortable(),

                Tables\Columns\TextColumn::make('stations_count')
                    ->label('关联线站')
                    ->counts('stations')
                    ->sortable(),

                Tables\Columns\TextColumn::make('documents_count')
                    ->label('文档数量')
                    ->counts('documents')
                    ->sortable(),

                Tables\Columns\TextColumn::make('created_at')
                    ->label('创建时间')
                    ->dateTime('Y-m-d H:i:s')
                    ->sortable()
                    ->toggleable(),

                Tables\Columns\TextColumn::make('updated_at')
                    ->label('更新时间')
                    ->dateTime('Y-m-d H:i:s')
                    ->sortable()
                    ->toggleable(isToggledHiddenByDefault: true),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('status')
                    ->label('状态')
                    ->options([
                        'active' => '启用',
                        'inactive' => '停用',
                    ]),
            ])
            ->actions([
                Tables\Actions\EditAction::make()
                    ->label('编辑'),
                Tables\Actions\DeleteAction::make()
                    ->label('删除'),
            ])
            ->bulkActions([
                Tables\Actions\BulkActionGroup::make([
                    Tables\Actions\DeleteBulkAction::make()
                        ->label('批量删除'),
                ]),
            ])
            ->defaultSort('created_at', 'desc');
    }

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