<?php

namespace App\Livewire\MistakeBook;

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

class ErrorTypeDistributionChart extends ChartWidget
{
    public ?string $studentId;

    protected static ?int $sort = 2;

    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);
        $errorTypes = $patterns['error_types'] ?? [];

        $labels = [];
        $data = [];
        $colors = [
            'rgb(239, 68, 68)',    // 红色 - 概念错误
            'rgb(249, 115, 22)',   // 橙色 - 计算错误
            'rgb(234, 179, 8)',    // 黄色 - 粗心错误
            'rgb(59, 130, 246)',   // 蓝色 - 逻辑错误
            'rgb(168, 85, 247)',   // 紫色 - 其他错误
        ];

        $typeLabels = [
            'concept' => '概念错误',
            'calculation' => '计算错误',
            'careless' => '粗心错误',
            'logic' => '逻辑错误',
            'other' => '其他错误',
        ];

        foreach ($errorTypes as $type => $count) {
            $labels[] = $typeLabels[$type] ?? $type;
            $data[] = $count;
        }

        return [
            'datasets' => [
                [
                    'label' => '错误数量',
                    'data' => $data,
                    'backgroundColor' => array_slice($colors, 0, count($data)),
                    'borderColor' => array_slice($colors, 0, count($data)),
                    'borderWidth' => 1,
                ],
            ],
            'labels' => $labels,
        ];
    }

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

    protected function getOptions(): array
    {
        return [
            'responsive' => true,
            'maintainAspectRatio' => false,
            'plugins' => [
                'legend' => [
                    'display' => true,
                    'position' => 'right',
                ],
            ],
        ];
    }
}
