<?php

namespace App\Filament\Pages;

use App\Services\Analytics\AnalyticsService;
use Filament\Pages\Page;
use Filament\Actions\Action;
use Illuminate\Contracts\Support\Htmlable;

class AnalyticsDashboard extends Page
{
    protected static ?string $navigationIcon = 'heroicon-o-chart-pie';

    protected static ?string $navigationGroup = 'Analytics';

    protected static ?int $navigationSort = 1;

    protected static string $view = 'filament.pages.analytics-dashboard';

    protected static ?string $navigationLabel = 'Dashboard';

    protected static ?string $title = 'Analytics Dashboard';

    public array $dashboardStats = [];
    public array $userStats = [];
    public array $contentStats = [];
    public array $eventStats = [];

    public function mount(): void
    {
        $this->loadAnalyticsData();
    }

    protected function getHeaderActions(): array
    {
        return [
            Action::make('refresh')
                ->label('Refresh Data')
                ->icon('heroicon-m-arrow-path')
                ->action('refreshData'),
            
            Action::make('clear_cache')
                ->label('Clear Cache')
                ->icon('heroicon-m-trash')
                ->action('clearCache')
                ->requiresConfirmation(),
        ];
    }

    public function refreshData(): void
    {
        $this->loadAnalyticsData();
        $this->dispatch('notify', message: 'Analytics data refreshed successfully');
    }

    public function clearCache(): void
    {
        $analyticsService = app(AnalyticsService::class);
        $analyticsService->clearCache();
        $this->loadAnalyticsData();
        $this->dispatch('notify', message: 'Analytics cache cleared successfully');
    }

    private function loadAnalyticsData(): void
    {
        try {
            $analyticsService = app(AnalyticsService::class);
            
            $this->dashboardStats = $analyticsService->getDashboardStats();
            $this->userStats = $analyticsService->getUserStats();
            $this->contentStats = $analyticsService->getContentStats();
            $this->eventStats = $analyticsService->getEventStats();
        } catch (\Throwable $e) {
            $this->dashboardStats = [];
            $this->userStats = [];
            $this->contentStats = [];
            $this->eventStats = [];
            
            $this->dispatch('notify', message: 'Error loading analytics data: ' . $e->getMessage(), type: 'error');
        }
    }

    public function getTitle(): string | Htmlable
    {
        return 'Analytics Dashboard';
    }

    public static function canAccess(): bool
    {
        // Only allow admin users to access analytics
        return auth()->user()?->role === 'admin';
    }
}