<?php

namespace App\Filament\Resources;

use App\Filament\Resources\SourceFileResource\Pages;
use App\Filament\Resources\SourceFileResource\RelationManagers\SourcePapersRelationManager;
use App\Models\SourceFile;
use Filament\Forms;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Filament\Tables\Table;
use Filament\Actions\ViewAction;
use Illuminate\Database\Eloquent\Model;
use BackedEnum;
use UnitEnum;

class SourceFileResource extends Resource
{
    protected static ?string $model = SourceFile::class;

    protected static bool $shouldRegisterNavigation = false;

    protected static BackedEnum|string|null $navigationIcon = 'heroicon-o-rectangle-stack';

    protected static UnitEnum|string|null $navigationGroup = '卷子导入流程';

    protected static ?string $navigationLabel = '源文件';

    protected static ?int $navigationSort = 5;

    public static function canCreate(): bool
    {
        // 由后台脚本/服务创建，不允许手工创建
        return false;
    }

    public static function canEdit(Model $record): bool
    {
        return false;
    }

    public static function form(Schema $schema): Schema
    {
        return $schema->schema([
            Forms\Components\TextInput::make('original_filename')->label('原始文件名')->disabled(),
            Forms\Components\TextInput::make('normalized_filename')->label('标准化文件名')->disabled(),
            Forms\Components\KeyValue::make('extracted_metadata')->label('文件元数据')->disabled(),
            Forms\Components\Textarea::make('raw_markdown')
                ->label('原始 Markdown')
                ->rows(12)
                ->disabled(),
        ]);
    }

    public static function table(Table $table): Table
    {
        return $table
            ->columns([
                Tables\Columns\TextColumn::make('original_filename')->label('文件名')->searchable(),
                Tables\Columns\TextColumn::make('extracted_metadata.grade')->label('年级')->sortable(),
                Tables\Columns\TextColumn::make('extracted_metadata.term')->label('学期')->sortable(),
                Tables\Columns\TextColumn::make('extracted_metadata.chapter')->label('章节'),
                Tables\Columns\TextColumn::make('created_at')->label('导入时间')->dateTime(),
            ])
            ->actions([
                ViewAction::make(),
            ]);
    }

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

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