#!/usr/bin/env python3
"""Tab navigation component for the UI."""
import curses
from typing import List, Optional

from ..display import Display


class TabsComponent:
    """Renders navigation tabs."""

    def __init__(self, display: Display):
        """Initialize the tabs component.

        Args:
            display: Display instance
        """
        self.display = display
        self.tabs = ["OVERVIEW", "AI PROCESSES", "GPU", "MEMORY", "CPU"]

    def render(
        self, selected_tab: int, y: int, custom_tabs: Optional[List[str]] = None
    ) -> int:
        """Render the navigation tabs.

        Args:
            selected_tab: Index of selected tab
            y: Starting Y coordinate (ignored, uses layout system)
            custom_tabs: Optional custom tab labels

        Returns:
            Next Y coordinate
        """
        # Get tabs layout from layout system
        layout = self.display.layout.calculate()
        tabs_rect = layout["tabs"]
        chip_active_attr = self.display.get_theme_attr("chip_active")
        chip_attr = self.display.get_theme_attr("chip")

        tabs = custom_tabs if custom_tabs is not None else self.tabs
        tab_width = tabs_rect.width // len(tabs)
        tab_width = max(1, tab_width)

        for i, tab in enumerate(tabs):
            x = i * tab_width
            attr = chip_active_attr if i == selected_tab else chip_attr
            max_label_width = max(1, tab_width - 4)
            label = (
                tab[: max(0, max_label_width - 3)] + "..."
                if len(tab) > max_label_width
                else tab
            )
            decorated = f"[{label}]" if i == selected_tab else f" {label} "
            tab_text = self.display.center_text(decorated, tab_width)

            self.display.safe_addstr(tabs_rect.y, x, tab_text, attr)

        return tabs_rect.bottom

    def get_tab_count(self, custom_tabs: Optional[List[str]] = None) -> int:
        """Get the number of tabs.

        Args:
            custom_tabs: Optional custom tab labels

        Returns:
            Number of tabs
        """
        return len(custom_tabs if custom_tabs is not None else self.tabs)

    def handle_tab_input(
        self,
        key: int,
        current_tab: int,
        custom_tabs: Optional[List[str]] = None,
    ) -> int:
        """Handle tab navigation input.

        Args:
            key: Input key code
            current_tab: Current tab index
            custom_tabs: Optional custom tab labels

        Returns:
            New tab index
        """
        tab_count = self.get_tab_count(custom_tabs=custom_tabs)
        if tab_count <= 0:
            return 0
        if key == curses.KEY_RIGHT:
            return (current_tab + 1) % tab_count
        elif key == curses.KEY_LEFT:
            return (current_tab - 1) % tab_count
        return current_tab
