"""
Modal d'avertissement pour les tests invasifs
Affichage d'un avertissement de sécurité avant d'activer les tests d'injection invasifs
"""

import tkinter as tk
from tkinter import ttk
from .i18n import localization


class InvasiveWarningModal:
    """Modal d'avertissement pour les tests invasifs."""
    
    def __init__(self, parent):
        self.parent = parent
        self.result = False
        self.window = None
        self.confirm_var = None
    
    def show(self) -> bool:
        """
        Affiche la modal d'avertissement et retourne True si l'utilisateur confirme.
        """
        self.window = tk.Toplevel(self.parent)
        self.window.title(localization.t("invasive_warning_title"))
        self.window.geometry("650x580")
        self.window.resizable(True, True)
        
        # Modal (bloquer interaction avec la fenêtre parent)
        self.window.transient(self.parent)
        self.window.grab_set()
        
        # Centrer la fenêtre
        self.window.update_idletasks()
        x = (self.window.winfo_screenwidth() // 2) - (650 // 2)
        y = (self.window.winfo_screenheight() // 2) - (580 // 2)
        self.window.geometry(f"650x580+{x}+{y}")
        
        # Icône d'avertissement dans la barre de titre
        try:
            self.window.iconbitmap(default="")  # Supprime l'icône par défaut
        except:
            pass  # Ignore si pas possible
        
        self._create_widgets()
        
        # Attendre que la modal soit fermée
        self.parent.wait_window(self.window)
        
        return self.result
    
    def _create_widgets(self):
        """Créer les widgets de la modal."""
        
        # Frame principal avec padding
        main_frame = ttk.Frame(self.window, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # Titre avec icône d'avertissement
        title_frame = ttk.Frame(main_frame)
        title_frame.pack(fill=tk.X, pady=(0, 20))
        
        title_label = ttk.Label(title_frame, 
                               text=localization.t("invasive_warning_title"),
                               font=("Arial", 14, "bold"),
                               foreground="red")
        title_label.pack(anchor="center")
        
        # Zone de message avec scrollbar
        message_frame = ttk.Frame(main_frame)
        message_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 20))
        
        # Créer un Text widget pour le message avec scrollbar
        text_widget = tk.Text(message_frame, 
                             wrap=tk.WORD,
                             font=("Arial", 10),
                             height=20,
                             width=80,
                             padx=15,
                             pady=15,
                             bg="#fff8dc",  # Couleur de fond légèrement jaune (avertissement)
                             relief=tk.SOLID,
                             borderwidth=1)
        
        scrollbar = ttk.Scrollbar(message_frame, orient=tk.VERTICAL, command=text_widget.yview)
        text_widget.configure(yscrollcommand=scrollbar.set)
        
        # Insérer le message
        text_widget.insert(tk.END, localization.t("invasive_warning_message"))
        text_widget.config(state=tk.DISABLED)  # Lecture seule
        
        # Positionner le texte et scrollbar
        text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        
        # Frame de confirmation
        confirm_frame = ttk.Frame(main_frame)
        confirm_frame.pack(fill=tk.X, pady=(0, 15))
        
        self.confirm_var = tk.BooleanVar()
        confirm_check = ttk.Checkbutton(confirm_frame,
                                       text=localization.t("invasive_checkbox_confirm"),
                                       variable=self.confirm_var,
                                       command=self._on_confirm_change)
        confirm_check.pack(anchor="w")
        
        # Frame des boutons
        buttons_frame = ttk.Frame(main_frame)
        buttons_frame.pack(fill=tk.X)
        
        # Bouton Annuler
        cancel_btn = ttk.Button(buttons_frame,
                               text=localization.t("invasive_btn_cancel"),
                               command=self._on_cancel,
                               style="Cancel.TButton")
        cancel_btn.pack(side=tk.RIGHT, padx=(10, 0))
        
        # Bouton Continuer (désactivé au début)
        self.continue_btn = ttk.Button(buttons_frame,
                                      text=localization.t("invasive_btn_continue"),
                                      command=self._on_continue,
                                      state=tk.DISABLED,
                                      style="Accept.TButton")
        self.continue_btn.pack(side=tk.RIGHT)
        
        # Configurer les styles des boutons
        self._setup_button_styles()
        
        # Focus sur la modal
        self.window.focus_set()
        
        # Gérer la fermeture de la fenêtre
        self.window.protocol("WM_DELETE_WINDOW", self._on_cancel)
        
        # Raccourcis clavier
        self.window.bind("<Escape>", lambda e: self._on_cancel())
        self.window.bind("<Return>", self._on_enter_pressed)
    
    def _setup_button_styles(self):
        """Configurer les styles personnalisés pour les boutons."""
        style = ttk.Style()
        
        # Style pour le bouton Annuler (rouge)
        style.configure("Cancel.TButton",
                       foreground="darkred",
                       font=("Arial", 10, "bold"))
        
        # Style pour le bouton Continuer (vert)
        style.configure("Accept.TButton",
                       foreground="darkgreen",
                       font=("Arial", 10, "bold"))
    
    def _on_confirm_change(self):
        """Gérer le changement de la case de confirmation."""
        if self.confirm_var.get():
            self.continue_btn.config(state=tk.NORMAL)
        else:
            self.continue_btn.config(state=tk.DISABLED)
    
    def _on_continue(self):
        """L'utilisateur confirme et veut continuer."""
        self.result = True
        self.window.destroy()
    
    def _on_cancel(self):
        """L'utilisateur annule."""
        self.result = False
        self.window.destroy()
    
    def _on_enter_pressed(self, event):
        """Gérer la touche Entrée."""
        if self.confirm_var.get():
            self._on_continue()


def show_invasive_warning(parent) -> bool:
    """
    Fonction utilitaire pour afficher la modal d'avertissement.
    
    Args:
        parent: Fenêtre parente
        
    Returns:
        bool: True si l'utilisateur confirme, False sinon
    """
    modal = InvasiveWarningModal(parent)
    return modal.show()