<?php

namespace App\Filament\Pages;

use App\Jobs\ProcessOCRRecord;
use App\Models\OCRRecord;
use App\Models\Student;
use BackedEnum;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Livewire\Attributes\Computed;
use Livewire\WithPagination;
use UnitEnum;

class OCRRecordList extends Page
{
    use WithPagination;

    protected static ?string $title = 'OCR识别记录';
    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-camera';
    protected static ?string $navigationLabel = 'OCR识别记录';
    protected static string|UnitEnum|null $navigationGroup = '卷子生成管理';
    protected static ?int $navigationSort = 3;
    protected static ?string $slug = 'ocr-records';
    protected string $view = 'filament.pages.ocr-record-list';

    public ?string $filterStatus = null;
    public ?string $filterGrade = null;
    public ?string $filterClass = null;
    public ?string $search = null;
    public int $perPage = 10;

    #[Computed]
    public function records()
    {
        $query = OCRRecord::with('student')
            ->when($this->filterStatus, fn($q) => $q->where('status', $this->filterStatus))
            ->when($this->filterGrade, fn($q) => $q->whereHas('student', fn($sq) => $sq->where('grade', $this->filterGrade)))
            ->when($this->filterClass, fn($q) => $q->whereHas('student', fn($sq) => $sq->where('class_name', $this->filterClass)))
            ->when($this->search, fn($q) => $q->whereHas('student', fn($sq) => $sq->where('name', 'like', "%{$this->search}%")))
            ->latest();

        return $query->paginate($this->perPage);
    }

    #[Computed]
    public function grades(): array
    {
        return Student::distinct()->pluck('grade')->filter()->toArray();
    }

    #[Computed]
    public function classes(): array
    {
        return Student::distinct()->pluck('class_name')->filter()->toArray();
    }

    #[Computed]
    public function statistics(): array
    {
        return [
            'total' => OCRRecord::count(),
            'pending' => OCRRecord::where('status', 'pending')->count(),
            'processing' => OCRRecord::where('status', 'processing')->count(),
            'completed' => OCRRecord::where('status', 'completed')->count(),
            'failed' => OCRRecord::where('status', 'failed')->count(),
        ];
    }

    public function resetFilters(): void
    {
        $this->filterStatus = null;
        $this->filterGrade = null;
        $this->filterClass = null;
        $this->search = null;
        $this->resetPage();
    }

    public function updatedFilterStatus(): void
    {
        $this->resetPage();
    }

    public function updatedFilterGrade(): void
    {
        $this->resetPage();
    }

    public function updatedFilterClass(): void
    {
        $this->resetPage();
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function startRecognition(int $recordId): void
    {
        $record = OCRRecord::find($recordId);

        if (!$record) {
            Notification::make()
                ->title('记录不存在')
                ->danger()
                ->send();
            return;
        }

        if ($record->status === 'completed') {
            Notification::make()
                ->title('该记录已完成识别')
                ->warning()
                ->send();
            return;
        }

        if ($record->status === 'processing') {
            Notification::make()
                ->title('该记录正在处理中')
                ->info()
                ->send();
            return;
        }

        try {
            // 分发OCR处理任务
            ProcessOCRRecord::dispatch($recordId);

            Notification::make()
                ->title('已开始识别')
                ->body("记录 #{$recordId} 已加入处理队列")
                ->success()
                ->send();
        } catch (\Exception $e) {
            Notification::make()
                ->title('识别启动失败')
                ->body($e->getMessage())
                ->danger()
                ->send();
        }
    }
}
