<?php

namespace App\Filament\Pages\Statistics;

use App\Services\QuestionBankService;
use BackedEnum;
use Filament\Pages\Page;
use UnitEnum;
use Livewire\Attributes\Computed;
use Illuminate\Support\Facades\Cache;

class KnowledgePointStats extends Page
{
    protected static ?string $title = '知识点题目统计';
    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-chart-bar';
    protected static ?string $navigationLabel = '知识点统计';
    protected static string|UnitEnum|null $navigationGroup = null;
    protected static ?int $navigationSort = 8;
    protected static bool $shouldRegisterNavigation = false;
    protected string $view = 'filament.pages.knowledge-point-stats';

    public ?string $selectedKpCode = null;
    public bool $showDetails = false;

    #[Computed(cache: false)]
    public function knowledgePointStatistics(): array
    {
        $cacheKey = 'knowledge-point-statistics';
        if ($this->selectedKpCode) {
            $cacheKey .= '-' . $this->selectedKpCode;
        }

        return Cache::remember(
            $cacheKey,
            now()->addMinutes(10),
            function () {
                $service = app(QuestionBankService::class);

                if ($this->selectedKpCode) {
                    $stats = $service->getKnowledgePointStatistics($this->selectedKpCode);
                    return [$stats]; // 返回数组格式
                }

                return $service->getKnowledgePointStatistics();
            }
        );
    }

    #[Computed(cache: false)]
    public function knowledgePointOptions(): array
    {
        try {
            $knowledgeApiBase = config('services.knowledge_api.base_url', 'http://localhost:5011');
            $response = \Illuminate\Support\Facades\Http::timeout(10)
                ->get($knowledgeApiBase . '/graph/export');

            if ($response->successful()) {
                $data = $response->json();
                $nodes = $data['nodes'] ?? [];

                $options = [];
                foreach ($nodes as $node) {
                    $code = $node['kp_code'] ?? null;
                    $name = $node['cn_name'] ?? null;

                    if ($code && $name) {
                        $options[$code] = $name;
                    }
                }

                ksort($options);
                return $options;
            }
        } catch (\Exception $e) {
            \Log::error('Failed to get knowledge points: ' . $e->getMessage());
        }

        return [];
    }

    public function updatedSelectedKpCode(): void
    {
        $this->showDetails = false;
        Cache::forget('knowledge-point-statistics-' . $this->selectedKpCode);
    }

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

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

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

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

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