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=styles.PAD_X,
            pady=styles.PAD_Y,
            **kwargs,
        )

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

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

    def _add_selector(self, label: str, var: tk.StringVar, callback: Optional[Callable] = None):
        frame = tk.Frame(self)
        frame.pack(fill="x", pady=2)

        tk.Label(frame, text=label, width=10, anchor="w", font=styles.FONT_LABEL).pack(side="left")
        tk.Entry(frame, textvariable=var, width=55, font=styles.FONT_SMALL).pack(side="left", padx=4)
        tk.Button(
            frame,
            text="Buscar",
            font=styles.FONT_SMALL,
            command=lambda: self._choose(var, callback),
        ).pack(side="left")

    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."""
        # Reemplaza el selector de ROMs con uno que tenga el callback
        for widget in self.winfo_children():
            widget.destroy()
        self._add_selector("ES-DE:", self.path_esde)
        self._add_selector("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)
