<?php

namespace App\Http\Livewire;

use App\Services\PresenceService;
use Livewire\Component;

class ProfileReactionStatusBadge extends Component
{
    public $profile; // The user/organization/bank model
    public $guard = 'web';
    public $showOnlineStatus = true;
    public $showReactions = true;
    public $compactMode = false;
    public $size = 'md'; // sm, md, lg

    // Reaction data
    public $reactions = [];
    public $isOnline = false;
    public $lastSeen = null;

    public function mount($profile, $guard = null, $showOnlineStatus = true, $showReactions = true, $compactMode = false, $size = 'md')
    {
        $this->profile = $profile;
        $this->guard = $guard ?: $this->detectGuard();
        $this->showOnlineStatus = $showOnlineStatus;
        $this->showReactions = $showReactions;
        $this->compactMode = $compactMode;
        $this->size = $size;

        $this->loadStatus();
    }

    protected function detectGuard()
    {
        // Detect guard based on model type
        $modelClass = get_class($this->profile);

        $guardMap = [
            'App\Models\User' => 'web',
            'App\Models\Organization' => 'organization',
            'App\Models\Bank' => 'bank',
            'App\Models\Admin' => 'admin',
        ];

        return $guardMap[$modelClass] ?? 'web';
    }

    public function loadStatus()
    {
        // Load online status
        if ($this->showOnlineStatus) {
            $presenceService = app(PresenceService::class);
            $this->isOnline = $presenceService->isUserOnline($this->profile, $this->guard);
            $this->lastSeen = $presenceService->getUserLastSeen($this->profile, $this->guard);
        }

        // Load reactions from authenticated user
        if ($this->showReactions) {
            $this->loadReactions();
        }
    }

    protected function loadReactions()
    {
        $this->reactions = [];

        // Get authenticated user from any guard
        $authUser = null;
        foreach (['web', 'organization', 'bank', 'admin'] as $guard) {
            if (auth($guard)->check()) {
                $authUser = auth($guard)->user();
                break;
            }
        }

        if (!$authUser) {
            return;
        }

        // Check if both models have reaction capabilities
        if (!method_exists($authUser, 'viaLoveReacter') || !method_exists($this->profile, 'viaLoveReactant')) {
            return;
        }

        try {
            $reactantFacade = $this->profile->viaLoveReactant();
            $reacterUser = $authUser;

            // Check common reaction types
            $reactionTypes = ['Like', 'Star', 'Bookmark'];

            foreach ($reactionTypes as $type) {
                if ($reactantFacade->isReactedBy($reacterUser, $type)) {
                    $this->reactions[] = [
                        'type' => $type,
                        'icon' => $this->getReactionIcon($type),
                        'color' => $this->getReactionColor($type),
                    ];
                }
            }
        } catch (\Exception $e) {
            \Log::error('Error loading reactions for badge: ' . $e->getMessage());
        }
    }

    protected function getReactionIcon($type)
    {
        $icons = [
            'Like' => '❤️',
            'Star' => '⭐',
            'Bookmark' => '🔖',
        ];

        return $icons[$type] ?? '👍';
    }

    protected function getReactionColor($type)
    {
        $colors = [
            'Like' => 'text-red-500',
            'Star' => 'text-yellow-500',
            'Bookmark' => 'text-blue-500',
        ];

        return $colors[$type] ?? 'text-gray-500';
    }

    public function toggleReaction($reactionType)
    {
        // Get authenticated user
        $authUser = null;
        foreach (['web', 'organization', 'bank', 'admin'] as $guard) {
            if (auth($guard)->check()) {
                $authUser = auth($guard)->user();
                break;
            }
        }

        if (!$authUser) {
            return;
        }

        try {
            $reacterFacade = $authUser->viaLoveReacter();
            $reactantFacade = $this->profile->viaLoveReactant();

            if ($reactantFacade->isReactedBy($authUser, $reactionType)) {
                $reacterFacade->unreactTo($this->profile, $reactionType);
            } else {
                $reacterFacade->reactTo($this->profile, $reactionType);
            }

            $this->loadReactions();

            // Dispatch event for other components
            $this->dispatch('reaction-toggled', [
                'profile_id' => $this->profile->id,
                'reaction_type' => $reactionType
            ]);
        } catch (\Exception $e) {
            \Log::error('Error toggling reaction: ' . $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.profile-reaction-status-badge');
    }
}
