"""AutoPOE2 - Trình Quản Lý Khay Hệ Thống (System Tray Manager).

Cung cấp tính năng thu nhỏ và chạy ngầm trên Windows System Tray (Taskbar Notification Area):
- Khởi động mặc định ở chế độ ẩn (Silent Mode), không chiếm diện tích màn hình làm việc của người dùng.
- Menu chuột phải: Hiện/Ẩn giao diện, Bật/Tắt Bot (F8), Thoát ứng dụng an toàn.
- Click đúp hoặc click chuột trái vào biểu tượng khay để bật/tắt nhanh giao diện.
- Tuân thủ Rule 4 (Anti-Monolithic Policy & Single Responsibility Principle).
"""

from __future__ import annotations

import logging
import threading
from typing import Any, Callable, Optional

from PIL import Image, ImageDraw

try:
    import pystray
    from pystray import MenuItem as item
except ImportError:
    pystray = None  # type: ignore[assignment]
    item = None  # type: ignore[assignment]


logger = logging.getLogger("AutoPOE2.SystemTray")


class SystemTrayManager:
    """Quản trị biểu tượng và menu khay hệ thống (System Tray) cho AutoPOE2 Control Center."""

    def __init__(
        self,
        app: Any,
        on_exit_callback: Optional[Callable[[], None]] = None,
        on_toggle_bot_callback: Optional[Callable[[], None]] = None,
    ):
        self.app = app
        self.on_exit_callback = on_exit_callback
        self.on_toggle_bot_callback = on_toggle_bot_callback
        self.icon: Optional[pystray.Icon] = None
        self._thread: Optional[threading.Thread] = None
        self._is_running = False

    def _create_icon_image(self) -> Image.Image:
        """Tạo icon sắc nét 64x64 màu xanh cyan đặc trưng của AutoPOE2."""
        img = Image.new("RGBA", (64, 64), color=(0, 0, 0, 0))
        draw = ImageDraw.Draw(img)

        # Vẽ nền tròn đậm
        draw.ellipse([4, 4, 60, 60], fill=(15, 23, 42, 255), outline=(56, 189, 248, 255), width=3)
        # Vẽ khiên năng lượng cyan (biểu trưng Energy Shield)
        draw.polygon(
            [(32, 14), (48, 22), (48, 42), (32, 52), (16, 42), (16, 22)],
            fill=(14, 165, 233, 230),
            outline=(255, 255, 255, 255),
        )
        return img

    def start(self) -> bool:
        """Khởi động luồng chạy System Tray."""
        if pystray is None:
            logger.warning("[SystemTray] Thư viện pystray chưa được cài đặt.")
            return False

        try:
            menu = pystray.Menu(
                item("Hiển thị / Ẩn Control Center", self.toggle_window, default=True),
                item("Bật / Tắt Bot (F8)", self.toggle_bot),
                pystray.Menu.SEPARATOR,
                item("Thoát AutoPOE2", self.quit_app),
            )

            self.icon = pystray.Icon(
                "AutoPOE2_Tray",
                self._create_icon_image(),
                "AutoPOE2 Control Center (Silent Mode)",
                menu=menu,
            )

            self._thread = threading.Thread(target=self.icon.run, daemon=True, name="SystemTrayThread")
            self._thread.start()
            self._is_running = True
            logger.info("[SystemTray] Đã khởi tạo biểu tượng System Tray thành công.")
            return True
        except Exception as e:
            logger.error(f"[SystemTray] Lỗi khởi tạo tray icon: {e}")
            return False

    def toggle_window(self, icon: Any = None, item_obj: Any = None) -> None:
        """Đảo trạng thái ẩn/hiện của cửa sổ Control Center trên Tkinter main thread."""
        self.app.after(0, self._do_toggle_window)

    def _do_toggle_window(self) -> None:
        try:
            # Kiểm tra trạng thái hiển thị của cửa sổ Tkinter
            if self.app.state() == "withdrawn" or not self.app.winfo_viewable():
                self.app.deiconify()
                self.app.lift()
                self.app.focus_force()
            else:
                self.app.withdraw()
        except Exception as e:
            logger.error(f"[SystemTray] Lỗi toggle window: {e}")

    def show_window(self) -> None:
        """Hiển thị cửa sổ Control Center lên màn hình."""
        self.app.after(0, self._do_show_window)

    def _do_show_window(self) -> None:
        try:
            self.app.deiconify()
            self.app.lift()
            self.app.focus_force()
        except Exception as e:
            logger.error(f"[SystemTray] Lỗi show window: {e}")

    def hide_window(self) -> None:
        """Thu nhỏ cửa sổ Control Center về System Tray."""
        self.app.after(0, self.app.withdraw)

    def toggle_bot(self, icon: Any = None, item_obj: Any = None) -> None:
        """Kích hoạt phím tắt F8 Bật/Tắt Bot qua callback."""
        if self.on_toggle_bot_callback:
            self.app.after(0, self.on_toggle_bot_callback)

    def quit_app(self, icon: Any = None, item_obj: Any = None) -> None:
        """Dừng khay hệ thống và đóng ứng dụng an toàn."""
        self.stop()
        if self.on_exit_callback:
            self.app.after(0, self.on_exit_callback)
        else:
            self.app.after(0, self.app.destroy)

    def stop(self) -> None:
        """Hủy biểu tượng trên khay hệ thống khi đóng app."""
        if self.icon:
            try:
                self.icon.stop()
            except Exception:
                pass
            self.icon = None
        self._is_running = False

    def is_running(self) -> bool:
        """Kiểm tra trạng thái hoạt động của System Tray."""
        return self._is_running
