import webbrowser
from sys import platform
from os import environ

from PySide6 import QtGui
from PySide6.QtCore import Qt
from PySide6.QtUiTools import QUiLoader
from PySide6.QtWidgets import QMainWindow, QSizePolicy

from config.config_manager import ConfigManager
from controllers.audio_controller import AudioController
from controllers.glow_animator import GlowAnimator
from controllers.window_dragger import WindowDragger
from tools import discord_oauth
from tools.constants import NO_STAFF, Urls

from fake_patch_notes import patch_note

# For Linux Wayland to authorize moving window
if platform.startswith('linux'):
   environ["QT_QPA_PLATFORM"] = "xcb"

class MainWindow(QMainWindow):
    def __init__(self, bundle_dir: str, config_manager: ConfigManager):
        super().__init__()

        self.config = config_manager

        # UI
        self.ui = QUiLoader().load(f"{bundle_dir}/ui/mainwindow_vertical_pager.ui", self)
        self.setCentralWidget(self.ui.centralWidget())
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | Qt.WindowType.Window)
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)

        # centrage vertical du bouton connexion
        if NO_STAFF:
            self.ui.staff_btn.hide()
            layout = self.ui.verticalLayout_6
            # Trouver et modifier le spacer item
            for i in range(layout.count()):
                item = layout.itemAt(i)
                if item.spacerItem():  # C'est un spacer
                    item.spacerItem().changeSize(20, 15, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
                    layout.invalidate()  # Forcer le recalcul du layout
                    break
            # self.ui.spacer_substitution.hide()

        if config_manager.get_discord_user() == "" or config_manager.get_discord_user().isspace():
            self.ui.queue_lbl.hide()
            self.ui.queue_position.hide()
            self.ui.stackedWidget.setCurrentIndex(1)

        self.ui.info_text.setMarkdown(patch_note)

        # Sous-systèmes
        self._audio   = AudioController(self.config, self.ui.audio_volume_adjust, self.ui.mute_btn)
        self._glow    = GlowAnimator(self.ui.connexion_btn)
        self._dragger = WindowDragger(self)

        self._connect_signals()
        self._center_window()
        self.show()

    # ------------------------------------------------------------------
    # Setup
    # ------------------------------------------------------------------

    def _connect_signals(self) -> None:
        self.ui.close_btn.clicked.connect(self.close)
        self.ui.minimize_btn.clicked.connect(self.showMinimized)
        self.ui.connexion_btn.clicked.connect(self._on_connexion)
        self.ui.discord_btn.clicked.connect(self._on_discord)
        self.ui.intranet_btn.clicked.connect(self._on_intranet)

        self.ui.discord_auth_btn.clicked.connect(self._on_discord_auth_btn)

    def _center_window(self) -> None:
        self.adjustSize()
        screen = (
            QtGui.QGuiApplication.screenAt(QtGui.QCursor.pos())
            or QtGui.QGuiApplication.primaryScreen()
        )
        rect = self.frameGeometry()
        rect.moveCenter(screen.availableGeometry().center())
        self.move(rect.topLeft())

    # ------------------------------------------------------------------
    # Button handlers
    # ------------------------------------------------------------------

    def _on_connexion(self) -> None:
        pass  # à implémenter

    @staticmethod
    def _on_discord() -> None:
        webbrowser.open(Urls.DISCORD.value)

    def _on_intranet(self) -> None:
        webbrowser.open(Urls.INTRANET.value)
        self._glow.start()

    def _on_discord_auth_btn(self) -> None:
        self.config.set_discord_user(discord_oauth.get_discord_user_id())
        self.config.save()
        self.ui.stackedWidget.setCurrentIndex(0)

    # ------------------------------------------------------------------
    # Mouse events → délégués au WindowDragger
    # ------------------------------------------------------------------

    def mousePressEvent(self, event: QtGui.QMouseEvent) -> None:
        self._dragger.mouse_press(event)
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event: QtGui.QMouseEvent) -> None:
        self._dragger.mouse_move(event)
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event: QtGui.QMouseEvent) -> None:
        self._dragger.mouse_release(event)
        super().mouseReleaseEvent(event)

    # ------------------------------------------------------------------
    # Close
    # ------------------------------------------------------------------

    def closeEvent(self, event) -> None:
        self.config.save()
        super().closeEvent(event)
