import os
import tkinter as tk
from tkinter import messagebox
from typing import List

from ui import styles


class SystemList(tk.Frame):
    """Listbox de sistemas con botones Select All / Select None."""

    def __init__(self, parent, **kwargs):
        super().__init__(parent, **kwargs)

        tk.Label(
            self,
            text="Sistemas encontrados en ROMs:",
            font=styles.FONT_LABEL,
        ).pack(pady=(6, 2))

        self.listbox = tk.Listbox(self, selectmode=tk.MULTIPLE, height=10, font=styles.FONT_SMALL)
        self.listbox.pack(fill="both", expand=True, padx=styles.PAD_X)

        btn_frame = tk.Frame(self)
        btn_frame.pack(fill="x", padx=styles.PAD_X, pady=2)

        tk.Button(
            btn_frame,
            text="Seleccionar todo",
            font=styles.FONT_SMALL,
            command=self._select_all,
        ).pack(side="left", padx=2)

        tk.Button(
            btn_frame,
            text="Quitar selección",
            font=styles.FONT_SMALL,
            command=self._select_none,
        ).pack(side="left", padx=2)

    def _select_all(self):
        self.listbox.selection_set(0, tk.END)

    def _select_none(self):
        self.listbox.selection_clear(0, tk.END)

    def populate(self, path: str) -> None:
        """Rellena el listbox con los subdirectorios de path."""
        self.listbox.delete(0, tk.END)
        if not os.path.isdir(path):
            return
        try:
            dirs = sorted(
                d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))
            )
            for d in dirs:
                self.listbox.insert(tk.END, d)
        except Exception as e:
            messagebox.showerror("Error", f"No se pudo leer la ruta:\n{e}")

    def get_selected(self) -> List[str]:
        return [self.listbox.get(i) for i in self.listbox.curselection()]

    def set_selected(self, names: List[str]) -> None:
        selected = set(names)
        self.listbox.selection_clear(0, tk.END)
        for i in range(self.listbox.size()):
            if self.listbox.get(i) in selected:
                self.listbox.selection_set(i)
