<?php

namespace App\Livewire\Integrations;

use Livewire\Component;
use App\Services\KnowledgeServiceApi;
use Illuminate\Support\Str;

class KnowledgePointsListComponent extends Component
{
    public $selectedKpCode = null;
    public $search = '';
    public $phaseFilter = null;
    public $categoryFilter = null;
    public $knowledgePoints = [];
    public $filteredPoints = [];
    public $isLoading = false;

    protected $listeners = [
        'selectKp' => 'selectKp',
        'clearSelection' => 'clearSelection',
    ];

    public function mount()
    {
        $this->loadKnowledgePoints();
    }

    public function loadKnowledgePoints()
    {
        $this->isLoading = true;
        try {
            $service = app(KnowledgeServiceApi::class);
            $points = $service->listKnowledgePoints(perPage: 200);
            $this->knowledgePoints = $points->toArray();
            $this->applyFilters();
        } catch (\Exception $e) {
            \Log::error('加载知识点列表失败', ['error' => $e->getMessage()]);
            $this->dispatch('error', message: '加载知识点列表失败');
        }
        $this->isLoading = false;
    }

    public function updatedSearch()
    {
        $this->applyFilters();
    }

    public function updatedPhaseFilter()
    {
        $this->applyFilters();
    }

    public function updatedCategoryFilter()
    {
        $this->applyFilters();
    }

    public function applyFilters()
    {
        $filtered = collect($this->knowledgePoints);

        // 按学段筛选
        if ($this->phaseFilter) {
            $filtered = $filtered->where('phase', $this->phaseFilter);
        }

        // 按类别筛选
        if ($this->categoryFilter) {
            $filtered = $filtered->where('category', $this->categoryFilter);
        }

        // 按搜索词筛选
        if ($this->search) {
            $searchTerm = Str::lower($this->search);
            $filtered = $filtered->filter(function ($point) use ($searchTerm) {
                return Str::contains(Str::lower($point['cn_name'] ?? ''), $searchTerm)
                    || Str::contains(Str::lower($point['kp_code'] ?? ''), $searchTerm)
                    || Str::contains(Str::lower($point['description'] ?? ''), $searchTerm);
            });
        }

        $this->filteredPoints = $filtered->values()->toArray();
    }

    public function selectKp($kpCode)
    {
        $this->selectedKpCode = $kpCode;
        $this->dispatch('kpSelected', kpCode: $kpCode);
    }

    public function clearSelection()
    {
        $this->selectedKpCode = null;
        $this->dispatch('clearGraphSelection');
    }

    public function getFilterOptionsProperty()
    {
        $phases = collect($this->knowledgePoints)
            ->pluck('phase')
            ->filter()
            ->unique()
            ->sort()
            ->values()
            ->toArray();

        $categories = collect($this->knowledgePoints)
            ->pluck('category')
            ->filter()
            ->unique()
            ->sort()
            ->values()
            ->toArray();

        return [
            'phases' => $phases,
            'categories' => $categories,
        ];
    }

    public function render()
    {
        return view('livewire.integrations.knowledge-points-list-component');
    }
}
