<?php

namespace App\Filament\Resources;

use App\Filament\Resources\TextbookResource\Pages;
use App\Filament\Resources\TextbookResource\Schemas\TextbookFormSchema;
use App\Filament\Resources\TextbookResource\Tables\TextbookTable;
use App\Filament\Resources\TextbookResource\Actions\DeleteTextbookAction;
use App\Models\Textbook;
use App\Services\TextbookApiService;
use BackedEnum;
use UnitEnum;
use Filament\Resources\Resource;
use Filament\Schemas\Schema;
use Filament\Tables;
use Illuminate\Database\Eloquent\Model;

class TextbookResource extends Resource
{
    protected static ?string $model = Textbook::class;

    protected static ?string $recordTitleAttribute = 'official_title';

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-book-open';

    protected static ?string $navigationLabel = '教材管理';

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

    protected static ?int $navigationSort = 2;

    protected static ?TextbookApiService $apiService = null;

    public static function boot()
    {
        parent::boot();
        static::$apiService = app(TextbookApiService::class);
    }

    protected static function getApiService(): TextbookApiService
    {
        if (!static::$apiService) {
            static::$apiService = app(TextbookApiService::class);
        }
        return static::$apiService;
    }

    public static function form(Schema $schema): Schema
    {
        return TextbookFormSchema::make($schema);
    }

    public static function table(Tables\Table $table): Tables\Table
    {
        return TextbookTable::make($table);
    }

    public static function getEloquentQuery(): \Illuminate\Database\Eloquent\Builder
    {
        // 返回空查询，实际数据通过 API 获取
        return parent::getEloquentQuery()->whereRaw('1=0');
    }

    public static function getRecords(): array
    {
        // 从 API 获取教材数据
        $apiService = static::getApiService();
        $result = $apiService->getTextbooks();

        \Log::info('TextbookResource::getRecords called', [
            'count' => count($result['data'] ?? []),
            'has_data' => !empty($result['data'])
        ]);

        $records = [];
        foreach ($result['data'] ?? [] as $item) {
            $model = new \App\Models\Textbook($item);
            $model->exists = true;
            $model->id = $item['id'];
            $records[] = $model;
        }

        return $records;
    }

    public static function resolveRecordRouteBinding(int | string $key, ?\Closure $modifyQuery = null): ?\Illuminate\Database\Eloquent\Model
    {
        $record = static::getApiService()->getTextbook((int) $key);
        if (!$record) {
            return null;
        }
        $model = new \App\Models\Textbook($record);
        $model->exists = true;
        $model->id = $record['id'];
        return $model;
    }

    public static function getPages(): array
    {
        return [
            'index' => Pages\ManageTextbooks::route('/'),
            'create' => Pages\CreateTextbook::route('/create'),
            'view' => Pages\ViewTextbook::route('/{record}'),
            'edit' => Pages\EditTextbook::route('/{record}/edit'),
        ];
    }

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

    public static function getHeaderActions(): array
    {
        return [
            \Filament\Actions\Action::make('import_excel')
                ->label('Excel导入')
                ->icon('heroicon-o-document-arrow-up')
                ->color('success')
                ->url(fn(): string =>
                    route('filament.admin.pages.textbook-excel-import-page')
                ),
        ];
    }

    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;
    }
}
