"""
Dialogo de configuracion del sistema.
Accesible solo con PIN de supervisor.
Permite ajustar stock, sede, ID del agente.
Los cambios se guardan en data/config.json.
"""
import customtkinter as ctk
import api
from ui.kb_shortcuts import bind_entry


class ConfigDialog(ctk.CTkToplevel):
    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)
        self.title("Configuracion del Sistema")
        self.geometry("460x420")
        self.resizable(False, False)
        self.grab_set()
        self.lift()
        self.focus_force()

        # Centrar sobre el padre
        self.update_idletasks()
        px = parent.winfo_rootx() + parent.winfo_width()  // 2 - 230
        py = parent.winfo_rooty() + parent.winfo_height() // 2 - 210
        self.geometry(f"+{px}+{py}")

        self._cfg = api.load_config()
        self._build()
        self.bind("<Escape>", lambda e: self.destroy())

    def _build(self):
        cfg = self._cfg

        # Boton X
        ctk.CTkButton(
            self, text="✕", width=30, height=30, corner_radius=6,
            fg_color="transparent", hover_color="#444444",
            text_color="#888888", font=ctk.CTkFont(size=14),
            command=self.destroy,
        ).place(x=420, y=8)

        # Titulo
        ctk.CTkLabel(
            self, text="Configuracion del Sistema",
            font=ctk.CTkFont(size=17, weight="bold"),
            text_color="#4fc3f7",
        ).pack(anchor="w", padx=24, pady=(20, 4))
        ctk.CTkLabel(
            self, text="Cambios protegidos por PIN de supervisor",
            font=ctk.CTkFont(size=11), text_color="#7a8ba8",
        ).pack(anchor="w", padx=24, pady=(0, 16))

        # Card contenedora
        card = ctk.CTkFrame(
            self, fg_color="#0f1d32", corner_radius=12,
            border_width=1, border_color="#1a3050",
        )
        card.pack(fill="x", padx=20, pady=(0, 16))

        # --- Stock total ---
        row1 = ctk.CTkFrame(card, fg_color="transparent")
        row1.pack(fill="x", padx=20, pady=(16, 8))

        ctk.CTkLabel(
            row1, text="Stock de manillas:",
            font=ctk.CTkFont(size=13), text_color="#e8edf5",
            width=160, anchor="w",
        ).pack(side="left")

        self._entry_stock = ctk.CTkEntry(
            row1, width=80, height=34,
            font=ctk.CTkFont(size=13),
            placeholder_text="6",
        )
        self._entry_stock.pack(side="left")
        self._entry_stock.insert(0, str(cfg.get("stock_total", 6)))
        bind_entry(self._entry_stock)

        ctk.CTkLabel(
            row1, text="unidades",
            font=ctk.CTkFont(size=11), text_color="#7a8ba8",
        ).pack(side="left", padx=(8, 0))

        # --- Sede ---
        row2 = ctk.CTkFrame(card, fg_color="transparent")
        row2.pack(fill="x", padx=20, pady=(8, 8))

        ctk.CTkLabel(
            row2, text="Sede (venue_id):",
            font=ctk.CTkFont(size=13), text_color="#e8edf5",
            width=160, anchor="w",
        ).pack(side="left")

        self._entry_venue = ctk.CTkEntry(
            row2, width=200, height=34,
            font=ctk.CTkFont(size=13),
            placeholder_text="Cuenca-racar",
        )
        self._entry_venue.pack(side="left")
        self._entry_venue.insert(0, cfg.get("venue_id", ""))
        bind_entry(self._entry_venue)

        # --- Agent ID ---
        row3 = ctk.CTkFrame(card, fg_color="transparent")
        row3.pack(fill="x", padx=20, pady=(8, 16))

        ctk.CTkLabel(
            row3, text="ID del agente:",
            font=ctk.CTkFont(size=13), text_color="#e8edf5",
            width=160, anchor="w",
        ).pack(side="left")

        self._entry_agent_id = ctk.CTkEntry(
            row3, width=200, height=34,
            font=ctk.CTkFont(size=13),
            placeholder_text="CUE001",
        )
        self._entry_agent_id.pack(side="left")
        self._entry_agent_id.insert(0, cfg.get("agent_id", ""))
        bind_entry(self._entry_agent_id)

        # --- Status ---
        self._lbl_status = ctk.CTkLabel(
            self, text="",
            font=ctk.CTkFont(size=12), text_color="#7a8ba8",
        )
        self._lbl_status.pack(anchor="w", padx=24, pady=(0, 8))

        # --- Botones ---
        btn_frame = ctk.CTkFrame(self, fg_color="transparent")
        btn_frame.pack(fill="x", padx=20, pady=(0, 20))

        ctk.CTkButton(
            btn_frame, text="Cancelar",
            width=120, height=38, corner_radius=8,
            fg_color="#1e2232", hover_color="#2a2e44",
            font=ctk.CTkFont(size=13),
            command=self.destroy,
        ).pack(side="right", padx=(8, 0))

        ctk.CTkButton(
            btn_frame, text="Guardar cambios",
            width=160, height=38, corner_radius=8,
            fg_color="#1565c0", hover_color="#0d47a1",
            font=ctk.CTkFont(size=13, weight="bold"),
            command=self._save,
        ).pack(side="right")

    def _save(self):
        # Validar stock
        stock_str = self._entry_stock.get().strip()
        try:
            stock = int(stock_str)
            if stock < 1:
                raise ValueError
        except ValueError:
            self._lbl_status.configure(
                text="Stock debe ser un numero entero >= 1.", text_color="#f44336"
            )
            return

        venue = self._entry_venue.get().strip()
        if not venue:
            self._lbl_status.configure(
                text="La sede no puede estar vacia.", text_color="#f44336"
            )
            return

        agent_id = self._entry_agent_id.get().strip()

        cfg = api.load_config()
        cfg["stock_total"] = stock
        cfg["venue_id"]    = venue
        if agent_id:
            cfg["agent_id"] = agent_id
        api.save_config(cfg)

        self._lbl_status.configure(
            text="Configuracion guardada correctamente.", text_color="#00e676"
        )
        self.after(1200, self.destroy)
