"""Tab Cài đặt: kết nối, người dùng & phân quyền, đổi mật khẩu, thông tin."""
from __future__ import annotations

import tkinter as tk
from tkinter import messagebox, simpledialog, ttk

from core import APP_NAME, APP_VERSION
from core.security import ROLE_LABELS, ROLES, AuthError
from .widgets import clear_tree, make_tree, open_folder


class SettingsTab(ttk.Frame):
    def __init__(self, parent, app):
        super().__init__(parent, padding=14)
        self.app, self.ctx = app, app.ctx
        db = self.ctx.db
        ttk.Label(self, text="Cài đặt", style="Title.TLabel").pack(anchor="w")

        conn = ttk.LabelFrame(self, text="Kết nối thiết bị", padding=10)
        conn.pack(fill="x", pady=(10, 8))
        self.timeout = tk.IntVar(value=int(db.get_setting("timeout", 30)))
        self.workers = tk.IntVar(value=int(db.get_setting("workers", 5)))
        self.delay = tk.DoubleVar(value=float(db.get_setting("delay_factor", 1.0)))
        self.save_def = tk.BooleanVar(value=bool(db.get_setting("save_default", True)))
        for i, (label, var, lo, hi, inc) in enumerate([("Timeout kết nối (giây)", self.timeout, 5, 300, 5),
                                                      ("Số luồng song song mặc định", self.workers, 1, 30, 1),
                                                      ("Hệ số chờ (tăng nếu thiết bị chậm)", self.delay, 0.5, 8, 0.5)]):
            ttk.Label(conn, text=label).grid(row=i, column=0, sticky="w", pady=3, padx=(0, 12))
            ttk.Spinbox(conn, from_=lo, to=hi, increment=inc, textvariable=var, width=8).grid(row=i, column=1, sticky="w")
        ttk.Checkbutton(conn, text="Mặc định lưu cấu hình (write memory/commit) sau khi áp dụng", variable=self.save_def).grid(
            row=3, column=0, columnspan=2, sticky="w", pady=3)
        self.hk_labels = {"tofu": "Tin ở lần đầu rồi ghi nhớ - chặn nếu khóa đổi (khuyến nghị)", "strict": "Nghiêm ngặt - chỉ thiết bị đã 'Tin cậy khóa SSH'",
                          "off": "Tắt kiểm tra khóa SSH (không khuyến nghị)"}
        self.hk = tk.StringVar(value=self.hk_labels.get(db.get_setting("host_key_mode", "tofu"), self.hk_labels["tofu"]))
        ttk.Label(conn, text="Kiểm tra khóa SSH của thiết bị").grid(row=4, column=0, sticky="w", pady=3, padx=(0, 12))
        ttk.Combobox(conn, textvariable=self.hk, values=list(self.hk_labels.values()), state="readonly", width=62).grid(row=4, column=1, sticky="w")
        self.keep = tk.IntVar(value=int(db.get_setting("retention_keep", 50)))
        self.days = tk.IntVar(value=int(db.get_setting("retention_days", 0)))
        ttk.Label(conn, text="Giữ tối đa bao nhiêu bản sao lưu / thiết bị").grid(row=5, column=0, sticky="w", pady=3, padx=(0, 12))
        ttk.Spinbox(conn, from_=1, to=1000, textvariable=self.keep, width=8).grid(row=5, column=1, sticky="w")
        ttk.Label(conn, text="Xóa bản sao lưu cũ hơn (ngày, 0 = không xóa theo ngày)").grid(row=6, column=0, sticky="w", pady=3, padx=(0, 12))
        ttk.Spinbox(conn, from_=0, to=3650, textvariable=self.days, width=8).grid(row=6, column=1, sticky="w")
        bt = ttk.Frame(conn)
        bt.grid(row=7, column=0, columnspan=2, sticky="w", pady=(6, 0))
        ttk.Button(bt, text="Lưu cài đặt", style="Accent.TButton", command=self.save_conn).pack(side="left")
        ttk.Button(bt, text="Dọn dẹp bản sao lưu cũ ngay", command=self.prune_now).pack(side="left", padx=8)

        acct = ttk.LabelFrame(self, text="Tài khoản & phân quyền", padding=10)
        acct.pack(fill="both", expand=True, pady=(0, 8))
        bar = ttk.Frame(acct)
        bar.pack(fill="x", pady=(0, 6))
        ttk.Button(bar, text="Đổi mật khẩu của tôi", command=self.change_my_password).pack(side="left")
        self.admin_btns = []
        for text, fn in [("➕ Thêm người dùng", self.add_user), ("Đặt lại mật khẩu", self.reset_password),
                         ("Đổi vai trò", self.change_role), ("🗑 Xóa", self.delete_user)]:
            b = ttk.Button(bar, text=text, command=fn)
            b.pack(side="left", padx=(6, 0))
            self.admin_btns.append(b)
        f, self.users = make_tree(acct, [("u", "Tên đăng nhập", 160), ("r", "Vai trò", 200), ("c", "Tạo lúc", 150)],
                                  selectmode="browse", height=5)
        f.pack(fill="both", expand=True)
        ttk.Label(acct, style="Muted.TLabel", wraplength=900, justify="left", text=(
            "Admin: toàn quyền · Operator: thêm/sửa thiết bị, chạy cấu hình, sao lưu, khôi phục · Viewer: chỉ xem. "
            "Lưu ý: phân quyền áp dụng trong ứng dụng; mọi tài khoản dùng chung khóa mã hóa dữ liệu thiết bị.")).pack(anchor="w", pady=(6, 0))
        if not self.ctx.can("manage_users"):
            for b in self.admin_btns:
                b.configure(state="disabled")

        about = ttk.LabelFrame(self, text="Thông tin", padding=10)
        about.pack(fill="x")
        ttk.Label(about, text=f"{APP_NAME} v{APP_VERSION}   ·   Dữ liệu lưu tại: {self.ctx.home}").pack(side="left")
        ttk.Button(about, text="Mở thư mục dữ liệu", command=lambda: open_folder(self.ctx.home)).pack(side="right")
        self.refresh_users()

    def save_conn(self) -> None:
        db = self.ctx.db
        db.set_setting("timeout", int(self.timeout.get()))
        db.set_setting("workers", int(self.workers.get()))
        db.set_setting("delay_factor", float(self.delay.get()))
        db.set_setting("save_default", bool(self.save_def.get()))
        db.set_setting("host_key_mode", next((k for k, v in self.hk_labels.items() if v == self.hk.get()), "tofu"))
        db.set_setting("retention_keep", max(1, int(self.keep.get())))
        db.set_setting("retention_days", max(0, int(self.days.get())))
        db.audit(self.ctx.username, "settings", "đổi cài đặt kết nối")
        self.app.set_status("Đã lưu cài đặt.")

    def prune_now(self) -> None:
        self.save_conn()
        n = sum(self.ctx.engine._prune(d) for d in self.ctx.db.list_devices())
        messagebox.showinfo("Dọn dẹp", f"Đã xóa {n} bản sao lưu cũ theo chính sách.", parent=self.app.root)

    def refresh_users(self) -> None:
        clear_tree(self.users)
        for u in self.ctx.db.list_users():
            self.users.insert("", "end", iid=u["username"], values=(u["username"], ROLE_LABELS.get(u["role"], u["role"]), u["created"]))

    def _sel(self):
        s = self.users.selection()
        return s[0] if s else None

    def _ask_password(self, who: str) -> str | None:
        p1 = simpledialog.askstring("Mật khẩu mới", f"Mật khẩu mới cho '{who}' (tối thiểu 8 ký tự):", show="*", parent=self.app.root)
        if not p1:
            return None
        p2 = simpledialog.askstring("Nhập lại", "Nhập lại mật khẩu:", show="*", parent=self.app.root)
        if p1 != p2:
            messagebox.showerror("Mật khẩu", "Hai mật khẩu không khớp.", parent=self.app.root)
            return None
        return p1

    def _try(self, fn, ok_msg: str) -> None:
        try:
            fn()
            self.ctx.db.audit(self.ctx.username, "user_mgmt", ok_msg)
            self.refresh_users()
            self.app.set_status(ok_msg)
        except AuthError as e:
            messagebox.showerror("Lỗi", str(e), parent=self.app.root)

    def change_my_password(self) -> None:
        me = self.ctx.username
        pw = self._ask_password(me)
        if pw:
            self._try(lambda: self.ctx.vault.set_password(me, pw), f"Đã đổi mật khẩu của {me}")

    def add_user(self) -> None:
        name = simpledialog.askstring("Thêm người dùng", "Tên đăng nhập:", parent=self.app.root)
        if not name:
            return
        role = simpledialog.askstring("Vai trò", "Nhập vai trò: admin / operator / viewer", initialvalue="operator", parent=self.app.root)
        if role not in ROLES:
            return messagebox.showerror("Vai trò", "Vai trò phải là: admin, operator hoặc viewer.", parent=self.app.root)
        pw = self._ask_password(name)
        if pw:
            self._try(lambda: self.ctx.vault.add_user(name, pw, role), f"Đã thêm người dùng {name} ({role})")

    def reset_password(self) -> None:
        u = self._sel()
        pw = u and self._ask_password(u)
        if pw:
            self._try(lambda: self.ctx.vault.set_password(u, pw), f"Đã đặt lại mật khẩu của {u}")

    def change_role(self) -> None:
        u = self._sel()
        if not u or u == self.ctx.username:
            return messagebox.showinfo("Vai trò", "Chọn một người dùng khác tài khoản đang đăng nhập.", parent=self.app.root)
        role = simpledialog.askstring("Vai trò", "admin / operator / viewer", parent=self.app.root)
        if role in ROLES:
            self.ctx.db.update_user_role(u, role)
            self.ctx.db.audit(self.ctx.username, "user_mgmt", f"{u} -> {role}")
            self.refresh_users()

    def delete_user(self) -> None:
        u = self._sel()
        if u and messagebox.askyesno("Xóa người dùng", f"Xóa tài khoản '{u}'?", parent=self.app.root):
            self._try(lambda: self.ctx.vault.delete_user(u), f"Đã xóa người dùng {u}")
