<?php

namespace App\Filament\Widgets;

use App\Models\ImpersonationLog;
use Filament\Widgets\StatsOverviewWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class ImpersonationStatsOverview extends StatsOverviewWidget
{
    protected function getStats(): array
    {
        $totalSessions = ImpersonationLog::count();
        $activeSessions = ImpersonationLog::active()->count();
        $completedSessions = ImpersonationLog::completed()->count();

        // Calculate average duration properly using the time difference
        $completedSessionsWithDuration = ImpersonationLog::completed()
            ->whereNotNull('end_time')
            ->get();

        $averageDuration = 0;
        if ($completedSessionsWithDuration->count() > 0) {
            $totalDuration = $completedSessionsWithDuration->sum(function ($session) {
                return $session->duration_in_minutes ?? 0;
            });
            $averageDuration = $totalDuration / $completedSessionsWithDuration->count();
        }

        return [
            Stat::make('Total Sessions', number_format($totalSessions))
                ->description('All impersonation sessions')
                ->descriptionIcon('heroicon-o-document-text')
                ->color('primary'),

            Stat::make('Active Sessions', number_format($activeSessions))
                ->description('Currently active')
                ->descriptionIcon('heroicon-o-eye')
                ->color($activeSessions > 0 ? 'success' : 'gray'),

            Stat::make('Completed Sessions', number_format($completedSessions))
                ->description('Successfully completed')
                ->descriptionIcon('heroicon-o-check-circle')
                ->color('primary'),

            Stat::make('Avg Duration', round($averageDuration, 1).' min')
                ->description('Average session time')
                ->descriptionIcon('heroicon-o-clock')
                ->color('warning'),
        ];
    }
}
