# FlightMonitor/gui/panels/views_notebook_panel.py
"""
Panel managing the views notebooks (Map View, Table View)
and providing access to the map canvas.
"""
import tkinter as tk
from tkinter import ttk
from typing import Any, Optional

from flightmonitor.utils.logger import get_logger
from flightmonitor.data import config as app_config # For canvas dimensions

module_logger = get_logger(__name__)

# Fallback dimensions if app_config is not fully reliable for canvas
FALLBACK_CANVAS_WIDTH = getattr(app_config, "DEFAULT_CANVAS_WIDTH", 800)
FALLBACK_CANVAS_HEIGHT = getattr(app_config, "DEFAULT_CANVAS_HEIGHT", 600)


class ViewsNotebookPanel:
    """
    Manages the application's view area, including the Map View and Table View notebooks.
    Provides access to the Tkinter Canvas used for map rendering.
    """

    def __init__(self, parent_frame: ttk.Frame):
        """
        Initializes the ViewsNotebookPanel.

        Args:
            parent_frame: The parent ttk.Frame where this notebook will be placed.
        """
        self.parent_frame = parent_frame
        self.flight_canvas: Optional[tk.Canvas] = None # Will be set by _build_ui

        # Store initial canvas dimensions from config (or fallbacks)
        self.canvas_width = getattr(app_config, "DEFAULT_CANVAS_WIDTH", FALLBACK_CANVAS_WIDTH)
        self.canvas_height = getattr(app_config, "DEFAULT_CANVAS_HEIGHT", FALLBACK_CANVAS_HEIGHT)

        self._build_ui() # Call a helper method to build the UI elements
        module_logger.debug("ViewsNotebookPanel initialized.")

    def _build_ui(self):
        """
        Builds the main notebook structure for views and all its tabs and widgets.
        """
        self.views_notebook = ttk.Notebook(self.parent_frame)
        self.views_notebook.pack(fill=tk.BOTH, expand=True, padx=0, pady=(2, 0))

        # --- Map View Tab ---
        # Crea il frame per la vista mappa e il canvas Tkinter che ospiterà la mappa.
        self.map_view_frame = ttk.Frame(self.views_notebook, padding=0)
        self.views_notebook.add(self.map_view_frame, text="Map View")

        self.flight_canvas = tk.Canvas(
            self.map_view_frame,
            bg="gray60", # Colore di sfondo di default per il canvas della mappa
            width=self.canvas_width, # Larghezza iniziale
            height=self.canvas_height, # Altezza iniziale
            highlightthickness=0, # Rimuove il bordo di evidenziazione di Tkinter
        )
        self.flight_canvas.pack(fill=tk.BOTH, expand=True) # Il canvas si espande per riempire il frame

        # --- Table View Tab (Placeholder) ---
        # Crea il frame per la vista tabella (attualmente un placeholder).
        self.table_view_frame = ttk.Frame(self.views_notebook, padding=5)
        self.views_notebook.add(self.table_view_frame, text="Table View")
        ttk.Label(
            self.table_view_frame,
            text="Table View - Coming Soon",
            font=("Arial", 12),
        ).pack(expand=True)

        # Binds the tab change event to an internal method
        self.views_notebook.bind("<<NotebookTabChanged>>", self._on_view_tab_change)

    def _on_view_tab_change(self, event: Optional[tk.Event] = None):
        """
        Handles changes in the selected view tab (e.g., Map View, Table View).
        """
        try:
            # Get the text of the newly selected tab
            tab_text = self.views_notebook.tab(self.views_notebook.index("current"), "text")
            module_logger.info(f"ViewsNotebookPanel: Switched view tab to: {tab_text}")
            # Future: Add specific logic based on tab content here if needed
            # For example, re-initialize map if switching back to it, or clear table.
        except tk.TclError as e:
            # Handle potential TclError if the notebook or tab is destroyed during the event
            module_logger.warning(f"ViewsNotebookPanel: TclError on view tab change: {e}, notebook might be closing.", exc_info=False)
        except Exception as e:
            module_logger.error(f"ViewsNotebookPanel: Error processing view tab change: {e}", exc_info=True)

    def get_map_canvas(self) -> Optional[tk.Canvas]:
        """
        Returns the Tkinter Canvas widget dedicated to map rendering.
        This method is essential for MainWindow to pass the canvas to MapCanvasManager.

        Returns:
            The `tkinter.Canvas` widget, or None if not yet created.
        """
        return self.flight_canvas