<?php

namespace App\Filament\Pages;

use App\Services\KnowledgeGraphService;
use App\Services\LearningAnalyticsService;
use BackedEnum;
use Filament\Pages\Page;
use UnitEnum;

class StudentAnalysis 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 = '资源';
    protected static ?int $navigationSort = 24;

    protected string $view = 'filament.pages.student-analysis-simple';

    /**
     * 禁用导航显示（与"学生仪表板"功能重复）
     */
    public static function shouldRegisterNavigation(): bool
    {
        return false;
    }

    // 当前选中的学生
    public ?string $selectedStudentId = null;
    public array $studentInfo = [];
    public array $masteryData = [];
    public array $weaknesses = [];
    public array $skills = [];
    public array $learningPath = [];

    /**
     * 获取所有学生列表
     */
    public function students(): array
    {
        return \App\Models\Student::all()->toArray();
    }

    public function updatedSelectedStudentId($value)
    {
        if ($value) {
            $this->loadAnalysisData();
        } else {
            $this->reset(['studentInfo', 'masteryData', 'weaknesses', 'skills', 'learningPath']);
        }
    }

    public function loadAnalysisData()
    {
        if (!$this->selectedStudentId) {
            return;
        }

        $learningService = app(LearningAnalyticsService::class);

        // 1. 获取学生掌握度数据
        $this->studentInfo = $learningService->getStudentMastery($this->selectedStudentId);

        // 2. 获取薄弱点列表
        $this->weaknesses = $learningService->getStudentWeaknesses($this->selectedStudentId, 15);

        // 3. 获取技能熟练度（如果有API的话）
        $this->skills = $this->getSkillsData($this->selectedStudentId);

        // 4. 获取学习路径建议
        $pathData = $learningService->recommendLearningPaths($this->selectedStudentId, 5);
        $this->learningPath = $pathData['recommendations'] ?? [];

        // 5. 获取知识点掌握度详情
        $this->masteryData = $this->getMasteryDetails($this->selectedStudentId);
    }

    private function getSkillsData(string $studentId): array
    {
        // TODO: 从LearningAnalytics服务获取技能熟练度数据
        return [];
    }

    private function getMasteryDetails(string $studentId): array
    {
        try {
            // 从MySQL直接查询学生掌握度详情
            $db = app('db');
            $db->connection('remote_mysql');

            $masteryRecords = \Illuminate\Support\Facades\DB::connection('remote_mysql')
                ->table('student_mastery as sm')
                ->join('knowledge_points as kp', 'sm.kp', '=', 'kp.kp')
                ->where('sm.student_id', $studentId)
                ->select([
                    'sm.kp as kp_code',
                    'kp.cn_name as kp_name',
                    'sm.mastery',
                    'sm.stability',
                    'sm.update_time'
                ])
                ->orderBy('sm.mastery', 'asc')
                ->limit(50)
                ->get()
                ->toArray();

            return array_map(function ($record) {
                return [
                    'kp_code' => $record->kp_code,
                    'kp_name' => $record->kp_name,
                    'mastery' => (float) $record->mastery,
                    'stability' => (float) $record->stability,
                    'update_time' => $record->update_time,
                    'mastery_level' => $this->getMasteryLevel((float) $record->mastery),
                    'weakness_score' => 1.0 - (float) $record->mastery
                ];
            }, $masteryRecords);
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('获取掌握度详情失败', [
                'student_id' => $studentId,
                'error' => $e->getMessage()
            ]);
            return [];
        }
    }

    private function getMasteryLevel(float $mastery): string
    {
        if ($mastery >= 0.9) return '优秀';
        if ($mastery >= 0.8) return '良好';
        if ($mastery >= 0.7) return '中等';
        if ($mastery >= 0.6) return '及格';
        return '需提升';
    }

    public function getMasteryColor(float $mastery): string
    {
        if ($mastery >= 0.9) return '#10b981'; // emerald-500
        if ($mastery >= 0.8) return '#34d399'; // emerald-400
        if ($mastery >= 0.7) return '#fbbf24'; // amber-400
        if ($mastery >= 0.6) return '#fb923c'; // orange-400
        return '#ef4444'; // red-500
    }

    public function getMasteryBgColor(float $mastery): string
    {
        if ($mastery >= 0.9) return 'bg-emerald-100';
        if ($mastery >= 0.8) return 'bg-emerald-50';
        if ($mastery >= 0.7) return 'bg-amber-100';
        if ($mastery >= 0.6) return 'bg-orange-100';
        return 'bg-red-100';
    }

    public function generateStudyPlan()
    {
        if (!$this->selectedStudentId || empty($this->weaknesses)) {
            return;
        }

        // TODO: 调用LearningAnalytics服务生成学习计划
        // 这里可以调用专门的API来生成个性化学习计划

        return redirect()->route('filament.admin.auth.learning-plan', [
            'student_id' => $this->selectedStudentId
        ]);
    }

    public function exportAnalysis()
    {
        if (!$this->selectedStudentId) {
            return;
        }

        // TODO: 导出分析报告为PDF或Excel
        // 可以调用专门的导出服务
    }
}
