import tkinter as tk
from tkinter import messagebox
from tkinter import colorchooser
import json
import os

def start(window, app_manager=None, **kwargs):
    frame = tk.Frame(window, bg="white")
    frame.pack(fill="both", expand=True, padx=10, pady=10)
    
    tk.Label(frame, text="Paramètres du Système", font=("Arial", 14, "bold"), bg="white").pack(pady=10)
    desktop = app_manager.desktop
    
    # --- THÈMES ---
    tk.Label(frame, text="Thème de l'interface :", font=("Arial", 12, "bold"), bg="white").pack(pady=5)
    
    import sys, os
    sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
    from core.theme import THEMES
    
    theme_var = tk.StringVar(value=desktop.settings.get("theme", "GrimOS"))
    theme_frame = tk.Frame(frame, bg="white")
    theme_frame.pack(fill="x", pady=5)
    
    theme_menu = tk.OptionMenu(theme_frame, theme_var, *THEMES.keys())
    theme_menu.pack(side="left", padx=5)
    
    def apply_theme_setting():
        desktop.settings["theme"] = theme_var.get()
        try:
            settings_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 
                "config", "settings.json"
            )
            with open(settings_path, "w", encoding="utf-8") as f:
                json.dump(desktop.settings, f, indent=4)
                
            desktop.restart_requested = True
            desktop.save_and_quit()
        except Exception as e:
            import traceback
            with open("/tmp/grimos_theme_error.txt", "w") as f:
                f.write(traceback.format_exc())
            messagebox.showerror("Erreur", f"Erreur détaillée sauvegardée dans /tmp/grimos_theme_error.txt\n{str(e)}")
            
    tk.Button(theme_frame, text=" Appliquer", image=(app_manager.desktop.icons.get("btn_apply") if app_manager else None), compound="left", command=apply_theme_setting).pack(side="left", padx=5)
        
    tk.Frame(frame, height=2, bg="black").pack(fill="x", pady=10)
    tk.Label(frame, text="Sécurité / Système :", font=("Arial", 12, "bold"), bg="white").pack(pady=5)
    
    sudo_frame = tk.Frame(frame, bg="white")
    sudo_frame.pack(fill="x", pady=2)
    tk.Label(sudo_frame, text="Mot de passe Sudo :", bg="white").pack(side="left", padx=5)
    
    sudo_entry = tk.Entry(sudo_frame, width=15)
    sudo_entry.pack(side="left", padx=5)
    sudo_entry.insert(0, desktop.settings.get("sudo_pwd", ""))
    
    def save_sudo():
        desktop.settings["sudo_pwd"] = sudo_entry.get()
        try:
            settings_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 
                "config", "settings.json"
            )
            with open(settings_path, "w", encoding="utf-8") as f:
                json.dump(desktop.settings, f, indent=4)
            messagebox.showinfo("Succès", "Mot de passe système (Sudo) enregistré avec succès.")
        except Exception as e:
            messagebox.showerror("Erreur", str(e))
            
    tk.Button(sudo_frame, text=" Enregistrer", image=(app_manager.desktop.icons.get("menu_save") if app_manager else None), compound="left", command=save_sudo).pack(side="left", padx=5)
    
    cpu_frame = tk.Frame(frame, bg="white")
    cpu_frame.pack(fill="x", pady=2)
    tk.Label(cpu_frame, text="Largeur Graphique CPU :", bg="white").pack(side="left", padx=5)
    
    cpu_entry = tk.Entry(cpu_frame, width=5)
    cpu_entry.pack(side="left", padx=5)
    cpu_entry.insert(0, str(desktop.settings.get("cpu_graph_width", 10)))
    
    def save_cpu_width():
        try:
            val = int(cpu_entry.get())
            if val < 1 or val > 50:
                raise ValueError("La valeur doit être entre 1 et 50.")
            desktop.settings["cpu_graph_width"] = val
            settings_path = os.path.join(
                os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))), 
                "config", "settings.json"
            )
            with open(settings_path, "w", encoding="utf-8") as f:
                json.dump(desktop.settings, f, indent=4)
            messagebox.showinfo("Succès", "Largeur du graphique CPU enregistrée.\nL'effet sera immédiat sur la barre des tâches.")
        except Exception as e:
            messagebox.showerror("Erreur", str(e))
            
    tk.Button(cpu_frame, text=" Enregistrer", image=(app_manager.desktop.icons.get("menu_save") if app_manager else None), compound="left", command=save_cpu_width).pack(side="left", padx=5)
