import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from ..config import settings as cfg_settings
from pathlib import Path


class SettingsDialog(tk.Toplevel):
    def __init__(self, parent):
        super().__init__(parent)
        self.title("PyUcc Settings")
        self.transient(parent)
        self.resizable(False, False)

        frm = ttk.Frame(self, padding=12)
        frm.grid(row=0, column=0, sticky="nsew")

        ttk.Label(frm, text="Baseline folder:").grid(row=0, column=0, sticky="w")
        self.baseline_var = tk.StringVar(value=cfg_settings.get_baseline_dir() or "")
        ent = ttk.Entry(frm, textvariable=self.baseline_var, width=60)
        ent.grid(row=0, column=1, sticky="w", padx=(8, 0))
        btn = ttk.Button(frm, text="Browse...", command=self._on_browse)
        btn.grid(row=0, column=2, sticky="w", padx=(8, 0))

        ttk.Label(frm, text="Keep last N baselines per profile:").grid(row=1, column=0, sticky="w", pady=(8,0))
        self.keep_var = tk.IntVar(value=cfg_settings.get_max_keep())
        spin = ttk.Spinbox(frm, from_=1, to=100, textvariable=self.keep_var, width=6)
        spin.grid(row=1, column=1, sticky="w", pady=(8,0))

        # Buttons
        btn_frame = ttk.Frame(frm)
        btn_frame.grid(row=3, column=0, columnspan=3, pady=(12,0), sticky="e")
        save_btn = ttk.Button(btn_frame, text="Save", command=self._on_save)
        save_btn.grid(row=0, column=0, padx=(0,8))
        cancel_btn = ttk.Button(btn_frame, text="Cancel", command=self._on_cancel)
        cancel_btn.grid(row=0, column=1)

        self.grab_set()
        # center over parent
        try:
            self.update_idletasks()
            pw = parent.winfo_width()
            ph = parent.winfo_height()
            px = parent.winfo_rootx()
            py = parent.winfo_rooty()
            dw = self.winfo_reqwidth()
            dh = self.winfo_reqheight()
            x = px + (pw - dw) // 2
            y = py + (ph - dh) // 2
            self.geometry(f"+{x}+{y}")
        except Exception:
            pass

    def _on_browse(self):
        d = filedialog.askdirectory()
        if d:
            self.baseline_var.set(str(Path(d)))

    def _on_save(self):
        bd = self.baseline_var.get().strip() or None
        try:
            mk = int(self.keep_var.get())
            if mk < 1:
                raise ValueError()
        except Exception:
            messagebox.showerror("Invalid value", "Keep count must be a positive integer")
            return
        cfg_settings.set_baseline_settings(bd, mk)
        messagebox.showinfo("Settings", "Settings saved")
        self.destroy()

    def _on_cancel(self):
        self.destroy()
