<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TextbookCatalogResource\Pages;
use App\Models\Textbook;
use App\Models\TextbookCatalog;
use BackedEnum;
use UnitEnum;
use Filament\Resources\Resource;
use Filament\Forms\Components;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Columns\BadgeColumn;
use Filament\Actions\EditAction;
use Filament\Actions\DeleteAction;
use Filament\Actions\Action;
use Illuminate\Database\Eloquent\Model;

class TextbookCatalogResource extends Resource
{
    protected static ?string $model = TextbookCatalog::class;

    protected static ?string $recordTitleAttribute = 'title';

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-squares-2x2';

    protected static ?string $navigationLabel = '教材目录';

    protected static UnitEnum|string|null $navigationGroup = '教材管理';

    protected static ?int $navigationSort = 3;

    public static function form(Schema $schema): Schema
    {
        return $schema->components([
            Components\Select::make('textbook_id')
                ->label('教材')
                ->options(
                    Textbook::query()
                        ->orderBy('id')
                        ->get(['id', 'official_title'])
                        ->mapWithKeys(function ($textbook) {
                            $label = $textbook->official_title ?: '未命名教材';
                            return [$textbook->id => $label];
                        })
                        ->toArray()
                )
                ->searchable()
                ->required(),
            Components\TextInput::make('title')
                ->label('目录标题')
                ->required(),
            Components\TextInput::make('display_no')
                ->label('编号'),
            Components\Select::make('node_type')
                ->label('类型')
                ->options([
                    'chapter' => '章',
                    'section' => '节',
                    'subsection' => '小节',
                    'item' => '条目',
                    'project' => '项目学习',
                    'reading' => '阅读材料',
                    'practice' => '综合实践',
                    'summary' => '复习',
                    'appendix' => '附录',
                ])
                ->required(),
            Components\TextInput::make('depth')
                ->label('层级')
                ->numeric(),
            Components\TextInput::make('sort_order')
                ->label('排序')
                ->numeric(),
            Components\TextInput::make('page_start')
                ->label('起始页码')
                ->numeric(),
            Components\TextInput::make('page_end')
                ->label('结束页码')
                ->numeric(),
        ])->columns(2);
    }

    public static function table(Tables\Table $table): Tables\Table
    {
        return $table
            ->columns([
                TextColumn::make('textbook.series_name')
                    ->label('教材系列')
                    ->searchable()
                    ->wrap(),

                TextColumn::make('textbook.official_title')
                    ->label('教材')
                    ->searchable()
                    ->wrap(),

                TextColumn::make('title')
                    ->label('目录标题')
                    ->searchable()
                    ->wrap(),

                TextColumn::make('display_no')
                    ->label('编号')
                    ->searchable(),

                BadgeColumn::make('node_type')
                    ->label('类型')
                    ->formatStateUsing(fn (string $state): string => match ($state) {
                        'chapter' => '章',
                        'section' => '节',
                        'subsection' => '小节',
                        'item' => '条目',
                        'project' => '项目学习',
                        'reading' => '阅读材料',
                        'practice' => '综合实践',
                        'summary' => '复习',
                        'appendix' => '附录',
                        default => '其他',
                    })
                    ->color('info'),

                TextColumn::make('depth')
                    ->label('层级')
                    ->sortable(),

                TextColumn::make('page_start')
                    ->label('起始页码')
                    ->sortable(),

                TextColumn::make('page_end')
                    ->label('结束页码')
                    ->sortable(),

                TextColumn::make('created_at')
                    ->label('创建时间')
                    ->dateTime('Y-m-d H:i')
                    ->sortable()
                    ->toggleable(),
            ])
            ->filters([
                Tables\Filters\SelectFilter::make('textbook_id')
                    ->label('教材')
                    ->options(function () {
                        return Textbook::query()
                            ->orderBy('id')
                            ->get(['id', 'official_title'])
                            ->mapWithKeys(function ($textbook) {
                                $label = $textbook->official_title ?: '未命名教材';
                                return [$textbook->id => $label];
                            })
                            ->toArray();
                    })
                    ->searchable()
                    ->preload(),

                Tables\Filters\SelectFilter::make('node_type')
                    ->label('节点类型')
                    ->options([
                        'chapter' => '章',
                        'section' => '节',
                        'subsection' => '小节',
                        'item' => '条目',
                        'project' => '项目学习',
                        'reading' => '阅读材料',
                        'practice' => '综合实践',
                        'summary' => '复习',
                        'appendix' => '附录',
                        'custom' => '其他',
                    ]),
            ])
            ->actions([
                EditAction::make()
                    ->label('编辑'),

                Action::make('delete')
                    ->label('删除')
                    ->color('danger')
                    ->icon('heroicon-o-trash')
                    ->requiresConfirmation()
                    ->modalHeading('删除教材目录')
                    ->modalDescription('确定要删除这个教材目录吗？此操作无法撤销。')
                    ->action(function (Model $record) {
                        $record->delete();
                        return redirect()->refresh();
                    }),
            ])
            ->paginated([10, 25, 50, 100])
            ->poll(null);  // 禁用自动刷新
    }

    public static function getEloquentQuery(): \Illuminate\Database\Eloquent\Builder
    {
        return parent::getEloquentQuery()
            ->with(['textbook', 'textbook.series']);
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ManageTextbookCatalogs::route('/'),
        ];
    }

    public static function canViewAny(): bool
    {
        // 临时允许所有用户查看，等待权限系统完善
        return true;
    }

    public static function canCreate(): bool
    {
        // 临时允许所有用户创建，等待权限系统完善
        return true;
    }

    public static function canEdit(Model $record): bool
    {
        // 临时允许所有用户编辑，等待权限系统完善
        return true;
    }

    public static function canDelete(Model $record): bool
    {
        // 临时允许所有用户删除，等待权限系统完善
        return true;
    }

    public static function canDeleteAny(): bool
    {
        // 临时允许所有用户批量删除，等待权限系统完善
        return true;
    }

    protected static function deleteRecord(Model $record): bool
    {
        return (bool) $record->delete();
    }
}
