<?php

namespace App\Filament\Pages;

use App\Filament\Traits\HandlesMindmapDetails;
use BackedEnum;
use Filament\Pages\Page;
use UnitEnum;

class KnowledgeMindmap extends Page
{
    use HandlesMindmapDetails;

    protected static string|BackedEnum|null $navigationIcon = 'heroicon-o-share';

    protected static string|UnitEnum|null $navigationGroup = null;

    protected static ?int $navigationSort = 4;

    protected static ?string $navigationLabel = '知识图谱脑图';

    protected static bool $shouldRegisterNavigation = false;

    protected static ?string $slug = 'knowledge-mindmap';

    protected static ?string $title = '知识图谱脑图';

    protected string $view = 'filament.pages.knowledge-mindmap';

    public $teachers = [];
    public $students = [];
    public $selectedTeacherId = '';
    public $selectedStudentId = '';
    public $selectedStudentName = '';
    public $masteryData = [];
    public $drawerOpen = false;
    public $selectedNode = null;
    public $nodeDetails = [];

    public function mount(): void
    {
        $this->loadTeachers();
    }

    public function loadTeachers(): void
    {
        // Use the same logic as the controller but directly here
        $teachers = \App\Models\Teacher::query()
            ->select('teacher_id', 'name')
            ->limit(10)
            ->get();

        if ($teachers->isEmpty()) {
            $this->teachers = [
                ['teacher_id' => 1, 'name' => '张老师'],
                ['teacher_id' => 2, 'name' => '李老师'],
                ['teacher_id' => 3, 'name' => '王老师'],
            ];
        } else {
            $this->teachers = $teachers->toArray();
        }
    }

    public function updatedSelectedTeacherId(): void
    {
        $this->students = [];
        $this->selectedStudentId = '';
        $this->selectedStudentName = '';
        $this->masteryData = [];
        
        if (!$this->selectedTeacherId) {
            return;
        }

        $students = \App\Models\Student::query()
            ->where('teacher_id', $this->selectedTeacherId)
            ->select('student_id', 'name')
            ->limit(20)
            ->get();

        if ($students->isEmpty()) {
             $this->students = [
                ['student_id' => 101, 'name' => '学生A'],
                ['student_id' => 102, 'name' => '学生B'],
                ['student_id' => 103, 'name' => '学生C'],
            ];
        } else {
            $this->students = $students->toArray();
        }
    }

    public function updatedSelectedStudentId(): void
    {
        $this->masteryData = [];
        $this->selectedStudentName = '';
        
        if (!$this->selectedStudentId) {
            $this->dispatch('mastery-updated', data: []);
            return;
        }

        // Find student name
        $student = collect($this->students)->firstWhere('student_id', $this->selectedStudentId);
        $this->selectedStudentName = $student['name'] ?? '';

        try {
            $service = app(\App\Services\LearningAnalyticsService::class);
            $response = $service->getStudentMasteryList($this->selectedStudentId);
            
            $data = $response['data'] ?? [];
            
            // Transform to map: { 'KP_CODE': { mastery_level: 0.8, total_attempts: 5, ... } }
            $masteryMap = [];
            foreach ($data as $item) {
                if (isset($item['kp_code'])) {
                    $masteryMap[$item['kp_code']] = $item;
                }
            }
            
            $this->masteryData = $masteryMap;
            
            // Dispatch event to notify frontend to refresh graph
            $this->dispatch('mastery-updated', data: $masteryMap);

        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Failed to fetch mastery data', [
                'student_id' => $this->selectedStudentId,
                'error' => $e->getMessage()
            ]);
            $this->dispatch('mastery-updated', data: []);
        }
    }

    public function openDrawer($nodeId = null)
    {
        if ($nodeId) {
            $this->selectedNode = $nodeId;
            $this->nodeDetails = $this->getNodeDetails($nodeId, $this->masteryData);
        }
        $this->drawerOpen = true;
    }

    public function closeDrawer()
    {
        $this->drawerOpen = false;
        $this->selectedNode = null;
        $this->nodeDetails = [];
    }

    // Open drawer with prerequisites
    public function openPrerequisiteDrawer($nodeId)
    {
        $this->openDrawer($nodeId);
    }

    // Open drawer with successors
    public function openSuccessorDrawer($nodeId)
    {
        $this->openDrawer($nodeId);
    }

    // Alias for shared mindmap drawer
    public function openMindmapDrawer(string $nodeId): void
    {
        $this->openDrawer($nodeId);
    }

}
