<?php

namespace App\Filament\Pages;

use App\Services\QuestionBankService;
use App\Services\KnowledgeGraphService;
use App\Services\QuestionBankClient;
use Filament\Pages\Page;
use Illuminate\Support\Facades\Log;

class QuestionDetailPage extends Page
{
    
    protected string $view = 'filament.pages.question-detail';

    protected static ?string $slug = 'question-detail-legacy';

    protected static bool $shouldRegisterNavigation = false;

    public $questionId;
    public $mistakeId;
    public $questionData;
    public $mistakeData;
    public $sourceType; // 'bank' or 'mistake'
    public $studentId;

    public function mount(?string $questionId = null, ?string $mistakeId = null, ?string $studentId = null)
    {
        $this->questionId = $questionId;
        $this->mistakeId = $mistakeId;
        $this->studentId = $studentId;

        if ($mistakeId && $studentId) {
            $this->sourceType = 'mistake';
            $this->loadMistakeData();
        } elseif ($questionId) {
            $this->sourceType = 'bank';
            $this->loadQuestionData();
        }
    }

    protected function loadQuestionData(): void
    {
        try {
            $client = app(QuestionBankClient::class);
            $question = $client->getQuestion($this->questionId);

            if ($question) {
                $this->questionData = $question;

                // 获取相似题目
                $similarQuestions = $client->getSimilarQuestions($this->questionId, 5);
                $this->relatedQuestions = $similarQuestions['questions'] ?? [];
            }
        } catch (\Throwable $e) {
            Log::error('Failed to load question data', [
                'question_id' => $this->questionId,
                'error' => $e->getMessage()
            ]);
            $this->questionData = null;
        }
    }

    protected function loadMistakeData(): void
    {
        try {
            // 本地化：从MySQL获取错题详情，不再调用外部API
            $mistakeData = \Illuminate\Support\Facades\DB::table('student_mistakes')
                ->where('id', $this->mistakeId)
                ->where('student_id', $this->studentId)
                ->first();

            if ($mistakeData) {
                $this->mistakeData = (array) $mistakeData;

                // 如果有question_id，同时获取题库中的题目详情
                if (!empty($this->mistakeData['question_id'])) {
                    $client = app(QuestionBankClient::class);
                    $bankQuestion = $client->getQuestion($this->mistakeData['question_id']);
                    if ($bankQuestion) {
                        // 合并题库数据和错题数据
                        $this->questionData = array_merge($bankQuestion, [
                            'mistake_info' => [
                                'student_answer' => $this->mistakeData['student_answer'] ?? '',
                                'correct' => $this->mistakeData['correct'] ?? false,
                                'score' => $this->mistakeData['score'] ?? 0,
                                'full_score' => $this->mistakeData['full_score'] ?? 0,
                                'partial_score_ratio' => $this->mistakeData['partial_score_ratio'] ?? 0,
                                'error_type' => $this->mistakeData['error_type'] ?? '',
                                'mistake_category' => $this->mistakeData['mistake_category'] ?? '',
                                'ai_analysis' => json_decode($this->mistakeData['ai_analysis'] ?? '[]', true),
                                'created_at' => $this->mistakeData['created_at'] ?? '',
                            ]
                        ]);
                    }
                }
            }
        } catch (\Throwable $e) {
            Log::error('Failed to load mistake data', [
                'mistake_id' => $this->mistakeId,
                'student_id' => $this->studentId,
                'error' => $e->getMessage()
            ]);
        }
    }

    public function getTitle(): string
    {
        $title = '题目详情';

        if ($this->sourceType === 'mistake') {
            $title = '错题分析 - ' . ($this->mistakeData['question']['question_number'] ?? '#' . $this->mistakeId);
        } elseif ($this->sourceType === 'bank' && $this->questionData) {
            $title = '题库详情 - ' . substr($this->questionData['stem'], 0, 30) . '...';
        }

        return $title;
    }

    public function getBreadcrumbs(): array
    {
        $breadcrumbs = [];

        $breadcrumbs[] = [
            'url' => url('/admin'),
            'name' => '首页',
        ];

        if ($this->sourceType === 'mistake') {
            $breadcrumbs[] = [
                'url' => url('/admin/mistake-book'),
                'name' => '错题本',
            ];
        } else {
            $breadcrumbs[] = [
                'url' => url('/admin/question-management'),
                'name' => '题库管理',
            ];
        }

        $breadcrumbs[] = [
            'url' => '',
            'name' => $this->getTitle(),
        ];

        return $breadcrumbs;
    }

    public function getKnowledgePointName(): string
    {
        $kpCode = '';

        if ($this->questionData && !empty($this->questionData['kp_code'])) {
            $kpCode = $this->questionData['kp_code'];
        } elseif ($this->mistakeData && !empty($this->mistakeData['question']['kp_code'])) {
            $kpCode = $this->mistakeData['question']['kp_code'];
        }

        if (!$kpCode) {
            return '未知知识点';
        }

        // 尝试从缓存获取知识点名称
        static $knowledgePoints = null;
        if ($knowledgePoints === null) {
            try {
                $service = app(KnowledgeGraphService::class);
                $kps = $service->listKnowledgePoints(1, 1000);
                $knowledgePoints = [];
                foreach ($kps['data'] ?? [] as $kp) {
                    $code = $kp['kp_code'] ?? $kp['id'];
                    $name = $kp['cn_name'] ?? $kp['name'] ?? $code;
                    $knowledgePoints[$code] = $name;
                }
            } catch (\Throwable $e) {
                Log::error('Failed to load knowledge points');
            }
        }

        return $knowledgePoints[$kpCode] ?? $kpCode;
    }

    public function getDifficultyColor(): string
    {
        $difficulty = 0.5;

        if ($this->questionData && isset($this->questionData['difficulty'])) {
            $difficulty = floatval($this->questionData['difficulty']);
        }

        if ($difficulty < 0.4) {
            return 'bg-green-100 text-green-700';
        } elseif ($difficulty < 0.7) {
            return 'bg-yellow-100 text-yellow-700';
        } else {
            return 'bg-red-100 text-red-700';
        }
    }

    public function getDifficultyLabel(): string
    {
        $difficulty = 0.5;

        if ($this->questionData && isset($this->questionData['difficulty'])) {
            $difficulty = floatval($this->questionData['difficulty']);
        }

        if ($difficulty < 0.4) {
            return '简单';
        } elseif ($difficulty < 0.7) {
            return '中等';
        } else {
            return '困难';
        }
    }
}
