from PyQt5.QtCore import QThread, pyqtSignal, Qt
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, 
                             QStackedWidget, QLabel, QFrame,
                             QApplication) 
from gui.widgets.side_bar import SideBar
from gui.widgets.top_bar import TopBar
from gui.widgets.timeline_widget import TimelineWidget
from gui.views.page_home import MenuInicialPage
from gui.views.page_agents import AgentesPage
from gui.views.page_messages import MensagensPage
from gui.views.page_environment import AmbientePage
from gui.views.page_learning import PageLearning
from gui.core.log_store import LogStore
from gui.core.data_model import AgentDataModel

from gui.widgets.settings_dialog import SettingsDialog
from gui.widgets.manual_dialog import ManualDialog
from gui.assets.theme.styler import load_stylesheet, set_active_theme, current_theme

class InterfaceWindow(QWidget):
    
    timeline_index_changed = pyqtSignal(int)

    def __init__(self, command_queue, num_agents, new_queue):
        super().__init__()
        self.setWindowTitle("MASPY GUI")
        self.setGeometry(100, 100, 1200, 700)
        
        self._current_theme = "dark" 

        self.command_queue = command_queue

        self.log_thread = QThread()
        self.log_store = LogStore(new_queue)
        self.log_store.moveToThread(self.log_thread)
        self.log_thread.started.connect(self.log_store.start_polling)
        self.log_thread.finished.connect(self.log_thread.deleteLater)

        self.data_model = AgentDataModel(self.log_store)

        self._setup_ui()

        self.timeline_index_changed.connect(self.log_store.set_current_timeline_index)
        
        self.timeline_index_changed.connect(self.page_agentes.on_store_updated)
        self.timeline_index_changed.connect(self.page_mensagens.on_store_updated)
        self.timeline_index_changed.connect(self.page_ambiente.on_timeline_state_changed)
        self.timeline_index_changed.connect(self.page_menu.on_store_updated)
        self.timeline_index_changed.connect(self.data_model.on_store_updated)

        self.log_thread.start()
        
        self.settings_dialog = None
        self.manual_dialog = None

    def _setup_ui(self):
        main_layout = QHBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        self.sidebar = SideBar()
        main_layout.addWidget(self.sidebar)

        right_layout = QVBoxLayout()
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(0)

        self.topbar = TopBar("Menu")
        self.topbar.settings_button_clicked.connect(self._open_settings)
        self.topbar.manual_button_clicked.connect(self._open_manual)
        right_layout.addWidget(self.topbar)
        
        self.timeline = TimelineWidget()
        right_layout.addWidget(self.timeline)

        self.stack = QStackedWidget()
        
        self.page_menu = MenuInicialPage(self.command_queue, self.log_store)
        self.page_agentes = AgentesPage(self.log_store, self.data_model)
        self.page_mensagens = MensagensPage(self.log_store)
        
        self.page_ambiente = AmbientePage(self.log_store)
        self.page_ambiente.setObjectName("page_ambiente") 
        
        self.page_learning = PageLearning(self.log_store)

        self.stack.addWidget(self.page_menu)
        self.stack.addWidget(self.page_agentes)
        self.stack.addWidget(self.page_ambiente)
        self.stack.addWidget(self.page_mensagens)
        self.stack.addWidget(self.page_learning)
        
        right_layout.addWidget(self.stack)
        main_layout.addLayout(right_layout)

        self.log_store.agent_list_updated.connect(self.page_agentes.on_agent_list_updated)
        
        self.log_store.store_updated.connect(self.page_agentes.on_store_updated)
        self.log_store.store_updated.connect(self.page_mensagens.on_store_updated)
        self.log_store.store_updated.connect(self.page_menu.on_store_updated)

        self.log_store.store_updated.connect(self._update_timeline_range)
        self.timeline.time_changed.connect(self._on_timeline_time_changed)
        
        self.sidebar.buttons["Menu"].clicked.connect(lambda: self.show_page(0, "Menu"))
        self.sidebar.buttons["Agents"].clicked.connect(lambda: self.show_page(1, "Agents"))
        self.sidebar.buttons["Environment"].clicked.connect(lambda: self.show_page(2, "Environment"))
        self.sidebar.buttons["Messages"].clicked.connect(lambda: self.show_page(3, "Messages"))
        self.sidebar.buttons["Learning"].clicked.connect(lambda: self.show_page(4, "Learning"))

        self.sidebar.buttons["Menu"].setChecked(True)

    def _open_settings(self):
        if self.settings_dialog is None:
            self.settings_dialog = SettingsDialog(self)
            self.settings_dialog.theme_changed.connect(self._apply_theme)
            self.settings_dialog.setAttribute(Qt.WA_DeleteOnClose)
            self.settings_dialog.destroyed.connect(self._on_settings_closed)

        if self._current_theme == 'light':
            self.settings_dialog.btn_light.setChecked(True)
        else:
            self.settings_dialog.btn_dark.setChecked(True)
            
        self.settings_dialog.show()
        self.settings_dialog.activateWindow()

    def _on_settings_closed(self):
        self.settings_dialog = None

    def _open_manual(self):
        if self.manual_dialog is None:
            self.manual_dialog = ManualDialog(self)
            self.manual_dialog.setAttribute(Qt.WA_DeleteOnClose)
            self.manual_dialog.destroyed.connect(self._on_manual_closed)
            
        self.manual_dialog.show()
        self.manual_dialog.activateWindow()

    def _on_manual_closed(self):
        self.manual_dialog = None

    def _apply_theme(self, theme_name):
        if theme_name == self._current_theme:
            return 

        set_active_theme(theme_name)
        self._current_theme = theme_name 

        app_instance = QApplication.instance()
        if app_instance:
            stylesheet = load_stylesheet(theme_name)
            app_instance.setStyleSheet(stylesheet)
        self._propagate_theme_to_pages()

    def _propagate_theme_to_pages(self):
        pages = [
            self.page_menu,
            self.page_agentes,
            self.page_mensagens,
            self.page_ambiente,
            self.page_learning
        ]
        
        for page in pages:
            if hasattr(page, 'update_theme'):
                try:
                    page.update_theme()
                except Exception as e:
                    print(f"Erro ao atualizar tema em {page}: {e}")
        
        if hasattr(self, 'timeline'):
            self.timeline.update_theme()

    def _update_timeline_range(self):
        new_max_ms = self.log_store.get_total_duration_ms()
        if new_max_ms == 0: 
            return

        self.timeline.set_range(new_max_ms)
        
        if self.log_store.is_live:
            cycle = self.log_store.get_message_count_limit()
            self.timeline.set_time(new_max_ms, cycle, block_signals=True)
            self.timeline.set_live(True)

    def _on_timeline_time_changed(self, ms_value):
        max_val_ms = self.log_store.get_total_duration_ms()
        
        index = self.log_store.get_index_from_ms(ms_value)
        self.log_store.set_current_timeline_index(index)
        
        is_live = (ms_value >= max_val_ms - 100)
        self.log_store.is_live = is_live
        self.timeline.set_live(is_live)

        self.timeline.set_cycle(index)

        self.timeline_index_changed.emit(index)

    def show_page(self, index, title):
        self.stack.setCurrentIndex(index)
        self.topbar.set_title(title)

    def closeEvent(self, event):
        self.log_thread.quit()
        self.log_thread.wait()
        super().closeEvent(event)