from typing import Optional
import carb
import omni.ui as ui
from omni.ui import constant as fl
from omni.kit.welcome.window import show_window as show_welcome_window

from .recent_widget import RecentWidget
from .template_grid import TemplateGrid
from .thumbnail_grid import ThumbnailItem

SETTING_SHOW_TEMPLATES = "/exts/omni.kit.welcome.open/show_templates"


class StageTab:
    """
    Tab to show stage content.
    """
    def __init__(self):
        self._checkpoint_combobox = None
        self._build_ui()

    def destroy(self):
        self._recent_widget.destroy()

    def _build_ui(self):
        with ui.VStack():
            # Templates
            if carb.settings.get_settings().get_as_bool(SETTING_SHOW_TEMPLATES):
                with ui.HStack(height=0):
                    ui.Spacer(width=fl._find("welcome_content_padding_x"))
                    with ui.VStack():
                        ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator")
                        ui.Label("NEW", height=0, style_type_name_override="ThumbnailGrid.Title")
                        ui.Spacer(height=10)

                    ui.Spacer(width=fl._find("welcome_content_padding_x"))
                with ui.HStack(height=fl._find("welcome_open_thumbnail_size") + fl._find("welcome_open_lable_size") + 60):
                    ui.Spacer(width=8)
                    self._template_grid = TemplateGrid(on_selection_changed=self.__on_template_selected)
                    ui.Spacer(width=8)

            # Recent files
            with ui.HStack(height=0):
                ui.Spacer(width=fl._find("welcome_content_padding_x"))
                with ui.VStack():
                    ui.Line(height=2, style_type_name_override="ThumbnailGrid.Separator")
                    with ui.HStack(height=20):
                        ui.Label("RECENT", width=0, style_type_name_override="ThumbnailGrid.Title")
                        ui.Spacer()
                        self._mode_image = ui.Image(name="grid", width=20, style_type_name_override="ThumbnailGrid.Mode", mouse_pressed_fn=lambda x, y, b,a: self.__toggle_thumbnail_model())
                    ui.Spacer(height=10)
                ui.Spacer(width=fl._find("welcome_content_padding_x"))
            self._recent_widget = RecentWidget(self.__on_recent_selected, self.__on_grid_mode)

            # Open widgets
            with ui.ZStack(height=26):
                ui.Rectangle(style_type_name_override="Stage.Separator")
                with ui.VStack():
                    ui.Spacer(height=2)
                    with ui.HStack(spacing=2):
                        self._checkpoint_blank = ui.Rectangle(style_type_name_override="Stage.Blank")
                        self._checkpoint_frame = ui.Frame(build_fn=self.__build_checkpoints, visible=False)

                        # Button size/style to be same as omni.kit.window.filepicker.FilePickerWidget
                        ui.Button("Open File", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:self.__open_file())
                        ui.Button("Close", width=117, style_type_name_override="Stage.Button", mouse_pressed_fn=lambda x, y, a, f:show_welcome_window(visible=False))

    def __toggle_thumbnail_model(self):
        if self._mode_image.name == "grid":
            self._mode_image.name = "table"
            self._recent_widget.show_grid(False)
        else:
            self._mode_image.name = "grid"
            self._recent_widget.show_grid(True)

    def __build_checkpoints(self):
        try:
            import omni.kit.app
            manager = omni.kit.app.get_app().get_extension_manager()
            manager.set_extension_enabled_immediate("omni.kit.widget.versioning", True)
            from omni.kit.widget.versioning import CheckpointCombobox
            with ui.HStack(spacing=2):
                with ui.ZStack(content_clipping=True, width=0):
                    ui.Rectangle(style_type_name_override="Stage.Blank")
                    ui.Label("Checkpoints", width=0, style_type_name_override="Stage.Label")
                self._checkpoint_combobox = CheckpointCombobox(
                    self._recent_widget.selected_url if self._recent_widget.selected_url else "",
                    None,
                    width=ui.Fraction(1),
                    has_pre_spacer=False,
                    popup_width=0,
                    modal=True
                )
        except Exception as e:
            carb.log_warn(f"Failed to create checkpoint combobox: {e}")
            self._checkpoint_combobox = None

    def __on_template_selected(self, item: Optional[ThumbnailItem]):
        if item:
            # Clear selection in recents
            self._recent_widget.selected_url = None
            # Hide checkpoint combobox
            self._checkpoint_frame.visible = False
            self._checkpoint_blank.visible = True

    def __on_recent_selected(self, item: Optional[ui.AbstractItem]):
        if item:
            # Clear selection in templates
            self._template_grid.selected = None

            if isinstance(item, ThumbnailItem):
                # Show checkpoint combobox if selected in recent grid
                self._checkpoint_frame.visible = bool(item)
                self._checkpoint_blank.visible = not bool(item)

                if item and self._checkpoint_combobox:
                    self._checkpoint_combobox.url = item.url

    def __on_grid_mode(self, grid_mode: bool) -> None:
        # Show checkpoint combobox in grid mode and recent file selected
        if grid_mode:
            show_checkpoint = bool(self._recent_widget.selected_url)
            self._checkpoint_frame.visible = show_checkpoint
            self._checkpoint_blank.visible = not show_checkpoint
        else:
            self._checkpoint_frame.visible = False
            self._checkpoint_blank.visible = True

    def __open_file(self) -> None:
        selected = self._template_grid.selected
        if selected:
            carb.log_info(f"Open template: {selected.url}")
            selected.execute()
        else:
            self._recent_widget.open_selected(self._checkpoint_combobox.url if self._checkpoint_combobox else None)
