<?php

namespace App\Livewire\MistakeBook;

use App\Services\MistakeBookService;
use Filament\Widgets\ChartWidget;

class WeakKnowledgePointsChart extends ChartWidget
{
    public ?string $studentId;

    protected static ?int $sort = 3;

    public function mount(?string $studentId = null): void
    {
        $this->studentId = $studentId;
    }

    protected function getData(): array
    {
        if (!$this->studentId) {
            return [
                'datasets' => [],
                'labels' => [],
            ];
        }

        $service = app(MistakeBookService::class);
        $patterns = $service->getMistakePatterns($this->studentId);
        $knowledgePoints = array_slice($patterns['knowledge_points'] ?? [], 0, 10, true);

        $labels = array_keys($knowledgePoints);
        $data = array_values($knowledgePoints);

        return [
            'datasets' => [
                [
                    'label' => '错误次数',
                    'data' => $data,
                    'backgroundColor' => 'rgba(239, 68, 68, 0.5)',
                    'borderColor' => 'rgb(239, 68, 68)',
                    'borderWidth' => 2,
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getType(): string
    {
        return 'bar';
    }

    protected function getOptions(): array
    {
        return [
            'responsive' => true,
            'maintainAspectRatio' => false,
            'plugins' => [
                'legend' => [
                    'display' => false,
                ],
            ],
            'scales' => [
                'y' => [
                    'beginAtZero' => true,
                    'ticks' => [
                        'stepSize' => 1,
                    ],
                ],
            ],
        ];
    }
}
