"""
RShake-Tools — Main application window.

Modern tabbed Tkinter interface with a log panel and dark/light theme toggle.
"""

import logging
import tkinter as tk
from tkinter import ttk

from rshaketools.gui.tab_acquisition import AcquisitionTab
from rshaketools.gui.tab_msd_merge import MsdMergeTab
from rshaketools.gui.tab_precondition import PreconditionTab
from rshaketools.gui.tab_viewer import ViewerTab

logger = logging.getLogger("rshaketools")

# ── Colour palette ──────────────────────────────────────────────────────────
DARK = {
    "bg": "#1e1e2e",
    "fg": "#cdd6f4",
    "accent": "#89b4fa",
    "entry_bg": "#313244",
    "entry_fg": "#cdd6f4",
    "button_bg": "#585b70",
    "button_fg": "#cdd6f4",
    "tab_bg": "#181825",
    "log_bg": "#11111b",
    "log_fg": "#a6e3a1",
    "border": "#45475a",
    "heading": "#f5c2e7",
}

LIGHT = {
    "bg": "#eff1f5",
    "fg": "#4c4f69",
    "accent": "#1e66f5",
    "entry_bg": "#ffffff",
    "entry_fg": "#4c4f69",
    "button_bg": "#dce0e8",
    "button_fg": "#4c4f69",
    "tab_bg": "#e6e9ef",
    "log_bg": "#ffffff",
    "log_fg": "#40a02b",
    "border": "#ccd0da",
    "heading": "#8839ef",
}


class _TextHandler(logging.Handler):
    """Logging handler that writes to a Tkinter Text widget."""

    def __init__(self, text_widget: tk.Text):
        super().__init__()
        self.text_widget = text_widget

    def emit(self, record):
        msg = self.format(record) + "\n"
        self.text_widget.configure(state="normal")
        self.text_widget.insert(tk.END, msg)
        self.text_widget.see(tk.END)
        self.text_widget.configure(state="disabled")


class RShakeApp(tk.Tk):
    """Main application window."""

    def __init__(self):
        super().__init__()
        self.title("RShake-Tools  —  Raspberry Shake Data Toolkit")
        self.geometry("960x700")
        self.minsize(800, 600)

        # Theme state
        self._dark = True
        self.colors = DARK.copy()

        # Build UI
        self._build_header()
        self._build_notebook()
        self._build_log_panel()

        # Attach logging
        self._setup_logging()

        # Apply initial theme
        self._apply_theme()

        logger.info("RShake-Tools v0.1.0 started")

    # ── Header ──────────────────────────────────────────────────────────────
    def _build_header(self):
        self.header = tk.Frame(self)
        self.header.pack(fill=tk.X, padx=0, pady=0)

        self.title_label = tk.Label(
            self.header,
            text="🌍  RShake-Tools",
            font=("Helvetica", 16, "bold"),
            anchor="w",
        )
        self.title_label.pack(side=tk.LEFT, padx=16, pady=10)

        self.theme_btn = tk.Button(
            self.header,
            text="☀️  Light",
            command=self._toggle_theme,
            relief="flat",
            font=("Helvetica", 10),
            cursor="hand2",
            bd=0,
            padx=12,
            pady=4,
        )
        self.theme_btn.pack(side=tk.RIGHT, padx=16, pady=10)

    # ── Notebook (tabs) ─────────────────────────────────────────────────────
    def _build_notebook(self):
        style = ttk.Style(self)
        style.theme_use("clam")

        self.notebook = ttk.Notebook(self)
        self.notebook.pack(fill=tk.BOTH, expand=True, padx=8, pady=(0, 4))

        self.tab_acq = AcquisitionTab(self.notebook, self)
        self.tab_msd = MsdMergeTab(self.notebook, self)
        self.tab_pre = PreconditionTab(self.notebook, self)
        self.tab_view = ViewerTab(self.notebook, self)

        self.notebook.add(self.tab_acq, text="  📡  Acquisition  ")
        self.notebook.add(self.tab_msd, text="  📦  MSD Merge  ")
        self.notebook.add(self.tab_pre, text="  🔧  Precondition  ")
        self.notebook.add(self.tab_view, text="  📊  Viewer  ")

    # ── Log panel ───────────────────────────────────────────────────────────
    def _build_log_panel(self):
        log_frame = tk.LabelFrame(self, text="  Log  ", font=("Helvetica", 10))
        log_frame.pack(fill=tk.X, padx=8, pady=(0, 8))

        self.log_text = tk.Text(
            log_frame,
            height=6,
            wrap=tk.WORD,
            font=("Menlo", 10),
            state="disabled",
            bd=0,
            padx=8,
            pady=4,
        )
        scrollbar = ttk.Scrollbar(log_frame, command=self.log_text.yview)
        self.log_text.configure(yscrollcommand=scrollbar.set)

        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.log_text.pack(fill=tk.BOTH, expand=True)

    # ── Logging setup ───────────────────────────────────────────────────────
    def _setup_logging(self):
        handler = _TextHandler(self.log_text)
        handler.setFormatter(
            logging.Formatter("%(asctime)s  %(levelname)-7s  %(message)s", "%H:%M:%S")
        )
        root_logger = logging.getLogger("rshaketools")
        root_logger.setLevel(logging.DEBUG)
        root_logger.addHandler(handler)

    # ── Theme toggle ────────────────────────────────────────────────────────
    def _toggle_theme(self):
        self._dark = not self._dark
        self.colors = DARK.copy() if self._dark else LIGHT.copy()
        self.theme_btn.configure(
            text="☀️  Light" if self._dark else "🌙  Dark"
        )
        self._apply_theme()

    def _apply_theme(self):
        c = self.colors
        self.configure(bg=c["bg"])
        self.header.configure(bg=c["bg"])
        self.title_label.configure(bg=c["bg"], fg=c["heading"])
        self.theme_btn.configure(bg=c["button_bg"], fg=c["button_fg"])

        # Log
        self.log_text.configure(bg=c["log_bg"], fg=c["log_fg"])

        # ttk style
        style = ttk.Style(self)
        style.configure("TNotebook", background=c["bg"])
        style.configure("TNotebook.Tab", background=c["tab_bg"], foreground=c["fg"],
                         padding=[14, 6])
        style.map("TNotebook.Tab",
                  background=[("selected", c["accent"])],
                  foreground=[("selected", "#ffffff" if self._dark else "#ffffff")])
        style.configure("TFrame", background=c["bg"])
        style.configure("TLabel", background=c["bg"], foreground=c["fg"])
        style.configure("TButton", background=c["button_bg"], foreground=c["button_fg"])
        style.configure("TLabelframe", background=c["bg"], foreground=c["fg"])
        style.configure("TLabelframe.Label", background=c["bg"], foreground=c["heading"])

        # Propagate to all tabs
        for tab in (self.tab_acq, self.tab_msd, self.tab_pre, self.tab_view):
            if hasattr(tab, "apply_theme"):
                tab.apply_theme(c)
