<?php

namespace App\Livewire\UploadExam;

use Livewire\Component;
use App\Models\OCRRecord;

class OCRResults extends Component
{
    public ?int $ocrRecordId = null;
    public ?OCRRecord $ocrRecord = null;
    public array $ocrData = [];
    public bool $showResults = false;

    protected $listeners = [
        'showOCRResults' => 'showResults',
        'refreshResults' => '$refresh',
    ];

    #[On('showOCRResults')]
    public function showResults(int $ocrRecordId)
    {
        $this->ocrRecordId = $ocrRecordId;
        $this->loadOCRResults();
        $this->showResults = true;
    }

    public function loadOCRResults()
    {
        if (!$this->ocrRecordId) {
            return;
        }

        $this->ocrRecord = OCRRecord::find($this->ocrRecordId);

        if ($this->ocrRecord) {
            $this->ocrData = $this->ocrRecord->ocr_data ?? [];
        }
    }

    public function getQuestionsProperty()
    {
        return $this->ocrData['questions'] ?? [];
    }

    public function getPaperInfoProperty()
    {
        return [
            'name' => $this->ocrData['paper_name'] ?? '',
            'type' => $this->ocrData['paper_type'] ?? '',
            'total_questions' => count($this->questions),
        ];
    }

    public function acceptResults()
    {
        if ($this->ocrRecord) {
            $this->ocrRecord->update(['status' => 'completed']);
            $this->dispatch('ocrResultsAccepted', [
                'ocrData' => $this->ocrData,
            ]);
        }
    }

    public function rejectResults()
    {
        if ($this->ocrRecord) {
            $this->ocrRecord->update(['status' => 'rejected']);
            $this->dispatch('ocrResultsRejected');
        }
        $this->showResults = false;
    }

    public function render()
    {
        return view('livewire.upload-exam.ocr-results');
    }
}
