import ttkbootstrap as ttk

from ..controller import Controller
from ..geometry import geometry
from ..defaults import LANGUAGES


class SettingsTab(ttk.Frame):
    def __init__(self, app):
        self.app = app
        self.c: Controller = self.app.c

        super().__init__(
            self.app.notebook,
            padding=(geometry.whp(4), geometry.whp(4)),
        )

        self.create_widgets()

    def apply_settings(self) -> None:
        self.c.apply_settings("speech")

        self.quality_scale.set(self.c.quality_var.get())
        self.speed_scale.set(self.c.speed_var.get())
        self.lang_combo.set(self.c.lang_var.get())

    def create_widgets(self):
        parent = self

        parent.columnconfigure(0, weight=0)
        parent.columnconfigure(1, weight=1)

        row = 0

        ttk.Label(
            parent,
            text="Language",
        ).grid(row=row, column=0, sticky="w", padx=(0, 20), pady=10)

        language_frame = ttk.Frame(parent)
        language_frame.grid(row=row, column=1, sticky="w")

        self.lang_combo = ttk.Combobox(
            language_frame,
            state="readonly",
            width=20,
            textvariable=self.c.lang_var,
            values=list(LANGUAGES.keys()),
            style="EntryLike.TCombobox",
        )
        self.lang_combo.grid(row=0, column=0, sticky="w")

        def on_lang_selected(event):
            event.widget.selection_clear()

        self.lang_combo.bind("<<ComboboxSelected>>", on_lang_selected)

        row += 1

        ttk.Label(
            parent,
            text="Voice",
        ).grid(row=row, column=0, sticky="w", padx=(0, 20), pady=10)

        voice_frame = ttk.Frame(parent)
        voice_frame.grid(row=row, column=1, sticky="w")

        for col, v in enumerate(["M1", "M2", "M3", "M4", "M5"]):
            ttk.Radiobutton(
                voice_frame,
                text=v,
                value=v,
                variable=self.c.voice_var,
            ).grid(row=0, column=col, padx=geometry.whp(2), sticky="w")

        for col, v in enumerate(["F1", "F2", "F3", "F4", "F5"]):
            ttk.Radiobutton(
                voice_frame,
                text=v,
                value=v,
                variable=self.c.voice_var,
            ).grid(
                row=1,
                column=col,
                padx=geometry.whp(2),
                pady=(geometry.whp(4), 0),
                sticky="w",
            )

        row += 1

        ttk.Label(
            parent,
            text="Quality",
        ).grid(row=row, column=0, sticky="w", padx=(0, 20), pady=10)

        quality_frame = ttk.Frame(parent)
        quality_frame.grid(row=row, column=1, sticky="ew")
        quality_frame.columnconfigure(0, weight=1)

        def on_quality_change(value):
            quality = max(5, min(12, round(float(value))))
            self.c.quality_var.set(quality)

            if hasattr(self, "quality_scale"):
                current = float(self.quality_scale.get())
                if current != quality:
                    self.quality_scale.set(quality)

        self.quality_scale = ttk.Scale(
            quality_frame,
            from_=5,
            to=12,
            orient="horizontal",
            command=on_quality_change,
        )
        self.quality_scale.set(self.c.quality_var.get())
        self.quality_scale.grid(row=0, column=0, sticky="ew")

        ttk.Label(
            quality_frame,
            textvariable=self.c.quality_var,
            width=3,
        ).grid(row=0, column=1, padx=(10, 0))

        row += 1

        ttk.Label(
            parent,
            text="Speed",
        ).grid(row=row, column=0, sticky="w", padx=(0, 20), pady=10)

        speed_frame = ttk.Frame(parent)
        speed_frame.grid(row=row, column=1, sticky="ew")
        speed_frame.columnconfigure(0, weight=1)

        def on_speed_change(value):
            self.c.speed_var.set(round(float(value), 2))

        self.speed_scale = ttk.Scale(
            speed_frame,
            from_=0.7,
            to=2.0,
            orient="horizontal",
            command=on_speed_change,
        )
        self.speed_scale.set(self.c.speed_var.get())
        self.speed_scale.grid(row=0, column=0, sticky="ew")

        ttk.Label(
            speed_frame,
            textvariable=self.c.speed_var,
            width=5,
        ).grid(row=0, column=1, padx=(10, 0))

        row += 1

        ttk.Label(
            parent,
            text="Output format",
        ).grid(row=row, column=0, sticky="w", padx=(0, 20), pady=10)

        format_frame = ttk.Frame(parent)
        format_frame.grid(row=row, column=1, sticky="w")

        for col, fmt in enumerate([".wav", ".mp3", ".ogg"]):
            ttk.Radiobutton(
                format_frame,
                text=fmt,
                value=fmt,
                variable=self.c.output_format_var,
            ).grid(
                row=0,
                column=col,
                padx=(0, geometry.whp(6)),
                sticky="w",
            )

        row += 1

        buttons_frame = ttk.Frame(parent)
        buttons_frame.grid(row=row, column=0, sticky="w", pady=(20, 0))

        btn_width = 10

        save_btn = ttk.Button(
            buttons_frame,
            text="Save",
            width=btn_width,
            padding=(0, geometry.whp(1)),
            command=self.c.save_speech_settings,
        )
        save_btn.grid(row=0, column=0, padx=(0, geometry.whp(4)))

        reset_btn = ttk.Button(
            buttons_frame,
            text="Reset",
            width=btn_width,
            padding=(0, geometry.whp(1)),
            bootstyle="outline",
            command=self.apply_settings,
        )
        reset_btn.grid(row=0, column=1)

        for i in range(row):
            parent.grid_rowconfigure(i, pad=geometry.whp(3))
