<?php

declare(strict_types=1);

namespace App\Filament\Widgets\SuperAdmin;

use App\Services\Platform\SaaSMetricsService;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;
use Illuminate\Support\Facades\Auth;

/**
 * Widget de estadísticas principales de plataforma para Super Admin.
 *
 * Muestra: MRR, ARR, Companies Activas, Churn Rate
 */
class PlatformStatsWidget extends BaseWidget
{
    protected ?string $pollingInterval = '60s';

    protected static ?int $sort = 1;

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

    protected function getStats(): array
    {
        $service = app(SaaSMetricsService::class);
        $summary = $service->getPlatformSummary();

        $companies = $summary['companies'];
        $revenue = $summary['revenue'];
        $growth = $summary['growth'];
        $subscriptions = $summary['subscriptions'];

        return [
            Stat::make('MRR', $this->formatCurrency($revenue['mrr']))
                ->description($this->formatGrowth($revenue['mrr_growth_percentage']))
                ->descriptionIcon($revenue['mrr_growth_percentage'] >= 0 ? 'heroicon-m-arrow-trending-up' : 'heroicon-m-arrow-trending-down')
                ->color($revenue['mrr_growth_percentage'] >= 0 ? 'success' : 'danger')
                ->chart($this->getMRRChartData()),

            Stat::make('ARR', $this->formatCurrency($revenue['arr']))
                ->description('Ingreso anual recurrente')
                ->color('primary'),

            Stat::make('Companies Activas', $companies['active'])
                ->description("+{$companies['new_this_month']} este mes")
                ->descriptionIcon('heroicon-m-building-office-2')
                ->color('success'),

            Stat::make('Suscripciones', $subscriptions['active_total'])
                ->description("{$subscriptions['by_status']['trial']['count']} en trial")
                ->descriptionIcon('heroicon-m-credit-card')
                ->color('info'),

            Stat::make('Churn Rate', $growth['churn_rate'].'%')
                ->description('Cancelaciones mensuales')
                ->descriptionIcon($growth['churn_rate'] <= 5 ? 'heroicon-m-check-circle' : 'heroicon-m-exclamation-triangle')
                ->color($growth['churn_rate'] <= 5 ? 'success' : 'warning'),

            Stat::make('Conversión Trial', $growth['trial_conversion_rate'].'%')
                ->description('Trial → Pago (30 días)')
                ->descriptionIcon('heroicon-m-arrow-path')
                ->color($growth['trial_conversion_rate'] >= 50 ? 'success' : 'warning'),
        ];
    }

    /**
     * Datos para el mini chart de MRR.
     */
    private function getMRRChartData(): array
    {
        $service = app(SaaSMetricsService::class);
        $trend = $service->getMRRTrend(6);

        return $trend->pluck('mrr')->toArray();
    }

    private function formatCurrency(float $amount): string
    {
        return '$'.number_format($amount, 0, ',', '.');
    }

    /**
     * Formatea porcentaje de crecimiento.
     */
    private function formatGrowth(float $percentage): string
    {
        $sign = $percentage >= 0 ? '+' : '';

        return "{$sign}{$percentage}% vs mes anterior";
    }
}
