from enum import Enum
from typing import Optional, Dict, Any


class ViewState(Enum):
    MAIN_MENU = "main"
    PLAYLIST_VIEW = "playlist"
    TRACK_DETAILS = "track"


class NavigationState:
    def __init__(self):
        self.current_view = ViewState.MAIN_MENU
        self.selected_playlist_index = 0
        self.selected_track_index = 0
        self.current_playlist: Optional[Dict[str, Any]] = None
        self.current_tracks = []
        self.navigation_history = []
    
    def navigate_to_playlist(self, playlist: Dict[str, Any]):
        """Navigate to playlist view"""
        self.navigation_history.append({
            'view': self.current_view,
            'playlist_index': self.selected_playlist_index
        })
        self.current_view = ViewState.PLAYLIST_VIEW
        self.current_playlist = playlist
        self.selected_track_index = 0
    
    def go_back(self):
        """Navigate back to previous view"""
        if self.navigation_history:
            previous_state = self.navigation_history.pop()
            self.current_view = previous_state['view']
            self.selected_playlist_index = previous_state.get('playlist_index', 0)
            
            if self.current_view == ViewState.MAIN_MENU:
                self.current_playlist = None
                self.current_tracks = []
        else:
            self.current_view = ViewState.MAIN_MENU
            self.current_playlist = None
            self.current_tracks = []
    
    def reset(self):
        """Reset to main menu"""
        self.current_view = ViewState.MAIN_MENU
        self.selected_playlist_index = 0
        self.selected_track_index = 0
        self.current_playlist = None
        self.current_tracks = []
        self.navigation_history = []


class KeyHandler:
    """Handles keyboard input mapping"""
    
    ARROW_UP = '\x1b[A'
    ARROW_DOWN = '\x1b[B'
    ARROW_LEFT = '\x1b[D'
    ARROW_RIGHT = '\x1b[C'
    ENTER = '\r'
    ENTER_ALT = '\n'
    BACKSPACE = '\x7f'
    DELETE = '\x08'
    ESCAPE = '\x1b'
    CTRL_C = '\x03'
    
    @staticmethod
    def is_navigation_key(key: str) -> bool:
        """Check if key is a navigation key"""
        return key in [
            KeyHandler.ARROW_UP,
            KeyHandler.ARROW_DOWN,
            KeyHandler.ARROW_LEFT,
            KeyHandler.ARROW_RIGHT
        ]
    
    @staticmethod
    def is_selection_key(key: str) -> bool:
        """Check if key is a selection key"""
        return key in [KeyHandler.ENTER, KeyHandler.ENTER_ALT]
    
    @staticmethod
    def is_back_key(key: str) -> bool:
        """Check if key is a back navigation key"""
        return key in [KeyHandler.BACKSPACE, KeyHandler.DELETE]
    
    @staticmethod
    def is_quit_key(key: str) -> bool:
        """Check if key is a quit key"""
        return key in [KeyHandler.ESCAPE, KeyHandler.CTRL_C]