<?php

namespace App\Filament\Pages;

use App\Services\QuestionBankService;
use App\Services\KnowledgeGraphService;
use BackedEnum;
use Filament\Pages\Page;
use Filament\Notifications\Notification;
use UnitEnum;

class RecommendationList extends Page
{
    protected static bool $shouldRegisterNavigation = false;
    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-sparkles';
    protected static ?string $title = '智能推荐';
    protected static ?string $navigationLabel = '智能推荐';
    protected static ?string $slug = 'recommendation-list';
    protected static ?int $navigationSort = 20;

    protected string $view = 'filament.pages.recommendation-list';
    
    public ?string $kpCode = null;
    public array $knowledgePoint = [];
    public array $recommendedQuestions = [];
    public bool $loading = true;

    public function mount(?string $kp = null)
    {
        $this->kpCode = $kp;

        if (!$kp) {
            Notification::make()
                ->title('参数错误')
                ->body('缺少知识点参数')
                ->warning()
                ->send();

            $this->redirectRoute('filament.admin.pages.exam-analysis');
            return;
        }

        $this->loadRecommendations();
    }

    protected function loadRecommendations()
    {
        try {
            $this->loading = true;

            // 1. 获取知识点信息
            $knowledgeService = app(KnowledgeGraphService::class);
            $kpList = $knowledgeService->listKnowledgePoints(1, 1000);

            if (isset($kpList['data'])) {
                foreach ($kpList['data'] as $kp) {
                    if ($kp['kp_code'] === $this->kpCode) {
                        $this->knowledgePoint = $kp;
                        break;
                    }
                }
            }

            // 2. 获取推荐题目
            $questionService = app(QuestionBankService::class);
            $response = $questionService->filterQuestions([
                'kp_codes' => $this->kpCode,
                'per_page' => 20,
                'sort' => 'difficulty' // 按难度排序
            ]);

            if (isset($response['data'])) {
                $this->recommendedQuestions = $response['data'];
            }

            // 3. 如果题目不足，生成更多推荐
            if (count($this->recommendedQuestions) < 10) {
                $this->recommendedQuestions = array_merge(
                    $this->recommendedQuestions,
                    $this->generateAdditionalQuestions()
                );
            }

            $this->loading = false;
        } catch (\Exception $e) {
            \Log::error('加载推荐题目失败', [
                'kp_code' => $this->kpCode,
                'error' => $e->getMessage()
            ]);

            Notification::make()
                ->title('加载失败')
                ->body('无法加载推荐题目，请稍后重试')
                ->danger()
                ->send();

            $this->loading = false;
        }
    }

    protected function generateAdditionalQuestions(): array
    {
        $kpName = $this->knowledgePoint['cn_name'] ?? $this->kpCode;
        $additional = [];

        // 基础题
        for ($i = 1; $i <= 5; $i++) {
            $additional[] = [
                'id' => "gen_basic_{$i}",
                'stem' => "{$kpName}基础练习题 {$i}",
                'question_type' => '基础题',
                'difficulty' => 'easy',
                'score' => 3,
                'kp_code' => $this->kpCode,
                'content' => "这是一道关于{$kpName}的基础练习题，帮助你巩固核心概念。"
            ];
        }

        // 提高题
        for ($i = 1; $i <= 5; $i++) {
            $additional[] = [
                'id' => "gen_advanced_{$i}",
                'stem' => "{$kpName}提高练习题 {$i}",
                'question_type' => '提高题',
                'difficulty' => 'hard',
                'score' => 8,
                'kp_code' => $this->kpCode,
                'content' => "这是一道关于{$kpName}的提高练习题，挑战你的解题能力。"
            ];
        }

        return $additional;
    }

    public function getDifficultyLabel(string $difficulty): string
    {
        return match($difficulty) {
            'easy' => '简单',
            'medium' => '中等',
            'hard' => '困难',
            default => '中等',
        };
    }

    public function getDifficultyColor(string $difficulty): string
    {
        return match($difficulty) {
            'easy' => 'green',
            'medium' => 'blue',
            'hard' => 'red',
            default => 'blue',
        };
    }

    public function getTitle(): string
    {
        if (!empty($this->knowledgePoint)) {
            return "{$this->knowledgePoint['cn_name']} - 智能推荐";
        }

        return '智能推荐';
    }
}
