<?php

namespace App\Http\Livewire;

use Livewire\Component;

class UserPresence extends Component
{
    public $onlineUsers = [];
    public $guard = 'web';
    public $showCount = false;
    public $refreshInterval = 10; // Faster polling for better real-time feel
    public $lastUpdate = '';
    public $debugInfo = [];
    public $clickCount = 0;

    public function mount($guard = 'web', $showCount = false)
    {
        $this->guard = $guard;
        $this->showCount = $showCount;
        $this->lastUpdate = now()->format('H:i:s');
        $this->addDebugInfo('Component mounted with guard: ' . $guard);
        $this->loadOnlineUsers();
    }

    public function loadOnlineUsers()
    {
        try {
            // Simplified version for debugging
            if (class_exists(\App\Services\PresenceService::class)) {
                $presenceService = app(\App\Services\PresenceService::class);

                try {
                    $users = $presenceService->getOnlineUsers($this->guard);
                    $this->onlineUsers = $users->toArray();
                    $this->addDebugInfo('✅ Loaded ' . count($this->onlineUsers) . ' real users from PresenceService');
                } catch (\Exception $e) {
                    $this->addDebugInfo('❌ PresenceService error: ' . $e->getMessage());

                    // Fallback: Get users directly from activity log
                    $activities = \Spatie\Activitylog\Models\Activity::where('log_name', 'presence_update')
                        ->where('properties->guard', $this->guard)
                        ->where('created_at', '>=', now()->subMinutes(5))
                        ->with('subject')
                        ->latest()
                        ->get()
                        ->unique('subject_id');

                    $this->onlineUsers = $activities->map(function ($activity) {
                        $user = $activity->subject;
                        return $user ? [
                            'id' => $user->id,
                            'name' => $user->name,
                            'avatar' => $user->avatar ?? null,
                            'last_seen' => $activity->created_at,
                            'guard' => $this->guard,
                        ] : null;
                    })->filter()->values()->toArray();

                    $this->addDebugInfo('✅ Fallback: Loaded ' . count($this->onlineUsers) . ' users from direct query');
                }
            } else {
                // Test data if service doesn't exist
                $this->onlineUsers = [
                    ['name' => 'Test User 1', 'last_seen' => now()],
                    ['name' => 'Test User 2', 'last_seen' => now()->subMinutes(2)],
                ];
                $this->addDebugInfo('⚠️ PresenceService not found, using test data');
            }

            $this->lastUpdate = now()->format('H:i:s');
        } catch (\Exception $e) {
            $this->addDebugInfo('❌ Error loading users: ' . $e->getMessage());
            // Fallback to empty array
            $this->onlineUsers = [];
        }
    }

    public function handleUserActivity()
    {
        try {
            $this->addDebugInfo('handleUserActivity called at ' . now()->format('H:i:s'));

            if (auth($this->guard)->check()) {
                $user = auth($this->guard)->user();
                $this->addDebugInfo('User authenticated: ' . $user->name);

                // Try to use real PresenceService
                if (class_exists(\App\Services\PresenceService::class)) {
                    $presenceService = app(\App\Services\PresenceService::class);
                    $presenceService->updatePresence($user, $this->guard);
                    $this->addDebugInfo('Updated presence for user: ' . $user->name);
                } else {
                    $this->addDebugInfo('PresenceService not found - would update presence for: ' . $user->name);
                }

                $this->loadOnlineUsers();
            } else {
                $this->addDebugInfo('User not authenticated for guard: ' . $this->guard);
            }
        } catch (\Exception $e) {
            $this->addDebugInfo('Error in handleUserActivity: ' . $e->getMessage());
        }
    }

    public function refresh()
    {
        $this->addDebugInfo('Manual refresh triggered at ' . now()->format('H:i:s'));
        $this->loadOnlineUsers();
    }

    public function clearDebug()
    {
        $this->debugInfo = [];
        $this->addDebugInfo('Debug cleared at ' . now()->format('H:i:s'));
    }

    // Add event listener for JavaScript with corrected Livewire 3 syntax
    #[On('user-activity')]
    public function onUserActivity()
    {
        $this->addDebugInfo('🔥 user-activity event received from JavaScript at ' . now()->format('H:i:s'));
        $this->handleUserActivity();
    }

    #[On('user-went-offline')]
    public function onUserWentOffline()
    {
        $this->addDebugInfo('🔴 user-went-offline event received from JavaScript at ' . now()->format('H:i:s'));
        $this->handleUserOffline();
    }

    // Alternative: Try different event listener syntax
    public function getListeners()
    {
        return [
            'user-activity' => 'onUserActivity',
            'user-went-offline' => 'onUserWentOffline',
        ];
    }

    public function handleUserOffline()
    {
        try {
            $this->addDebugInfo('handleUserOffline called at ' . now()->format('H:i:s'));

            if (auth($this->guard)->check()) {
                $user = auth($this->guard)->user();

                if (class_exists(\App\Services\PresenceService::class)) {
                    $presenceService = app(\App\Services\PresenceService::class);
                    $presenceService->setUserOffline($user, $this->guard);
                    $this->addDebugInfo('Set user offline: ' . $user->name);
                } else {
                    $this->addDebugInfo('PresenceService not found - would set offline: ' . $user->name);
                }

                $this->loadOnlineUsers();
            }
        } catch (\Exception $e) {
            $this->addDebugInfo('Error in handleUserOffline: ' . $e->getMessage());
        }
    }

    private function addDebugInfo($message)
    {
        // Force array append to ensure it works
        $this->debugInfo[] = '[' . now()->format('H:i:s') . '] ' . $message;

        // Keep only last 15 debug messages
        if (count($this->debugInfo) > 15) {
            array_shift($this->debugInfo);
        }

        // Force Livewire to recognize the change
        $this->dispatch('debug-updated');
    }

    public function render()
    {
        return view('livewire.user-presence');
    }
}
