"""
Info tab — display server details, edit button.
"""

import customtkinter as ctk


class InfoTab(ctk.CTkFrame):
    def __init__(self, master, store, edit_callback=None):
        super().__init__(master, fg_color="transparent")
        self.store = store
        self.edit_callback = edit_callback
        self._current_alias: str | None = None

        # Header
        self.header = ctk.CTkLabel(self, text="No server selected", font=ctk.CTkFont(size=20, weight="bold"))
        self.header.pack(padx=20, pady=(20, 10))

        # Info card
        self.card = ctk.CTkFrame(self)
        self.card.pack(fill="x", padx=20, pady=10)

        self._fields: dict[str, ctk.CTkLabel] = {}
        for label in ["Alias", "IP", "Port", "User", "Type", "Notes", "Status"]:
            row = ctk.CTkFrame(self.card, fg_color="transparent")
            row.pack(fill="x", padx=15, pady=4)
            ctk.CTkLabel(row, text=f"{label}:", width=80, anchor="w",
                        font=ctk.CTkFont(size=12), text_color="#9ca3af").pack(side="left")
            val = ctk.CTkLabel(row, text="-", anchor="w", font=ctk.CTkFont(size=13))
            val.pack(side="left", fill="x", expand=True)
            self._fields[label] = val

        # Edit button
        self.edit_btn = ctk.CTkButton(self, text="Edit Server", command=self._on_edit)
        self.edit_btn.pack(pady=15)

    def set_server(self, alias: str | None):
        self._current_alias = alias
        self.refresh()

    def refresh(self):
        if not self._current_alias:
            self.header.configure(text="No server selected")
            for v in self._fields.values():
                v.configure(text="-")
            return

        server = self.store.get_server(self._current_alias)
        if not server:
            return

        self.header.configure(text=server["alias"])
        self._fields["Alias"].configure(text=server.get("alias", "-"))
        self._fields["IP"].configure(text=server.get("ip", "-"))
        self._fields["Port"].configure(text=str(server.get("port", 22)))
        self._fields["User"].configure(text=server.get("user", "root"))
        self._fields["Type"].configure(text=server.get("type", "ssh").upper())
        self._fields["Notes"].configure(text=server.get("notes", "-") or "-")

        status = self.store.get_status(self._current_alias)
        color = {"online": "#22c55e", "offline": "#ef4444"}.get(status, "#9ca3af")
        self._fields["Status"].configure(text=status.upper(), text_color=color)

    def _on_edit(self):
        if self.edit_callback and self._current_alias:
            self.edit_callback(self._current_alias)
