<?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 distribución de suscripciones por estado.
 *
 * Muestra un donut chart con el desglose de suscripciones
 * por estado (activas, trial, gracia, expiradas, canceladas).
 */
class SubscriptionsByStatusChart extends ChartWidget
{
    protected ?string $heading = 'Suscripciones por Estado';

    protected ?string $pollingInterval = '120s';

    protected static ?int $sort = 2;

    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 'doughnut';
    }

    protected function getData(): array
    {
        $service = app(SaaSMetricsService::class);
        $stats = $service->getSubscriptionStats();
        $byStatus = $stats['by_status'];

        $labels = [];
        $data = [];
        $colors = [];

        foreach ($byStatus as $status => $info) {
            if ($info['count'] > 0) {
                $labels[] = $info['label'];
                $data[] = $info['count'];
                $colors[] = $info['color'];
            }
        }

        return [
            'datasets' => [
                [
                    'data' => $data,
                    'backgroundColor' => $colors,
                    'borderWidth' => 0,
                ],
            ],
            'labels' => $labels,
        ];
    }

    protected function getOptions(): array
    {
        return [
            'plugins' => [
                'legend' => [
                    'position' => 'right',
                    'labels' => [
                        'usePointStyle' => true,
                        'padding' => 15,
                    ],
                ],
                'tooltip' => [
                    'callbacks' => [
                        'label' => "function(context) {
                            const total = context.dataset.data.reduce((a, b) => a + b, 0);
                            const value = context.raw;
                            const percentage = Math.round((value / total) * 100);
                            return context.label + ': ' + value + ' (' + percentage + '%)';
                        }",
                    ],
                ],
            ],
            'cutout' => '60%',
        ];
    }
}
