<?php

namespace App\Filament\Pages;

use Filament\Forms;
use Filament\Pages\Page;
use Filament\Actions\Action;
use Filament\Schemas\Schema;
use Filament\Notifications\Notification;

class QuestionReview extends Page implements Forms\Contracts\HasForms
{
    use Forms\Concerns\InteractsWithForms;

    protected static string|\BackedEnum|null $navigationIcon = 'heroicon-o-clipboard-document-check';
    protected static string|\UnitEnum|null $navigationGroup = '题库管理';
    protected static ?string $title = '题目校验';
    protected static ?int $navigationSort = 4;
    protected string $view = 'filament.pages.question-review';

    public string $book = '';
    public int $page = 1;
    public array $mineru = [];
    public array $builder = [];
    public string $message = '';
    public bool $saving = false;
    public string $builderJson = '';
    public array $bookOptions = [];
    public array $pageOptions = [];
    public ?string $pagePngBase64 = null;
    public bool $showOverlay = true;
    public array $paths = [];

    public function mount(): void
    {
        // 默认值可在 .env 中配置
        $this->book = config('question_bank.default_book', '');
        $this->page = 1;
        // 预填可选书名（扫描 /data/mineru_raw）
        $root = base_path('../data/mineru_raw');
        $dirs = is_dir($root) ? scandir($root) : [];
        $opts = [];
        foreach ($dirs as $d) {
            if ($d === '.' || $d === '..') {
                continue;
            }
            if (is_dir($root . '/' . $d)) {
                $opts[] = $d;
            }
        }
        $this->bookOptions = $opts;
        if ($this->book) {
            $this->refreshPageOptions($this->book);
        }
    }

    public function form(Schema $form): Schema
    {
        return $form
            ->components([
                Forms\Components\Select::make('book')
                    ->label('书名/目录名')
                    ->options(array_combine($this->bookOptions, $this->bookOptions))
                    ->native(false)
                    ->searchable()
                    ->placeholder('选择书名目录')
                    ->reactive()
                    ->afterStateUpdated(fn($state) => $this->onBookChange($state))
                    ->required(),
                Forms\Components\Select::make('page')
                    ->label('页码')
                    ->options(fn() => array_combine(
                        array_map('strval', $this->pageOptions),
                        array_map(fn($p) => "第{$p}页", $this->pageOptions)
                    ))
                    ->native(false)
                    ->searchable()
                    ->placeholder('选择页码')
                    ->reactive()
                    ->afterStateUpdated(fn($state) => $this->onPageChange($state))
                    ->required(),
            ]);
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('load')
                ->label('加载')
                ->color('primary')
                ->action('loadPage'),
            Action::make('save')
                ->label('保存到草稿')
                ->color('success')
                ->disabled(fn() => empty($this->builder))
                ->action('saveDraft'),
            Action::make('toggleOverlay')
                ->label(fn() => $this->showOverlay ? '隐藏标框' : '显示标框')
                ->color('gray')
                ->action('toggleOverlay'),
        ];
    }

    protected function refreshPageOptions(string $book): void
    {
        $dir = base_path("../data/mineru_raw/{$book}/pages");
        $pages = [];
        if (is_dir($dir)) {
            foreach (glob($dir . '/page_*.json') as $file) {
                if (preg_match('/page_(\\d+)\\.json$/', $file, $m)) {
                    $pages[] = (int)$m[1];
                }
            }
        }
        sort($pages);
        $this->pageOptions = $pages;
        if (!empty($pages)) {
            $this->page = $pages[0];
        }
    }

    public function onBookChange($book): void
    {
        $this->book = (string)$book;
        $this->refreshPageOptions($this->book);
        if ($this->book && $this->page) {
            $this->loadPage();
        }
    }

    public function onPageChange($page): void
    {
        if ($page === null || $page === '') {
            return;
        }
        $this->page = (int)$page;
        if ($this->book) {
            $this->loadPage();
        }
    }

    public function toggleOverlay(): void
    {
        $this->showOverlay = !$this->showOverlay;
    }

    public function loadPage(): void
    {
        $this->mineru = [];
        $this->builder = [];
        $this->builderJson = '';
        $this->pagePngBase64 = null;
        $this->paths = [];
        $this->message = '题目校验已迁移到“题目审核工作台”，请使用新流程。';
    }

    public function saveDraft(): void
    {
        $this->message = '题目校验已迁移到“题目审核工作台”，该入口不再写入数据。';
        Notification::make()->title('已迁移')->body($this->message)->warning()->send();
    }

    public function saveQuestion(int $index): void
    {
        $this->message = '题目校验已迁移到“题目审核工作台”，该入口不再写入数据。';
        Notification::make()->title('已迁移')->body($this->message)->warning()->send();
    }
}
