"""
Viewer tab — Load and visualise MiniSEED waveforms with metadata display.
"""

import logging
import tkinter as tk
from tkinter import ttk, filedialog, messagebox

import obspy
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure

from rshaketools.plotting import plot_stream, get_stream_info
from rshaketools.gui.helpers import section_frame

logger = logging.getLogger("rshaketools")


class ViewerTab(ttk.Frame):
    def __init__(self, parent, app):
        super().__init__(parent)
        self.app = app
        self.stream = None
        self._build()

    def _build(self):
        # ── Toolbar ─────────────────────────────────────────────────────────
        toolbar = ttk.Frame(self)
        toolbar.pack(fill=tk.X, padx=12, pady=(10, 0))

        ttk.Button(toolbar, text="  📂  Open File  ", command=self._open_file).pack(side=tk.LEFT)
        self.file_label = ttk.Label(toolbar, text="No file loaded", font=("Helvetica", 10))
        self.file_label.pack(side=tk.LEFT, padx=12)

        # ── Matplotlib canvas ───────────────────────────────────────────────
        self.fig = Figure(figsize=(9, 4), dpi=100)
        self.fig.patch.set_facecolor("#1e1e2e")
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True, padx=8, pady=4)

        nav_frame = ttk.Frame(self)
        nav_frame.pack(fill=tk.X, padx=8)
        self.nav_toolbar = NavigationToolbar2Tk(self.canvas, nav_frame)
        self.nav_toolbar.update()

        # ── Metadata pane ──────────────────────────────────────────────────
        self.meta_frame = section_frame(self, "ℹ️  Metadata")
        self.meta_text = tk.Text(
            self.meta_frame,
            height=5,
            wrap=tk.WORD,
            font=("Menlo", 10),
            state="disabled",
            bd=0,
            padx=8,
            pady=4,
        )
        self.meta_text.pack(fill=tk.BOTH, expand=True)

    # ── Actions ─────────────────────────────────────────────────────────────
    def _open_file(self):
        path = filedialog.askopenfilename(
            filetypes=[
                ("MiniSEED", "*.mseed"),
                ("MSD", "*.msd"),
                ("SAC", "*.sac"),
                ("All files", "*.*"),
            ]
        )
        if not path:
            return

        try:
            self.stream = obspy.read(path)
            logger.info("Loaded %s — %d trace(s)", path, len(self.stream))
            self.file_label.configure(text=path.split("/")[-1])
        except Exception as exc:
            logger.error("Failed to load %s: %s", path, exc)
            messagebox.showerror("Load Error", str(exc))
            return

        # Plot
        bg = self.app.colors["bg"]
        fg = self.app.colors["fg"]
        self.fig.patch.set_facecolor(bg)
        plot_stream(self.stream, fig=self.fig, title=path.split("/")[-1])
        for ax in self.fig.get_axes():
            ax.set_facecolor(bg)
            ax.tick_params(colors=fg)
            ax.xaxis.label.set_color(fg)
            ax.yaxis.label.set_color(fg)
            for spine in ax.spines.values():
                spine.set_color(fg)
            ax.title.set_color(fg)
        if self.fig._suptitle:
            self.fig._suptitle.set_color(fg)
        self.canvas.draw()

        # Metadata
        info_list = get_stream_info(self.stream)
        lines = []
        for info in info_list:
            lines.append(
                f"{info['network']}.{info['station']}.{info['location']}.{info['channel']}  "
                f"| {info['starttime']}  →  {info['endtime']}  "
                f"| {info['sampling_rate']} Hz  | {info['npts']} pts  | {info['duration_s']}s"
            )

        self.meta_text.configure(state="normal")
        self.meta_text.delete("1.0", tk.END)
        self.meta_text.insert(tk.END, "\n".join(lines))
        self.meta_text.configure(state="disabled")

    def apply_theme(self, c):
        self.meta_text.configure(bg=c["log_bg"], fg=c["log_fg"])
        self.fig.patch.set_facecolor(c["bg"])
        if self.stream:
            for ax in self.fig.get_axes():
                ax.set_facecolor(c["bg"])
                ax.tick_params(colors=c["fg"])
                for spine in ax.spines.values():
                    spine.set_color(c["fg"])
            if self.fig._suptitle:
                self.fig._suptitle.set_color(c["fg"])
            self.canvas.draw()
