"""Main window for Meeting Helper GUI."""

from __future__ import annotations

import platform
from pathlib import Path
from typing import TYPE_CHECKING

from PySide6.QtWidgets import (
    QApplication,
    QHBoxLayout,
    QMainWindow,
    QStackedWidget,
    QWidget,
)

if platform.system() == "Darwin":
    try:
        from AppKit import NSApp, NSApplicationActivationPolicyAccessory, NSApplicationActivationPolicyRegular
        HAS_APPKIT = True
    except ImportError:
        HAS_APPKIT = False
else:
    HAS_APPKIT = False

from meeting_helper.gui.screens import (
    DashboardScreen,
    RecordingsScreen,
    SettingsScreen,
    WorkspaceScreen,
)
from meeting_helper.gui.theme import apply_theme
from meeting_helper.gui.widgets import Sidebar


class MainWindow(QMainWindow):
    """Main application window with sidebar navigation."""

    def __init__(self, config=None, tray_icon=None):
        super().__init__()
        self.setWindowTitle("Meeting Helper")
        self.setMinimumSize(1000, 700)
        self.resize(1200, 800)

        self._config = config
        self._tray_icon = tray_icon
        self._force_quit = False

        apply_theme(QApplication.instance())
        self._setup_ui()
        self._connect_signals()
        self._show_screen("dashboard")

    def set_tray_icon(self, tray_icon):
        self._tray_icon = tray_icon

    def _setup_ui(self):
        central = QWidget()
        self.setCentralWidget(central)

        layout = QHBoxLayout(central)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)

        self._sidebar = Sidebar()
        self._sidebar.quit_requested.connect(self._quit_app)
        layout.addWidget(self._sidebar)

        self._content = QStackedWidget()
        self._content.setObjectName("content-area")
        layout.addWidget(self._content, 1)

        self._screens: dict[str, QWidget] = {}
        self._create_screens()

    def _create_screens(self):
        self._screens["dashboard"] = DashboardScreen()
        self._content.addWidget(self._screens["dashboard"])

        self._screens["recordings"] = RecordingsScreen()
        self._content.addWidget(self._screens["recordings"])

        self._screens["workspace"] = WorkspaceScreen()
        self._content.addWidget(self._screens["workspace"])

        self._screens["settings"] = SettingsScreen()
        self._content.addWidget(self._screens["settings"])

        # Pass config to screens that need it
        if self._config:
            self._apply_config()

    def _apply_config(self):
        """Push config to all screens that need it."""
        recordings = self._screens.get("recordings")
        if recordings and self._config:
            app_config = self._config.to_app_config()
            recordings.set_config(app_config)
            recordings.set_recordings_dir(self._config.recordings_dir)

        workspace = self._screens.get("workspace")
        if workspace and self._config:
            workspace.set_config(self._config)

        settings = self._screens.get("settings")
        if settings and self._config:
            settings.set_config(self._config)

        dashboard = self._screens.get("dashboard")
        if dashboard and self._config:
            dashboard.set_port(self._config.port)
            dashboard.update_workspace_info(self._config.repos, self._config.knowledge_path)

    def _connect_signals(self):
        self._sidebar.screen_selected.connect(self._show_screen)

    def _show_screen(self, screen_id: str):
        if screen_id in self._screens:
            self._content.setCurrentWidget(self._screens[screen_id])
            self._sidebar.select_screen(screen_id)

            screen = self._screens[screen_id]
            if hasattr(screen, "refresh"):
                screen.refresh()

    def on_status_update(self, daemon_running: bool, session_active: bool, meeting_name: str):
        """Called by MenuBarIcon polling."""
        self._sidebar.update_status(session_active, meeting_name)

        dashboard = self._screens.get("dashboard")
        if dashboard:
            dashboard.update_status(daemon_running, session_active, meeting_name)

    def _quit_app(self):
        self._force_quit = True
        QApplication.instance().quit()

    def closeEvent(self, event):
        if self._force_quit or self._tray_icon is None:
            event.accept()
        else:
            event.ignore()
            self.hide()
            if HAS_APPKIT:
                NSApp.setActivationPolicy_(NSApplicationActivationPolicyAccessory)

    def show(self):
        self.showMaximized()
        if HAS_APPKIT:
            NSApp.setActivationPolicy_(NSApplicationActivationPolicyRegular)
            NSApp.activateIgnoringOtherApps_(True)
