"""Cửa sổ chính: thanh tiêu đề, các tab, hàng đợi sự kiện giữa luồng nền và giao diện."""
from __future__ import annotations

import queue
import threading
import tkinter as tk
from tkinter import messagebox, ttk
from typing import Any, Callable, Optional

from core import APP_NAME, APP_VERSION
from core.security import ROLE_LABELS
from .context import AppContext
from .theme import Theme
from .widgets import scaled_geometry, ui_scale


class MainWindow:
    def __init__(self, root: tk.Tk, ctx: AppContext, theme: Theme):
        self.root, self.ctx, self.theme = root, ctx, theme
        self.tabs: dict[str, ttk.Frame] = {}
        self._closing = False
        root.title(f"{APP_NAME} {APP_VERSION}")
        root.geometry(scaled_geometry(root, 1320, 800))
        sc = ui_scale(root)
        root.minsize(int(1000 * sc), int(640 * sc))
        root.protocol("WM_DELETE_WINDOW", self.on_close)
        ctx.engine.emit = lambda kind, **kw: ctx.events.put((kind, kw))
        self._build_header()
        self._build_tabs()
        self._build_statusbar()
        self.root.after(100, self._pump)
        self.set_status("Sẵn sàng.")

    # ------------------------------------------------------------------ bố cục
    def _build_header(self) -> None:
        bar = ttk.Frame(self.root, padding=(16, 10))
        bar.pack(fill="x")
        ttk.Label(bar, text="🌐 NetAutoConfig", style="Title.TLabel").pack(side="left")
        ttk.Label(bar, text="  Cấu hình & quản lý thiết bị mạng tự động", style="Muted.TLabel").pack(side="left", pady=(6, 0))
        u = self.ctx.vault.user
        right = ttk.Frame(bar)
        right.pack(side="right")
        ttk.Label(right, text=f"👤 {u['username']}  ({ROLE_LABELS.get(u['role'], u['role'])})", style="Muted.TLabel").pack(
            side="left", padx=(0, 12))
        self.theme_btn = ttk.Button(right, text="🌙 Giao diện tối", command=self.toggle_theme)
        self.theme_btn.pack(side="left")
        ttk.Separator(self.root).pack(fill="x")

    def _build_tabs(self) -> None:
        from .tab_backups import BackupsTab
        from .tab_compliance import ComplianceTab
        from .tab_dashboard import DashboardTab
        from .tab_inventory import InventoryTab
        from .tab_logs import LogsTab
        from .tab_settings import SettingsTab
        from .tab_tasks import TasksTab
        from .tab_tools import ToolsTab
        from .tab_vendors import VendorsTab

        self.nb = ttk.Notebook(self.root)
        self.nb.pack(fill="both", expand=True, padx=12, pady=(10, 4))
        spec = [("dashboard", "📊 Tổng quan", DashboardTab), ("inventory", "🖧 Thiết bị", InventoryTab),
                ("tasks", "⚙ Cấu hình", TasksTab), ("backups", "💾 Sao lưu", BackupsTab), ("compliance", "🛡 Tuân thủ", ComplianceTab),
                ("logs", "📜 Nhật ký", LogsTab), ("tools", "🧰 Công cụ", ToolsTab),
                ("vendors", "✅ Hãng hỗ trợ", VendorsTab), ("settings", "🔧 Cài đặt", SettingsTab)]
        for key, title, cls in spec:
            tab = cls(self.nb, self)
            self.tabs[key] = tab
            self.nb.add(tab, text=title)
        self.nb.bind("<<NotebookTabChanged>>", self._on_tab_changed)

    def _build_statusbar(self) -> None:
        self.status = tk.StringVar()
        bar = ttk.Frame(self.root, padding=(14, 4))
        bar.pack(fill="x", side="bottom")
        ttk.Label(bar, textvariable=self.status, style="Muted.TLabel").pack(side="left")
        self.sched_lbl = ttk.Label(bar, text="", style="Muted.TLabel")
        self.sched_lbl.pack(side="right")

    # ------------------------------------------------------------------ tiện ích cho các tab
    def set_status(self, msg: str) -> None:
        self.status.set(msg)

    def select_tab(self, key: str) -> None:
        self.nb.select(self.tabs[key])

    def _on_tab_changed(self, _e=None) -> None:
        tab = self.root.nametowidget(self.nb.select())
        if hasattr(tab, "on_show"):
            tab.on_show()

    def require(self, perm: str, what: str = "thao tác này") -> bool:
        if self.ctx.can(perm):
            return True
        messagebox.showwarning("Không đủ quyền", f"Tài khoản của bạn không có quyền thực hiện {what}.", parent=self.root)
        return False

    def toggle_theme(self) -> None:
        mode = "dark" if self.theme.mode == "light" else "light"
        self.theme.apply(mode)
        self.ctx.db.set_setting("theme", mode)
        self.theme_btn.configure(text="☀ Giao diện sáng" if mode == "dark" else "🌙 Giao diện tối")

    def notify_devices_changed(self) -> None:
        for tab in self.tabs.values():
            if hasattr(tab, "refresh_devices"):
                tab.refresh_devices()

    def call_soon(self, fn: Callable[[], Any]) -> None:
        """Gọi fn trên luồng giao diện (an toàn khi gọi từ luồng nền)."""
        self.ctx.events.put(("callback", {"fn": fn}))

    def run_bg(self, work: Callable[[], Any], done: Optional[Callable[[Any, Optional[BaseException]], None]] = None) -> None:
        """Chạy work() ở luồng nền, rồi gọi done(kết_quả, lỗi) trên luồng giao diện."""
        def target() -> None:
            res, err = None, None
            try:
                res = work()
            except BaseException as e:  # noqa: BLE001 - chuyển lỗi về luồng giao diện
                err = e
            if done:
                self.call_soon(lambda: done(res, err))

        threading.Thread(target=target, daemon=True).start()

    # ------------------------------------------------------------------ vòng lặp sự kiện
    def _pump(self) -> None:
        if self._closing:
            return
        try:
            for _ in range(200):
                kind, data = self.ctx.events.get_nowait()
                if kind == "callback":
                    try:
                        data["fn"]()
                    except Exception as e:  # lỗi ở callback không được làm chết vòng lặp
                        from core.logger import get_logger
                        get_logger().error("Lỗi giao diện: %s", e, exc_info=True)
                    continue
                for tab in self.tabs.values():
                    handler = getattr(tab, "on_event", None)
                    if handler:
                        handler(kind, data)
        except queue.Empty:
            pass
        sch = self.ctx.scheduler
        self.sched_lbl.configure(text=f"⏱ Sao lưu tự động: mỗi {sch.interval_min} phút" if sch.running else "")
        self.root.after(100, self._pump)

    def on_close(self) -> None:
        if self.ctx.scheduler.running and not messagebox.askyesno(
                "Thoát", "Sao lưu tự động đang bật và sẽ dừng khi đóng chương trình.\nVẫn thoát?", parent=self.root):
            return
        self._closing = True
        self.ctx.scheduler.stop()
        if self.ctx.jobs:
            self.ctx.jobs.stop()
        self.ctx.db.close()
        self.root.destroy()
