import sys
from rich.console import Console
from rich.panel import Panel
from rich.table import Table
from rich.text import Text
from rich import box
from rich.align import Align


class HomeScreen:
    def __init__(self):
        self.console = Console()
        self.selected_option = 0
        self.fixed_panel_height = 15  # Fixed height for the main content panel
        self.options = ["View My Profile", "Browse Playlists", "Currently Playing"]

    def create_layout(self):
        """Create the home screen layout"""
        width = self.console.width

        # Header
        header_text = Text("🎵 Spotify Lite - Home", style="bold magenta", justify="center")
        header_panel = Panel(header_text, box=box.DOUBLE_EDGE)

        # Menu options with fixed height
        menu_table = Table(show_header=False, box=None, padding=(1, 4))
        menu_table.add_column("", justify="center")

        # Add the actual menu options
        for i, option in enumerate(self.options):
            if i == self.selected_option:
                menu_table.add_row(f"► {option}", style="bold cyan")
            else:
                menu_table.add_row(f"  {option}", style="white")

        # Add empty rows to reach fixed height
        current_rows = len(self.options)  # +2 for padding
        empty_rows_needed = max(0, self.fixed_panel_height - current_rows)
        for _ in range(empty_rows_needed):
            menu_table.add_row(" ")

        menu_panel = Panel(
            menu_table,
            title="[bold green]Choose an option[/bold green]",
            border_style="green",
            box=box.ROUNDED if width > 60 else box.SQUARE,
            height=self.fixed_panel_height,
        )

        # Footer
        footer_text = Text(
            "↑↓: Navigate | Enter: Select | q/Esc: Quit", style="dim", justify="center"
        )
        footer_panel = Panel(footer_text, box=box.SQUARE)

        return header_panel, menu_panel, footer_panel

    def display_screen(self):
        """Display the home screen"""
        self.console.clear()
        header, menu, footer = self.create_layout()

        self.console.print(header)
        self.console.print()
        self.console.print(menu)
        self.console.print()
        self.console.print(footer)

    def show_selection_screen(self, choice_num, option_name):
        """Show a new screen for the selected option with fixed height"""
        while True:
            self.console.clear()

            # Header
            header_text = Text(
                f"🎵 Spotify Lite - {option_name}", style="bold magenta", justify="center"
            )
            header_panel = Panel(header_text, box=box.DOUBLE_EDGE)

            # Content with fixed height
            content_text = Text(
                f"✓ Clicked Choice {choice_num}: {option_name}",
                style="bold green",
                justify="center",
            )
            content_panel = Panel(
                Align.center(content_text, vertical="middle"),
                title="[bold cyan]Selected Option[/bold cyan]",
                border_style="cyan",
                box=box.ROUNDED,
                height=self.fixed_panel_height,
            )

            # Footer
            footer_text = Text(
                "Press Backspace/Delete to go back to main menu | q/Esc: Quit",
                style="dim",
                justify="center",
            )
            footer_panel = Panel(footer_text, box=box.SQUARE)

            # Print content
            self.console.print(header_panel)
            self.console.print()
            self.console.print(content_panel)
            self.console.print()
            self.console.print(footer_panel)

            # Wait for input
            key = self.get_key()

            if key in ["\x7f", "\x08"]:  # Backspace or Delete
                return  # Go back to main menu
            elif key in ["q", "Q", "\x1b", "\x03"]:  # q, Escape, or Ctrl+C
                return "quit"

    def handle_selection(self):
        """Handle when user selects an option"""
        selected = self.options[self.selected_option]
        choice_num = self.selected_option + 1

        result = self.show_selection_screen(choice_num, selected)
        return result

    def get_key(self):
        """Get a single key press"""
        try:
            import termios
            import tty

            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(fd)
                ch = sys.stdin.read(1)

                # Handle arrow keys
                if ch == "\x1b":
                    try:
                        ch += sys.stdin.read(2)
                    except:
                        pass

                return ch
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        except ImportError:
            # Fallback for Windows
            try:
                import msvcrt

                return msvcrt.getch().decode("utf-8")
            except ImportError:
                return input()[:1]

    def run(self):
        """Main loop for home screen"""
        try:
            while True:
                self.display_screen()
                key = self.get_key()

                # Handle navigation
                if key == "\x1b[A":  # Up arrow
                    self.selected_option = (self.selected_option - 1) % len(self.options)
                elif key == "\x1b[B":  # Down arrow
                    self.selected_option = (self.selected_option + 1) % len(self.options)
                elif key in ["\r", "\n"]:  # Enter
                    result = self.handle_selection()
                    if result == "quit":
                        break
                elif key in ["q", "Q", "\x1b", "\x03"]:  # q, Escape, or Ctrl+C
                    break

        except KeyboardInterrupt:
            pass

        self.console.print("\n[yellow]👋 Goodbye![/yellow]")


if __name__ == "__main__":
    home = HomeScreen()
    home.run()
