import logging
from PySide6.QtGui import QAction, QIcon
from PySide6.QtWidgets import QMenu, QSystemTrayIcon

logger = logging.getLogger(__name__)


class TrayManager:
    def __init__(self, app, bridge):
        self.app = app
        self.bridge = bridge
        self.tray = QSystemTrayIcon(app.windowIcon(), app)
        self.tray.setToolTip("QTran")
        self.menu = QMenu()
        self._setup_menu()
        self._connect_signals()

    def _setup_menu(self):
        # Show action
        show_action = QAction("Show", self.menu)
        show_action.triggered.connect(self._show_window)

        # Theme submenu
        theme_menu = QMenu("Theme", self.menu)
        self.theme_actions = {}
        for name, is_dark in [("Dark", True), ("Light", False)]:
            action = QAction(name, theme_menu, checkable=True)
            action.triggered.connect(lambda chk, d=is_dark: setattr(self.bridge, "isDark", d))
            theme_menu.addAction(action)
            self.theme_actions[is_dark] = action

        # Mode submenu
        mode_menu = QMenu("Mode", self.menu)
        self.mode_actions = {}
        for name, mode in [("Mirror", "mirror"), ("Google", "google")]:
            action = QAction(name, mode_menu, checkable=True)
            action.triggered.connect(lambda chk, m=mode: setattr(self.bridge, "translationMode", m))
            mode_menu.addAction(action)
            self.mode_actions[mode] = action

        # Shortcut submenu
        trigger_menu = QMenu("Shortcut", self.menu)
        self.trigger_actions = {}
        for key in ["Ctrl", "Shift"]:
            action = QAction(f"Double-click {key}", trigger_menu, checkable=True)
            action.triggered.connect(lambda chk, k=key: setattr(self.bridge, "triggerKey", k))
            trigger_menu.addAction(action)
            self.trigger_actions[key] = action

        # Language submenu
        lang_menu = QMenu("Default Lang", self.menu)
        self.lang_actions = {}
        lang_data = {
            "简体中文": "zh-CN",
            "English": "en",
            "日本語": "ja",
            "한국어": "ko",
        }
        for name, code in lang_data.items():
            action = QAction(name, lang_menu, checkable=True)
            action.triggered.connect(lambda chk, c=code: setattr(self.bridge, "defaultLang", c))
            lang_menu.addAction(action)
            self.lang_actions[code] = action

        # Quit
        quit_action = QAction("Quit", self.menu)
        quit_action.triggered.connect(self.app.quit)

        # Build menu
        self.menu.addAction(show_action)
        self.menu.addMenu(theme_menu)
        self.menu.addMenu(mode_menu)
        self.menu.addMenu(trigger_menu)
        self.menu.addMenu(lang_menu)
        self.menu.addSeparator()
        self.menu.addAction(quit_action)

        self.tray.setContextMenu(self.menu)
        self.update_checks()

    def _connect_signals(self):
        self.bridge.isDarkChanged.connect(self.update_checks)
        self.bridge.translationModeChanged.connect(self.update_checks)
        self.bridge.defaultLangChanged.connect(self.update_checks)
        self.bridge.triggerKeyChanged.connect(self.update_checks)
        
        self.tray.activated.connect(self._on_activated)

    def update_checks(self):
        for d, act in self.theme_actions.items():
            act.setChecked(self.bridge.isDark == d)
        for m, act in self.mode_actions.items():
            act.setChecked(self.bridge.translationMode == m)
        for k, act in self.trigger_actions.items():
            act.setChecked(self.bridge.triggerKey == k)
        for c, act in self.lang_actions.items():
            act.setChecked(self.bridge.defaultLang == c)

    def _show_window(self):
        self.bridge.isShowingFromTray = True
        if hasattr(self.app, "main_window"):
            self.app.main_window.show()

    def _on_activated(self, reason):
        if reason == QSystemTrayIcon.Trigger:
            self._show_window()

    def show(self):
        self.tray.show()
