<?php

namespace App\Livewire\Integrations;

use Livewire\Component;
use App\Services\QuestionBankService;

class KnowledgePointStatsComponent extends Component
{
    public $selectedKpCode = null;
    public $statsData = [];
    public $isLoading = false;
    public $showDetails = false;

    protected $listeners = [
        'kpSelected' => 'handleKpSelected',
        'clearSelection' => 'clearSelection',
        'refreshStats' => 'loadStatsData',
    ];

    public function mount($selectedKpCode = null)
    {
        $this->selectedKpCode = $selectedKpCode;
        $this->loadStatsData();
    }

    public function loadStatsData()
    {
        $this->isLoading = true;
        try {
            $service = app(QuestionBankService::class);
            $this->statsData = $service->getKnowledgePointStatistics($this->selectedKpCode);
        } catch (\Exception $e) {
            \Log::error('加载知识点统计失败', [
                'kp_code' => $this->selectedKpCode,
                'error' => $e->getMessage()
            ]);
            $this->dispatch('error', message: '加载统计数据失败');
        }
        $this->isLoading = false;
    }

    public function handleKpSelected($kpCode)
    {
        $this->selectedKpCode = $kpCode;
        $this->loadStatsData();
    }

    public function clearSelection()
    {
        $this->selectedKpCode = null;
        $this->loadStatsData();
    }

    public function toggleDetails()
    {
        $this->showDetails = !$this->showDetails;
    }

    public function getTotalQuestions($stats)
    {
        return $stats['total_questions'] ?? 0;
    }

    public function getDirectQuestions($stats)
    {
        return $stats['direct_questions'] ?? 0;
    }

    public function getChildrenQuestions($stats)
    {
        return $stats['children_questions'] ?? 0;
    }

    public function getSkillQuestions($stats)
    {
        return $stats['skills_total_questions'] ?? 0;
    }

    public function render()
    {
        return view('livewire.integrations.knowledge-point-stats-component', [
            'statsData' => $this->statsData,
        ]);
    }
}
