package game

import (
	"sync"

	"gitea.boner.be/bdnugget/goonscape/types"
	rl "github.com/gen2brain/raylib-go/raylib"
)

// PlayerManager handles all player-related operations
type PlayerManager struct {
	LocalPlayer  *types.Player
	OtherPlayers map[int32]*types.Player
	mutex        sync.RWMutex
}

// NewPlayerManager creates a new player manager
func NewPlayerManager() *PlayerManager {
	return &PlayerManager{
		OtherPlayers: make(map[int32]*types.Player),
	}
}

// GetPlayer returns the player with the given ID, or the local player if ID matches
func (pm *PlayerManager) GetPlayer(id int32) *types.Player {
	pm.mutex.RLock()
	defer pm.mutex.RUnlock()

	if pm.LocalPlayer != nil && pm.LocalPlayer.ID == id {
		return pm.LocalPlayer
	}

	return pm.OtherPlayers[id]
}

// AddPlayer adds a player to the manager
func (pm *PlayerManager) AddPlayer(player *types.Player) {
	pm.mutex.Lock()
	defer pm.mutex.Unlock()

	pm.OtherPlayers[player.ID] = player
}

// RemovePlayer removes a player from the manager
func (pm *PlayerManager) RemovePlayer(id int32) {
	pm.mutex.Lock()
	defer pm.mutex.Unlock()

	delete(pm.OtherPlayers, id)
}

// AssetManager handles all game assets
type AssetManager struct {
	Models []types.ModelAsset
	Music  rl.Music
}

// NewAssetManager creates a new asset manager
func NewAssetManager() *AssetManager {
	return &AssetManager{}
}

// GetModelForPlayer returns the appropriate model for a player
func (am *AssetManager) GetModelForPlayer(playerID int32) (types.ModelAsset, bool) {
	if len(am.Models) == 0 {
		return types.ModelAsset{}, false
	}

	// Simple model assignment based on player ID
	modelIndex := int(playerID) % len(am.Models)
	return am.Models[modelIndex], true
}

// UIManager manages all user interface components
type UIManager struct {
	Chat        *Chat
	LoginScreen *LoginScreen
	IsLoggedIn  bool
	MenuOpen    bool
}

// NewUIManager creates a new UI manager
func NewUIManager() *UIManager {
	return &UIManager{
		Chat:        NewChat(),
		LoginScreen: NewLoginScreen(),
	}
}

// HandleChatInput processes chat input and returns messages to send
func (ui *UIManager) HandleChatInput() (string, bool) {
	return ui.Chat.Update()
}

// DrawUI renders all UI components
func (ui *UIManager) DrawUI(screenWidth, screenHeight int32) {
	if !ui.IsLoggedIn {
		ui.LoginScreen.Draw()
	} else {
		if ui.MenuOpen {
			// Draw menu
		}

		// Draw chat always when logged in
		ui.Chat.Draw(screenWidth, screenHeight)
	}
}
