<?php

declare(strict_types=1);

namespace App\Filament\Widgets\SuperAdmin;

use App\Services\Platform\SaaSMetricsService;
use Filament\Widgets\ChartWidget;
use Illuminate\Support\Facades\Auth;

/**
 * Gráfico de evolución del MRR.
 *
 * Muestra la tendencia del Monthly Recurring Revenue
 * durante los últimos 12 meses.
 */
class MRRGrowthChart extends ChartWidget
{
    protected ?string $heading = 'Evolución MRR (12 meses)';

    protected ?string $pollingInterval = '300s';

    protected static ?int $sort = 3;

    protected int|string|array $columnSpan = 'half';

    /**
     * Solo visible para Super Admins.
     */
    public static function canView(): bool
    {
        return Auth::user()?->isSuperAdmin() ?? false;
    }

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

    protected function getData(): array
    {
        $service = app(SaaSMetricsService::class);
        $trend = $service->getMRRTrend(12);

        $labels = $trend->pluck('month_label')->toArray();
        $mrrData = $trend->pluck('mrr')->toArray();

        return [
            'datasets' => [
                [
                    'label' => 'MRR',
                    'data' => $mrrData,
                    'borderColor' => '#10b981',
                    'backgroundColor' => 'rgba(16, 185, 129, 0.1)',
                    'fill' => true,
                    'tension' => 0.3,
                    'pointRadius' => 4,
                    'pointHoverRadius' => 6,
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'legend' => [
                    'display' => false,
                ],
                'tooltip' => [
                    'callbacks' => [
                        'label' => "function(context) {
                            return '$' + context.raw.toLocaleString('es-CO');
                        }",
                    ],
                ],
            ],
            'scales' => [
                'y' => [
                    'beginAtZero' => true,
                    'ticks' => [
                        'callback' => "function(value) {
                            return '$' + value.toLocaleString('es-CO');
                        }",
                    ],
                ],
            ],
        ];
    }
}
