"""Các thành phần giao diện dùng chung."""
from __future__ import annotations

import os
import re
import subprocess
import sys
import tkinter as tk
from pathlib import Path
from tkinter import filedialog, messagebox, ttk
from typing import Any, Callable, Optional, Sequence

from .theme import MONO, Theme

TREE_TAGS = {"ok": "#15803d", "err": "#dc2626", "warn": "#b45309", "muted": "#6b7280"}


def make_tree(parent: tk.Misc, columns: Sequence[tuple], selectmode: str = "extended", height: int = 10, tree_col: bool = False):
    """columns: (id, tiêu đề, độ rộng, anchor). Trả về (frame, tree)."""
    frame = ttk.Frame(parent)
    tree = ttk.Treeview(frame, columns=[c[0] for c in columns], show="headings", selectmode=selectmode, height=height)
    if tree_col:                       # hiện cột mũi tên ▶/▼ để xổ nhóm
        tree.configure(show="tree headings")
        tree.column("#0", width=26, minwidth=26, stretch=False)
        tree.heading("#0", text="")
    for cid, head, width, *anchor in columns:
        tree.heading(cid, text=head)
        tree.column(cid, width=width, minwidth=40, anchor=(anchor[0] if anchor else "w"), stretch=True)
    ys = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
    xs = ttk.Scrollbar(frame, orient="horizontal", command=tree.xview)
    tree.configure(yscrollcommand=ys.set, xscrollcommand=xs.set)
    tree.grid(row=0, column=0, sticky="nsew")
    ys.grid(row=0, column=1, sticky="ns")
    xs.grid(row=1, column=0, sticky="ew")
    frame.rowconfigure(0, weight=1)
    frame.columnconfigure(0, weight=1)
    for tag, color in TREE_TAGS.items():
        tree.tag_configure(tag, foreground=color)
    return frame, tree


def ui_scale(win: tk.Misc) -> float:
    """Hệ số phóng theo độ phân giải màn hình (1.0 = 96 DPI, 1.5 = 150%...)."""
    try:
        return max(1.0, float(win.winfo_fpixels("1i")) / 96.0)
    except (TypeError, ValueError, tk.TclError):
        return 1.0


def scaled_geometry(win: tk.Misc, w: int, h: int) -> str:
    """Chuỗi geometry 'WxH+X+Y' đã nhân theo DPI, không vượt quá màn hình, căn giữa."""
    try:
        sc = ui_scale(win)
        sw, sh = int(win.winfo_screenwidth()), int(win.winfo_screenheight())
        w, h = min(int(w * sc), sw - 60), min(int(h * sc), sh - 110)
        return f"{w}x{h}+{max(0, (sw - w) // 2)}+{max(0, (sh - h) // 3)}"
    except (TypeError, ValueError, tk.TclError):
        return f"{w}x{h}"


def clear_tree(tree: ttk.Treeview) -> None:
    tree.delete(*tree.get_children())


def make_text(parent: tk.Misc, theme: Theme, terminal: bool = False, height: int = 10, wrap: str = "none"):
    frame = ttk.Frame(parent)
    text = tk.Text(frame, height=height, wrap=wrap, font=MONO, undo=False, padx=8, pady=6)
    ys = ttk.Scrollbar(frame, orient="vertical", command=text.yview)
    text.configure(yscrollcommand=ys.set)
    text.grid(row=0, column=0, sticky="nsew")
    ys.grid(row=0, column=1, sticky="ns")
    if wrap == "none":
        xs = ttk.Scrollbar(frame, orient="horizontal", command=text.xview)
        text.configure(xscrollcommand=xs.set)
        xs.grid(row=1, column=0, sticky="ew")
    frame.rowconfigure(0, weight=1)
    frame.columnconfigure(0, weight=1)
    theme.register_text(text, terminal)
    return frame, text


def set_text(text: tk.Text, content: str, diff: bool = False) -> None:
    text.configure(state="normal")
    text.delete("1.0", "end")
    for line in content.split("\n"):
        tag = ()
        if diff:
            if line.startswith("+") and not line.startswith("+++"):
                tag = ("add",)
            elif line.startswith("-") and not line.startswith("---"):
                tag = ("del",)
            elif line.startswith("@@") or line.startswith("---") or line.startswith("+++"):
                tag = ("hdr",)
        text.insert("end", line + "\n", tag)
    text.configure(state="disabled")


def show_text_window(app, title: str, content: str, diff: bool = False, size: str = "960x620") -> tk.Toplevel:
    top = tk.Toplevel(app.root)
    top.title(title)
    wh = [int(x) for x in size.split("x")]
    top.geometry(scaled_geometry(top, wh[0], wh[1]))
    top.configure(bg=app.theme.c["bg"])
    bar = ttk.Frame(top)
    bar.pack(side="bottom", fill="x", padx=10, pady=8)
    frame, text = make_text(top, app.theme, terminal=True, height=20)
    frame.pack(fill="both", expand=True, padx=10, pady=(10, 4))
    set_text(text, content or "(trống)", diff=diff)

    def copy() -> None:
        top.clipboard_clear()
        top.clipboard_append(content)

    def save() -> None:
        path = filedialog.asksaveasfilename(parent=top, defaultextension=".txt", initialfile="noi_dung.txt")
        if path:
            Path(path).write_text(content, encoding="utf-8")

    ttk.Button(bar, text="Sao chép", command=copy).pack(side="left")
    ttk.Button(bar, text="Lưu ra file...", command=save).pack(side="left", padx=6)
    ttk.Button(bar, text="Đóng", command=top.destroy).pack(side="right")
    return top


def open_folder(path: Path | str) -> None:
    p = str(path)
    try:
        if sys.platform.startswith("win"):
            os.startfile(p)  # type: ignore[attr-defined]
        elif sys.platform == "darwin":
            subprocess.Popen(["open", p])
        else:
            subprocess.Popen(["xdg-open", p])
    except Exception as e:
        messagebox.showinfo("Thư mục dữ liệu", f"{p}\n\n(Không tự mở được: {e})")


class ScrollableFrame(ttk.Frame):
    """Khung cuộn dọc: đặt widget vào `.body`. Thanh cuộn chỉ hiện khi nội dung dài hơn khung."""

    def __init__(self, parent: tk.Misc, bg_or_theme):
        super().__init__(parent)
        is_theme = hasattr(bg_or_theme, "register_canvas")
        bg = bg_or_theme.c["bg"] if is_theme else bg_or_theme          # luôn là mã màu hợp lệ (Tk không nhận chuỗi rỗng)
        self.canvas = tk.Canvas(self, highlightthickness=0, borderwidth=0, bg=bg)
        if is_theme:
            bg_or_theme.register_canvas(self.canvas)
        self.vbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vbar.set)
        self.canvas.pack(side="left", fill="both", expand=True)
        self.body = ttk.Frame(self.canvas)
        self._win = self.canvas.create_window((0, 0), window=self.body, anchor="nw")
        self.body.bind("<Configure>", lambda _e: self._refresh())
        self.canvas.bind("<Configure>", self._on_canvas)
        top = self.winfo_toplevel()                      # lăn chuột ở bất kỳ đâu trong cửa sổ
        top.bind("<MouseWheel>", self._wheel, add="+")
        top.bind("<Button-4>", lambda e: self._inside(e) and self._scroll(-1), add="+")
        top.bind("<Button-5>", lambda e: self._inside(e) and self._scroll(1), add="+")
        self._bar_shown = False

    def _on_canvas(self, event) -> None:
        self.canvas.itemconfigure(self._win, width=event.width)
        self._refresh()

    def _refresh(self) -> None:
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
        try:
            need = self.body.winfo_reqheight() > self.canvas.winfo_height() + 1 and self.canvas.winfo_height() > 1
        except tk.TclError:
            return
        if need and not self._bar_shown:
            self.vbar.pack(side="right", fill="y")
            self._bar_shown = True
        elif not need and self._bar_shown:
            self.vbar.pack_forget()
            self._bar_shown = False

    def _scroll(self, units: int) -> None:
        if self._bar_shown:
            self.canvas.yview_scroll(units, "units")

    def _inside(self, event) -> bool:
        """Con trỏ đang ở trong khung này và KHÔNG ở trên widget tự cuộn được (Text, bảng, danh sách xổ)."""
        w = event.widget
        try:
            if not str(w).startswith(str(self.canvas)):
                return False
            return w.winfo_class() not in ("Text", "Treeview", "Listbox", "TCombobox", "TSpinbox", "Spinbox")
        except (tk.TclError, AttributeError):
            return False

    def _wheel(self, event) -> None:
        if self._inside(event):
            self._scroll(-1 if event.delta > 0 else 1)

    def scroll_to_bottom(self) -> None:
        """Cuộn xuống cuối (vd để thấy ngay kết quả vừa chạy)."""
        self.update_idletasks()
        if self._bar_shown:
            self.canvas.yview_moveto(1.0)

    def scroll_to_top(self) -> None:
        self.canvas.yview_moveto(0.0)


def fit_dialog(top: tk.Toplevel, scroll: ScrollableFrame, footer: tk.Misc, parent: tk.Misc, min_w: int = 520) -> None:
    """Co cửa sổ vừa nội dung nhưng không vượt màn hình; phần dư được cuộn, footer (nút) luôn nhìn thấy."""
    top.update_idletasks()
    try:
        sw, sh = int(top.winfo_screenwidth()), int(top.winfo_screenheight())
        sc = ui_scale(top)
        w = min(max(scroll.body.winfo_reqwidth() + 24, int(min_w * sc)), sw - 80)
        want_h = scroll.body.winfo_reqheight() + footer.winfo_reqheight() + 8
        h = min(want_h, sh - int(150 * sc / 1.0 if sc > 1 else 150))   # chừa chỗ thanh tiêu đề + taskbar
        h = max(h, min(want_h, int(360 * sc)))
        try:
            visible = bool(parent.winfo_viewable())
        except tk.TclError:
            visible = False
        if visible:
            x = parent.winfo_rootx() + max(0, (parent.winfo_width() - w) // 2)
            y = parent.winfo_rooty() + max(0, (parent.winfo_height() - h) // 4)
        else:
            x, y = (sw - w) // 2, (sh - h) // 3
        x = max(0, min(x, sw - w - 10))
        y = max(10, min(y, sh - h - 90))
        top.geometry(f"{w}x{h}+{x}+{y}")
        top.minsize(min(w, int(min_w * sc)), min(h, int(320 * sc)))
        top.resizable(True, True)
    except (TypeError, ValueError, tk.TclError):
        pass


class Tooltip:
    """Chú thích khi rê chuột."""

    def __init__(self, widget: tk.Misc, text: str):
        self.widget, self.text, self.tip = widget, text, None
        widget.bind("<Enter>", self._show, add="+")
        widget.bind("<Leave>", self._hide, add="+")

    def _show(self, _e=None) -> None:
        if self.tip or not self.text:
            return
        x, y = self.widget.winfo_rootx() + 12, self.widget.winfo_rooty() + self.widget.winfo_height() + 4
        self.tip = tk.Toplevel(self.widget)
        self.tip.wm_overrideredirect(True)
        self.tip.wm_geometry(f"+{x}+{y}")
        tk.Label(self.tip, text=self.text, background="#1f2933", foreground="#ffffff", padx=8, pady=4,
                 wraplength=360, justify="left").pack()

    def _hide(self, _e=None) -> None:
        if self.tip:
            self.tip.destroy()
            self.tip = None


class DynamicForm(ttk.Frame):
    """Tạo form nhập liệu từ định nghĩa fields trong tasks.yaml.

    Ô có `ref` (VLAN, cổng, zone, address...) được liên kết với cấu hình thiết bị: ô đơn thành danh sách xổ xuống có sẵn giá trị
    đang có trên thiết bị (vẫn gõ tay được), ô nhiều giá trị có nút "Chọn từ cấu hình" mở bảng chọn.
    """

    def __init__(self, parent: tk.Misc):
        super().__init__(parent)
        self._vars: dict[str, Any] = {}
        self._kinds: dict[str, str] = {}
        self._texts: dict[str, tk.Text] = {}
        self._choices: dict[str, dict[str, str]] = {}
        self._opt_maps: dict[str, dict[str, Any]] = {}
        self.picker = None            # callable(tiêu_đề, danh_sách_option, giá_trị_hiện_tại) -> list[str] | None
        self.columnconfigure(1, weight=1)

    def build(self, fields: list[dict], theme: Theme, preset: Optional[dict] = None, options: Optional[dict] = None) -> None:
        """preset: giá trị đã nhập trước đó. options: {ref: [Option, ...]} lấy từ cấu hình thiết bị đang chọn."""
        preset, options = preset or {}, options or {}
        for w in self.winfo_children():
            w.destroy()
        self._vars.clear()
        self._kinds.clear()
        self._texts.clear()
        self._choices.clear()
        self._opt_maps.clear()
        if not fields:
            ttk.Label(self, text="Tác vụ này không cần nhập thêm thông tin.", style="Muted.TLabel").grid(
                row=0, column=0, columnspan=2, sticky="w", pady=6)
            return
        for r, f in enumerate(fields):
            name, kind = f["name"], f.get("kind", "text")
            f = dict(f, default=preset.get(name, f.get("default", False if kind == "bool" else "")))
            ref = f.get("ref")
            opts = list(options.get(ref, [])) if ref else []
            self._kinds[name] = kind
            label = f["label"] + (" *" if f.get("required") else "")
            ttk.Label(self, text=label).grid(row=r, column=0, sticky="nw", padx=(0, 12), pady=4)
            if kind == "bool":
                var = tk.BooleanVar(value=bool(f.get("default", False)))
                ttk.Checkbutton(self, variable=var).grid(row=r, column=1, sticky="w", pady=4)
                self._vars[name] = var
            elif kind == "choice":
                opt_list = f["options"]
                by_label = {str(o["label"]): str(o["value"]) for o in opt_list}
                label_by_val = {v: k for k, v in by_label.items()}
                default = label_by_val.get(str(f.get("default", opt_list[0]["value"])), str(opt_list[0]["label"]))
                var = tk.StringVar(value=default)
                ttk.Combobox(self, textvariable=var, values=list(by_label), state="readonly", width=34).grid(
                    row=r, column=1, sticky="w", pady=4)
                self._vars[name] = var
                self._choices[name] = by_label
            elif kind in ("list", "vlanlines", "vlans") and kind != "vlans" or (kind == "vlans" and ref):
                t = tk.Text(self, height=3 if kind != "vlanlines" else 5, width=44, font=MONO, wrap="word", padx=4, pady=3)
                theme.register_text(t)
                t.grid(row=r, column=1, sticky="ew", pady=4)
                t.insert("1.0", str(f.get("default", "")))
                self._texts[name] = t
                if ref:
                    self._picker_button(r, name, f, opts)
            elif ref and f.get("multi"):
                var = tk.StringVar(value=str(f.get("default", "")))
                ttk.Entry(self, textvariable=var).grid(row=r, column=1, sticky="ew", pady=4)
                self._vars[name] = var
                self._picker_button(r, name, f, opts)
            elif ref and kind not in ("password",):
                by_label = {o.label: o for o in opts}
                label_by_val = {o.value: o.label for o in opts}
                cur = str(f.get("default", ""))
                var = tk.StringVar(value=label_by_val.get(cur, cur))
                cb = ttk.Combobox(self, textvariable=var, values=list(by_label), width=46, height=14)
                cb.grid(row=r, column=1, sticky="ew", pady=4)
                cb.bind("<<ComboboxSelected>>", lambda _e, n=name: self._on_pick(n))
                self._vars[name] = var
                self._opt_maps[name] = by_label
                note = f"{len(opts)} lựa chọn từ cấu hình" if opts else "chưa có dữ liệu cấu hình - gõ tay hoặc bấm 'Đọc cấu hình'"
                ttk.Label(self, text=note, style="Muted.TLabel").grid(row=r, column=2, sticky="w", padx=(8, 0))
            else:
                var = tk.StringVar(value=str(f.get("default", "")))
                ttk.Entry(self, textvariable=var, show="*" if kind == "password" else "").grid(
                    row=r, column=1, sticky="ew", pady=4)
                self._vars[name] = var

    # ---- chọn từ cấu hình ----
    def _picker_button(self, row: int, name: str, f: dict, opts: list) -> None:
        ttk.Button(self, text=f"📋 Chọn từ cấu hình ({len(opts)})", command=lambda: self._pick_many(name, f, opts)).grid(
            row=row, column=2, sticky="nw", padx=(8, 0), pady=4)

    def _tokens(self, name: str) -> list[str]:
        raw = self._texts[name].get("1.0", "end") if name in self._texts else str(self._vars[name].get())
        return [t for t in re.split(r"[,\s;]+", raw.strip()) if t]

    def _pick_many(self, name: str, f: dict, opts: list) -> None:
        if not self.picker:
            return
        chosen = self.picker(f["label"], opts, self._tokens(name))
        if chosen is None:
            return
        text = ", ".join(chosen)
        if name in self._texts:
            self._texts[name].delete("1.0", "end")
            self._texts[name].insert("1.0", text)
        else:
            self._vars[name].set(text)

    def _on_pick(self, name: str) -> None:
        opt = self._opt_maps.get(name, {}).get(self._vars[name].get())
        if not opt:
            return
        for k, v in opt.extra:                       # vd chọn policy -> tự điền from/to zone
            if k in self._vars:
                lbl = next((l for l, o in self._opt_maps.get(k, {}).items() if o.value == v), v)
                self._vars[k].set(lbl)

    def set_value(self, name: str, value: str) -> None:
        if name in self._vars:
            self._vars[name].set(value)

    def values(self) -> dict:
        out: dict[str, Any] = {}
        for name, var in self._vars.items():
            val = var.get()
            if name in self._choices:                      # đổi nhãn hiển thị -> giá trị thật
                val = self._choices[name].get(val, val)
            elif name in self._opt_maps:
                opt = self._opt_maps[name].get(val)
                val = opt.value if opt else str(val).strip()
            out[name] = val
        for name, t in self._texts.items():
            out[name] = t.get("1.0", "end").strip()
        return out
