import tkinter as tk
from tkinter import filedialog
from typing import Callable, Optional

from ui import styles


class PathPanel(tk.LabelFrame):
    """Panel con dos selectores de ruta (origen o destino)."""

    def __init__(self, parent, title: str, **kwargs):
        super().__init__(
            parent,
            text=title,
            font=styles.FONT_HEADING,
            padx=8,
            pady=4,
            **kwargs,
        )

        self.columnconfigure(1, weight=1)

        self.path_esde = tk.StringVar()
        self.path_roms = tk.StringVar()

        self._add_selector(0, "ES-DE:", self.path_esde)
        self._add_selector(1, "ROMs:", self.path_roms)

    def _add_selector(self, row: int, label: str, var: tk.StringVar, callback: Optional[Callable] = None):
        tk.Label(
            self,
            text=label,
            width=8,
            anchor="w",
            font=styles.FONT_LABEL,
        ).grid(row=row, column=0, sticky="w", pady=2)

        tk.Entry(
            self,
            textvariable=var,
            font=styles.FONT_SMALL,
        ).grid(row=row, column=1, sticky="ew", padx=4, pady=2)

        tk.Button(
            self,
            text="Buscar",
            font=styles.FONT_SMALL,
            command=lambda: self._choose(var, callback),
        ).grid(row=row, column=2, sticky="e", pady=2)

    def _choose(self, var: tk.StringVar, callback: Optional[Callable]):
        path = filedialog.askdirectory()
        if not path:
            return
        var.set(path)
        if callback:
            callback(path)

    def set_roms_callback(self, callback: Callable[[str], None]) -> None:
        """Registra callback que se invoca al cambiar la ruta de ROMs."""
        for widget in self.winfo_children():
            widget.destroy()
        self._add_selector(0, "ES-DE:", self.path_esde)
        self._add_selector(1, "ROMs:", self.path_roms, callback=callback)

    def get_esde(self) -> str:
        return self.path_esde.get()

    def get_roms(self) -> str:
        return self.path_roms.get()

    def set_esde(self, value: str) -> None:
        self.path_esde.set(value)

    def set_roms(self, value: str) -> None:
        self.path_roms.set(value)
