from __future__ import annotations

from collections import Counter
from typing import Optional

import tkinter as tk
from tkinter import ttk, scrolledtext

from ...model import ScanResult
from ...logging_config import get_logger

LOGGER = get_logger("gui.history")


class HistorySection:
    """Gestion du panneau historique de la GUI."""

    def __init__(self, gui: "ModernWebSentinelGUI") -> None:
        self.gui = gui

    # ------------------------------------------------------------------
    # Construction de l'onglet
    # ------------------------------------------------------------------
    def build_tab(self) -> None:
        gui = self.gui
        notebook = getattr(gui, "notebook")

        gui.reports_tab = ttk.Frame(notebook)
        notebook.add(gui.reports_tab, text=gui._text("tab_reports_history"))

        main_frame = ttk.Frame(gui.reports_tab, style="Modern.TFrame", padding=20)
        main_frame.pack(fill=tk.BOTH, expand=True)

        gui.history_title_label = ttk.Label(main_frame, style="Title.TLabel")
        gui.history_title_label.pack(anchor=tk.W, pady=(0, 20))
        gui._register_widget(gui.history_title_label, "history_title")

        table_frame = ttk.Frame(main_frame, style="Modern.TFrame")
        table_frame.pack(fill=tk.BOTH, expand=True)
        table_frame.columnconfigure(0, weight=1)
        table_frame.rowconfigure(0, weight=1)

        columns = ("type", "target", "summary", "timestamp")
        gui.history_tree = ttk.Treeview(table_frame, columns=columns, show="headings", height=12)
        gui.history_tree.heading("type", text=gui._text("history_column_type"))
        gui.history_tree.heading("target", text=gui._text("history_column_target"))
        gui.history_tree.heading("summary", text=gui._text("history_column_summary"))
        gui.history_tree.heading("timestamp", text=gui._text("history_column_date"))

        gui.history_tree.column("type", width=90, stretch=False)
        gui.history_tree.column("target", width=220)
        gui.history_tree.column("summary", width=360)
        gui.history_tree.column("timestamp", width=160, stretch=False)

        tree_scroll = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=gui.history_tree.yview)
        gui.history_tree.configure(yscrollcommand=tree_scroll.set)

        gui.history_tree.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))
        tree_scroll.grid(row=0, column=1, sticky=(tk.N, tk.S))

        gui.history_detail_frame = ttk.LabelFrame(main_frame, padding=15)
        gui.history_detail_frame.pack(fill=tk.BOTH, expand=True, pady=(20, 0))
        gui.history_detail_frame.columnconfigure(0, weight=1)
        gui.history_detail_frame.rowconfigure(0, weight=1)
        gui._register_widget(gui.history_detail_frame, "history_detail_frame")

        gui.history_detail_text = tk.Text(
            gui.history_detail_frame,
            wrap=tk.WORD,
            font=("Consolas", 10),
            height=10,
            state=tk.DISABLED,
        )
        gui.history_detail_text.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.E, tk.W))

        gui.history_tree.bind("<<TreeviewSelect>>", gui._on_history_select)
        gui.refresh_history_tab()
        return gui.reports_tab

    # ------------------------------------------------------------------
    # Rafraîchir la table
    # ------------------------------------------------------------------
    def refresh(self) -> None:
        gui = self.gui
        history_tree = getattr(gui, "history_tree", None)
        if history_tree is None:
            return

        for item in history_tree.get_children():
            history_tree.delete(item)
        gui.history_tree_data.clear()

        for result in reversed(getattr(gui, "history_entries", [])):
            counts = Counter(finding.severity for finding in result.findings)
            summary = gui._render_severity_overview(counts)
            scan_type = gui._determine_scan_type(result)
            target = gui._history_target_label(result)
            timestamp = result.generated_at.astimezone().strftime("%Y-%m-%d %H:%M")
            item_id = history_tree.insert("", "end", values=(scan_type, target, summary, timestamp))
            gui.history_tree_data[item_id] = result

        detail_widget = getattr(gui, "history_detail_text", None)
        if detail_widget is None:
            return

        detail_widget.config(state=tk.NORMAL)
        detail_widget.delete("1.0", tk.END)
        if gui.history_entries:
            detail_widget.insert(tk.END, gui._text("history_no_entries_prompt"))
        else:
            detail_widget.insert(tk.END, gui._text("history_no_entries"))
        detail_widget.config(state=tk.DISABLED)

    def on_select(self) -> None:
        gui = self.gui
        history_tree = getattr(gui, "history_tree", None)
        if history_tree is None:
            return
        selection = history_tree.selection()
        if not selection:
            return
        item_id = selection[0]
        result = gui.history_tree_data.get(item_id)
        self.show_detail(result)


    # ------------------------------------------------------------------
    # Sélection d’une ligne
    # ------------------------------------------------------------------
    def show_detail(self, result: Optional[ScanResult]) -> None:
        gui = self.gui
        detail_widget = getattr(gui, "history_detail_text", None)
        if detail_widget is None:
            return

        detail_widget.config(state=tk.NORMAL)
        detail_widget.delete("1.0", tk.END)
        if result is None:
            detail_widget.config(state=tk.DISABLED)
            return

        detail_text = gui._format_history_detail(result)
        detail_widget.insert(tk.END, detail_text)
        detail_widget.config(state=tk.DISABLED)
