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


class ProfileDisplay:
    def __init__(self):
        self.console = Console()
    
    def show_profile(self, user_data):
        self.console.clear()
        
        # Get terminal dimensions
        width = self.console.width
        height = self.console.height
        
        # Create responsive layout
        layout = Layout()
        
        # Adjust header size based on terminal height
        header_size = 3 if height > 20 else 2
        
        layout.split_column(
            Layout(name="header", size=header_size),
            Layout(name="body")
        )
        
        # Center the header text
        header_text = Text("🎵 Spotify Lite", style="bold magenta", justify="center")
        layout["header"].update(Panel(header_text, box=box.DOUBLE_EDGE))
        
        # Create responsive table
        table = Table(show_header=False, box=None, padding=(0, 2), expand=False)
        
        # Adjust column widths based on terminal width
        label_width = 15 if width > 80 else 12
        table.add_column(style="bold cyan", justify="right", width=label_width)
        table.add_column(style="white", overflow="ellipsis")
        
        table.add_row("Display Name", user_data.get('display_name', 'N/A'))
        table.add_row("Email", user_data.get('email', 'N/A'))
        table.add_row("Country", user_data.get('country', 'N/A'))
        table.add_row("Followers", str(user_data.get('followers', {}).get('total', 0)))
        table.add_row("Subscription", user_data.get('product', 'N/A').title())
        table.add_row("User ID", user_data.get('id', 'N/A'))
        
        # Center the table in the panel
        centered_table = Align.center(table, vertical="middle")
        
        # Use different box styles based on terminal width
        box_style = box.ROUNDED if width > 60 else box.SQUARE
        
        profile_panel = Panel(
            centered_table,
            title="[bold green]👤 User Profile[/bold green]",
            border_style="green",
            padding=(1, 2) if width > 60 else (0, 1),
            box=box_style,
            expand=True  # This makes the panel expand to fill available space
        )
        
        layout["body"].update(profile_panel)
        
        self.console.print(layout)
    
    def show_playlists(self, playlists_data):
        self.console.print("\n")
        
        # Get terminal width for responsiveness
        width = self.console.width
        
        # Create playlist table
        table = Table(show_header=True, box=box.ROUNDED if width > 80 else box.SQUARE)
        table.add_column("Name", style="bold cyan", overflow="ellipsis")
        table.add_column("Tracks", style="green", justify="center", width=8)
        table.add_column("Public", style="yellow", justify="center", width=8)
        table.add_column("Owner", style="magenta", overflow="ellipsis")
        
        playlists = playlists_data.get('items', [])
        
        for playlist in playlists:
            name = playlist.get('name', 'N/A')
            track_count = str(playlist.get('tracks', {}).get('total', 0))
            is_public = "Yes" if playlist.get('public', False) else "No"
            owner = playlist.get('owner', {}).get('display_name', 'N/A')
            
            table.add_row(name, track_count, is_public, owner)
        
        playlist_panel = Panel(
            table,
            title=f"[bold green]🎵 Your Playlists ({len(playlists)} total)[/bold green]",
            border_style="green",
            padding=(1, 1),
            expand=True
        )
        
        self.console.print(playlist_panel)
    
    def show_error(self, error_message, error_type="general"):
        self.console.print(f"\n[bold red]❌ Error:[/bold red] {error_message}\n")
        
        if error_type == "config":
            self.console.print("[yellow]Please ensure you have a .env file with:[/yellow]")
            self.console.print("  SPOTIFY_CLIENT_ID=your_client_id")
            self.console.print("  SPOTIFY_CLIENT_SECRET=your_client_secret")
            self.console.print("  SPOTIFY_REDIRECT_URI=http://localhost:8888/callback (optional)\n")
        elif error_type == "auth":
            self.console.print("[yellow]If this is your first time, you may need to authorize the app in your browser.[/yellow]\n")
    
    def show_loading(self, message="Connecting to Spotify..."):
        self.console.print(f"\n[bold green]🎵 {message}[/bold green]\n")