"""Menu bar (system tray) integration for Meeting Helper."""

from __future__ import annotations

import json
from pathlib import Path
from typing import TYPE_CHECKING

from PySide6.QtCore import QTimer
from PySide6.QtGui import QAction, QColor, QIcon, QPainter, QPixmap
from PySide6.QtWidgets import QMenu, QSystemTrayIcon

if TYPE_CHECKING:
    from meeting_helper.gui.main_window import MainWindow


class MenuBarIcon(QSystemTrayIcon):
    """System tray icon with status polling via daemon health endpoint."""

    STATUS_STOPPED = "stopped"
    STATUS_READY = "ready"
    STATUS_RECORDING = "recording"

    def __init__(self, main_window: "MainWindow", port: int = 7891):
        super().__init__()
        self._main_window = main_window
        self._port = port
        self._current_status = self.STATUS_STOPPED
        self._meeting_name = ""

        self._setup_icons()
        self._setup_menu()
        self._setup_polling()
        self._update_icon()

        self.activated.connect(self._on_activated)

    def _setup_icons(self):
        self._icons = {}
        for status, color in [
            (self.STATUS_STOPPED, "#5a5a5a"),
            (self.STATUS_READY, "#4ec9b0"),
            (self.STATUS_RECORDING, "#f14c4c"),
        ]:
            self._icons[status] = self._create_icon(color)

    def _create_icon(self, color: str) -> QIcon:
        size = 22
        pixmap = QPixmap(size, size)
        pixmap.fill(QColor(0, 0, 0, 0))
        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(QColor(color))
        painter.setPen(QColor(color))
        margin = 3
        painter.drawEllipse(margin, margin, size - margin * 2, size - margin * 2)
        painter.end()
        return QIcon(pixmap)

    def _setup_menu(self):
        self._menu = QMenu()
        self._menu.setStyleSheet("""
            QMenu { background-color: #1a1a1a; border: 1px solid #2a2a2a; border-radius: 6px; padding: 5px; }
            QMenu::item { color: #d4d4d4; padding: 8px 20px; border-radius: 4px; }
            QMenu::item:selected { background-color: #2a2a2a; }
            QMenu::separator { height: 1px; background-color: #2a2a2a; margin: 5px 10px; }
        """)

        self._status_action = QAction("Stopped")
        self._status_action.setEnabled(False)
        self._menu.addAction(self._status_action)
        self._menu.addSeparator()

        open_action = QAction("Open Meeting Helper")
        open_action.triggered.connect(self._show_main_window)
        self._menu.addAction(open_action)

        self._menu.addSeparator()

        quit_action = QAction("Quit")
        quit_action.triggered.connect(self._quit_app)
        self._menu.addAction(quit_action)

        self.setContextMenu(self._menu)

    def _setup_polling(self):
        self._poll_timer = QTimer()
        self._poll_timer.timeout.connect(self._poll_status)
        self._poll_timer.start(3000)

    def _poll_status(self):
        """Poll daemon health endpoint for status."""
        import urllib.request

        try:
            req = urllib.request.Request(f"http://127.0.0.1:{self._port}/health", method="GET")
            with urllib.request.urlopen(req, timeout=1) as resp:
                data = json.loads(resp.read().decode())

            daemon_running = True
            session_active = data.get("session_active", False)
            meeting = data.get("meeting", "")

            if session_active:
                new_status = self.STATUS_RECORDING
                self._meeting_name = meeting or "Recording..."
            else:
                new_status = self.STATUS_READY
                self._meeting_name = ""

        except Exception:
            daemon_running = False
            new_status = self.STATUS_STOPPED
            self._meeting_name = ""

        if new_status != self._current_status:
            self._current_status = new_status
            self._update_icon()
            self._update_status_text()

        # Notify main window
        self._main_window.on_status_update(
            daemon_running=daemon_running,
            session_active=(new_status == self.STATUS_RECORDING),
            meeting_name=self._meeting_name,
        )

    def _update_icon(self):
        self.setIcon(self._icons[self._current_status])

    def _update_status_text(self):
        if self._current_status == self.STATUS_RECORDING:
            text = f"Recording: {self._meeting_name}"
        elif self._current_status == self.STATUS_READY:
            text = "Ready (daemon running)"
        else:
            text = "Stopped"

        self._status_action.setText(text)
        self.setToolTip(f"Meeting Helper - {text}")

    def _on_activated(self, reason):
        if reason == QSystemTrayIcon.ActivationReason.Trigger:
            if self._main_window.isVisible():
                self._main_window.hide()
            else:
                self._show_main_window()
        elif reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            self._show_main_window()

    def _show_main_window(self):
        self._main_window.show()
        self._main_window.raise_()
        self._main_window.activateWindow()

    def _quit_app(self):
        self._poll_timer.stop()
        from PySide6.QtWidgets import QApplication
        QApplication.instance().quit()
