"""
Applique des thèmes de couleur au GUI existant
Au lieu de créer des GUI séparés, on applique juste des palettes de couleurs
"""

from __future__ import annotations

import tkinter as tk
from tkinter import ttk

from .themes import ThemeManager


class ThemeApplicator:
    """Applique des thèmes de couleur au GUI existant."""

    THEME_ALIASES = {
        "classic": "default",
        "minimal": "default",
    }

    @classmethod
    def apply_theme(cls, root: tk.Tk, theme_name: str = "classic"):
        """Applique un thème au widget root et tous ses enfants."""
        normalized, colors = cls._resolve_theme(theme_name)

        # Configurer le root
        root.configure(bg=colors["bg_primary"])

        # Appliquer récursivement aux enfants
        cls._apply_to_widget(root, colors)

        # Configurer les styles ttk
        style = ttk.Style()

        # Style des frames
        style.configure(
            "Modern.TFrame",
            background=colors["bg_secondary"],
            bordercolor=colors["border"],
        )

        # Style des labels
        style.configure(
            "Modern.TLabel",
            background=colors["bg_secondary"],
            foreground=colors["text_secondary"],
        )

        style.configure(
            "Title.TLabel",
            background=colors["bg_secondary"],
            foreground=colors["text_primary"],
        )

        # Style des boutons
        style.configure(
            "Modern.TButton",
            background=colors["accent"],
            foreground=colors["text_primary"],
        )

        # Style des onglets
        style.configure(
            "Modern.TNotebook",
            background=colors["bg_secondary"],
            bordercolor=colors["border"],
        )

        style.configure(
            "Modern.TNotebook.Tab",
            background=colors["bg_secondary"],
            foreground=colors["text_secondary"],
        )

        style.map(
            "Modern.TNotebook.Tab",
            background=[("selected", colors["accent"])],
            foreground=[("selected", colors["text_primary"])],
        )

    @classmethod
    def _resolve_theme(cls, theme_name: str) -> tuple[str, dict[str, str]]:
        normalized = cls.THEME_ALIASES.get(theme_name.lower(), theme_name.lower())
        theme = ThemeManager.get_theme(normalized)
        if theme is None:
            normalized = "default"
            theme = ThemeManager.get_theme(normalized)
        if theme is None:
            palette = {
                "bg_primary": "#f8fafc",
                "bg_secondary": "#ffffff",
                "text_primary": "#1f2937",
                "text_secondary": "#6b7280",
                "accent": "#2563eb",
                "border": "#e5e7eb",
            }
            return normalized, palette
        colors = theme.colors
        palette = {
            "bg_primary": colors.bg_primary,
            "bg_secondary": colors.bg_secondary,
            "text_primary": colors.fg_primary,
            "text_secondary": colors.fg_secondary,
            "accent": colors.bg_accent,
            "border": colors.border,
        }
        return normalized, palette

    @classmethod
    def _apply_to_widget(cls, widget, colors):
        """Applique les couleurs à un widget et ses enfants récursivement."""
        try:
            # Widgets tk standard
            if isinstance(widget, (tk.Frame, tk.LabelFrame)):
                widget.configure(bg=colors["bg_secondary"])
            elif isinstance(widget, tk.Label):
                widget.configure(
                    bg=colors["bg_secondary"], fg=colors["text_secondary"]
                )
            elif isinstance(widget, tk.Button):
                widget.configure(
                    bg=colors["accent"],
                    fg=colors["text_primary"],
                    activebackground=colors["accent"],
                    activeforeground=colors["text_primary"],
                )
            elif isinstance(widget, (tk.Text, tk.Entry)):
                widget.configure(
                    bg=colors["bg_primary"],
                    fg=colors["text_primary"],
                    insertbackground=colors["text_primary"],
                )
            elif isinstance(widget, tk.Listbox):
                widget.configure(
                    bg=colors["bg_primary"],
                    fg=colors["text_primary"],
                    selectbackground=colors["accent"],
                    selectforeground=colors["text_primary"],
                )
        except tk.TclError:
            pass  # Certaines propriétés peuvent ne pas être supportées

        # Appliquer récursivement aux enfants
        try:
            for child in widget.winfo_children():
                cls._apply_to_widget(child, colors)
        except Exception:
            pass
