"""The Editor Tool manages the ImGui context and tool overlays."""

import logging
from typing import Optional, Any

try:
    import imgui
    from imgui.integrations.pygame import PygameRenderer

    HAS_IMGUI = True
except ImportError:
    HAS_IMGUI = False
    imgui = None
    PygameRenderer = None

from pyguara.di.container import DIContainer
from pyguara.ecs.manager import EntityManager
from pyguara.scene.manager import SceneManager
from pyguara.scene.serializer import SceneSerializer
from pyguara.resources.manager import ResourceManager
from pyguara.editor.panels.hierarchy import HierarchyPanel
from pyguara.editor.panels.inspector import InspectorPanel
from pyguara.editor.panels.assets import AssetsPanel
from pyguara.tools.base import Tool
from pyguara.graphics.protocols import UIRenderer

logger = logging.getLogger(__name__)


class EditorTool(Tool):
    """A robust ImGui-based editor integrated into the Tool system."""

    def __init__(self, container: DIContainer) -> None:
        """Initialize the editor tool."""
        super().__init__("Editor", container)

        self._renderer: Optional[PygameRenderer] = None
        self._initialized = False

        # Panels
        self._show_hierarchy = True
        self._show_inspector = True
        self._show_assets = True

        resource_manager = self._container.get(ResourceManager)

        self._hierarchy_panel = HierarchyPanel(self._get_current_manager)
        self._inspector_panel = InspectorPanel(resource_manager)

        self._assets_panel = AssetsPanel(resource_manager, self._get_current_manager)

    def _get_current_manager(self) -> Optional[EntityManager]:
        """Resolve the active EntityManager from the current scene."""
        scene_manager = self._container.get(SceneManager)
        if scene_manager.current_scene:
            return scene_manager.current_scene.entity_manager
        return None

    def initialize(self) -> None:
        """Configure ImGui context."""
        if not HAS_IMGUI:
            logger.warning("ImGui not found. Editor disabled.")
            return

        imgui.create_context()
        self._renderer = PygameRenderer()

        # Apply style (Dark Theme)
        style = imgui.get_style()
        style.colors[imgui.COLOR_WINDOW_BACKGROUND] = (0.1, 0.1, 0.1, 0.95)
        style.colors[imgui.COLOR_TITLE_BACKGROUND_ACTIVE] = (0.2, 0.3, 0.4, 1.0)

        self._initialized = True
        logger.debug("ImGui editor initialized")

    def process_event(self, event: Any) -> bool:
        """Process inputs for the editor."""
        if not self.is_active or not self.is_visible:
            return False

        if not self._initialized:
            self.initialize()
            if not self._initialized:
                return False

        # Pass to ImGui
        if self._renderer:
            self._renderer.process_event(event)

        # Consume mouse/keyboard if ImGui wants them
        io = imgui.get_io()
        if io.want_capture_mouse or io.want_capture_keyboard:
            return True

        return False

    def update(self, dt: float) -> None:
        """Update editor logic."""
        # Synchronize selection
        self._inspector_panel.selected_entity = self._hierarchy_panel.selected_entity

    def render(self, renderer: UIRenderer) -> None:
        """Render the editor UI."""
        if not self.is_visible:
            return

        if not self._initialized:
            self.initialize()
            if not self._initialized:
                return

        imgui.new_frame()

        # Main Menu
        if imgui.begin_main_menu_bar():
            if imgui.begin_menu("File", True):
                if imgui.menu_item("Save Scene", "Ctrl+S")[0]:
                    self._save_current_scene()

                if imgui.menu_item("Load Scene", "Ctrl+L")[0]:
                    self._load_current_scene()

                imgui.end_menu()

            if imgui.begin_menu("View", True):
                clicked, self._show_hierarchy = imgui.menu_item(
                    "Hierarchy", None, self._show_hierarchy
                )
                clicked, self._show_inspector = imgui.menu_item(
                    "Inspector", None, self._show_inspector
                )
                clicked, self._show_assets = imgui.menu_item(
                    "Assets", None, self._show_assets
                )
                imgui.end_menu()

            imgui.end_main_menu_bar()

        # Draw Panels
        if self._show_hierarchy:
            self._hierarchy_panel.render()

        if self._show_inspector:
            self._inspector_panel.render()

        if self._show_assets:
            self._assets_panel.render()

        imgui.render()
        if self._renderer:
            self._renderer.render(imgui.get_draw_data())

    def _save_current_scene(self) -> None:
        """Save the current scene to disk."""
        scene_manager = self._container.get(SceneManager)
        if not scene_manager.current_scene:
            logger.warning("No scene to save")
            return

        scene = scene_manager.current_scene
        serializer = self._container.get(SceneSerializer)

        # Use scene name as filename
        filename = f"scene_{scene.name}"

        try:
            success = serializer.save_scene(scene, filename)
            if success:
                logger.info(
                    "Scene '%s' saved successfully to '%s'", scene.name, filename
                )
            else:
                logger.error("Failed to save scene '%s'", scene.name)
        except Exception as e:
            logger.error("Error saving scene '%s': %s", scene.name, e, exc_info=True)

    def _load_current_scene(self) -> None:
        """Load and refresh the current scene from disk."""
        scene_manager = self._container.get(SceneManager)
        if not scene_manager.current_scene:
            logger.warning("No scene to load into")
            return

        scene = scene_manager.current_scene
        serializer = self._container.get(SceneSerializer)

        # Use scene name as filename
        filename = f"scene_{scene.name}"

        try:
            # Clear existing entities before loading
            scene.entity_manager._entities.clear()
            scene.entity_manager._component_index.clear()

            success = serializer.load_scene(scene, filename)
            if success:
                logger.info(
                    "Scene '%s' loaded successfully from '%s'", scene.name, filename
                )
            else:
                logger.error("Failed to load scene '%s'", scene.name)
        except Exception as e:
            logger.error("Error loading scene '%s': %s", scene.name, e, exc_info=True)
