"""Settings screen — API keys, model, language, preferences, AI behaviour."""

from __future__ import annotations

from typing import TYPE_CHECKING

import flet as ft

if TYPE_CHECKING:
    from meeting_helper.config import Config

TEAL = "#4ec9b0"


class SettingsScreen(ft.Column):
    """API keys, model selection, and other preferences."""

    def __init__(self, page: ft.Page, config: "Config"):
        super().__init__(
            expand=True,
            scroll=ft.ScrollMode.AUTO,
            spacing=20,
            horizontal_alignment=ft.CrossAxisAlignment.STRETCH,
        )
        self._page = page
        self._config = config

        # --- API Keys ---
        self._anthropic_key = ft.TextField(
            label="Anthropic API Key",
            password=True,
            can_reveal_password=True,
            hint_text="sk-ant-...",
            value=config.anthropic_api_key,
            border_radius=8,
        )
        self._deepgram_key = ft.TextField(
            label="Deepgram API Key",
            password=True,
            can_reveal_password=True,
            hint_text="Deepgram API key (optional — falls back to local Whisper)",
            value=config.deepgram_api_key,
            border_radius=8,
        )

        api_card = ft.Card(
            content=ft.Container(
                content=ft.Column([
                    ft.Text("API Keys", size=14, weight=ft.FontWeight.W_600),
                    self._anthropic_key,
                    self._deepgram_key,
                ], spacing=12),
                padding=20,
            ),
        )

        # --- Preferences ---
        self._theme_dropdown = ft.Dropdown(
            label="Theme",
            value=config._data.get("gui_theme", "system"),
            options=[ft.dropdown.Option(t) for t in ["system", "dark", "light"]],
            width=200,
            border_radius=8,
            on_select=self._on_theme_change,
        )

        self._model_dropdown = ft.Dropdown(
            label="Claude Model",
            value=config._data.get("claude_model", "sonnet"),
            options=[ft.dropdown.Option(m) for m in ["sonnet", "opus", "haiku"]],
            width=200,
            border_radius=8,
        )

        self._lang_dropdown = ft.Dropdown(
            label="Transcription Language",
            value=config.transcription_language,
            options=[ft.dropdown.Option(lang) for lang in
                     ["en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh", "auto"]],
            width=200,
            border_radius=8,
        )

        self._sw_label = ft.Text(str(config.sentence_window), size=13, width=40)
        self._sw_slider = ft.Slider(
            min=1, max=10, divisions=9,
            value=config.sentence_window,
            label="{value}",
            active_color=TEAL,
            on_change=lambda e: self._update_slider_label(e, self._sw_label),
            width=250,
        )

        self._st_label = ft.Text(str(config.silence_timeout), size=13, width=40)
        self._st_slider = ft.Slider(
            min=10, max=120, divisions=22,
            value=config.silence_timeout,
            label="{value}",
            active_color=TEAL,
            on_change=lambda e: self._update_slider_label(e, self._st_label),
            width=250,
        )

        # File picker for recordings dir — uses async get_directory_path
        self._file_picker = ft.FilePicker()
        page.services.append(self._file_picker)

        self._rec_input = ft.TextField(
            label="Recordings Directory",
            value=str(config.recordings_dir),
            border_radius=8,
            expand=True,
        )
        browse_btn = ft.OutlinedButton(
            "Browse",
            icon=ft.Icons.FOLDER_OPEN,
            on_click=self._browse_recordings,
        )

        prefs_card = ft.Card(
            content=ft.Container(
                content=ft.Column([
                    ft.Text("Preferences", size=14, weight=ft.FontWeight.W_600),
                    ft.Row([self._theme_dropdown, self._model_dropdown, self._lang_dropdown], spacing=20),
                    ft.Row([
                        ft.Text("Sentence Window", size=13, width=180),
                        self._sw_slider,
                        self._sw_label,
                    ], vertical_alignment=ft.CrossAxisAlignment.CENTER),
                    ft.Row([
                        ft.Text("Silence Timeout (s)", size=13, width=180),
                        self._st_slider,
                        self._st_label,
                    ], vertical_alignment=ft.CrossAxisAlignment.CENTER),
                    ft.Row([self._rec_input, browse_btn], spacing=10),
                ], spacing=14),
                padding=20,
            ),
        )

        # --- AI Behaviour ---
        self._proactive_check = ft.Checkbox(
            label="Proactive answers",
            value=config.proactive_answers,
            tooltip="Auto-answer questions detected in the transcript",
        )
        self._auto_ctx_check = ft.Checkbox(
            label="Auto-select context",
            value=config.auto_context_enabled,
            tooltip="Automatically load repos and knowledge based on discussion",
        )

        self._aci_label = ft.Text(str(config.auto_context_interval), size=13, width=40)
        self._aci_slider = ft.Slider(
            min=10, max=120, divisions=22,
            value=config.auto_context_interval,
            label="{value}",
            active_color=TEAL,
            on_change=lambda e: self._update_slider_label(e, self._aci_label, step=5),
            width=250,
        )

        ai_card = ft.Card(
            content=ft.Container(
                content=ft.Column([
                    ft.Text("AI Behaviour", size=14, weight=ft.FontWeight.W_600),
                    self._proactive_check,
                    ft.Text("Auto-answer questions detected in the transcript",
                            size=12, color=ft.Colors.ON_SURFACE_VARIANT),
                    self._auto_ctx_check,
                    ft.Text("Automatically load repos and knowledge based on what is being discussed",
                            size=12, color=ft.Colors.ON_SURFACE_VARIANT),
                    ft.Row([
                        ft.Text("Auto-Context Interval (s)", size=13, width=180),
                        self._aci_slider,
                        self._aci_label,
                    ], vertical_alignment=ft.CrossAxisAlignment.CENTER),
                ], spacing=10),
                padding=20,
            ),
        )

        # --- Save ---
        self._save_status = ft.Text("", size=12, color=ft.Colors.ON_SURFACE_VARIANT)
        save_btn = ft.ElevatedButton(
            "Save Settings",
            icon=ft.Icons.SAVE,
            bgcolor=TEAL,
            color="white",
            on_click=self._save,
        )

        for card in (api_card, prefs_card, ai_card):
            card.expand = True

        self.controls = [
            ft.Container(
                content=ft.Column([
                    ft.Text("Settings", size=22, weight=ft.FontWeight.W_600),
                    api_card,
                    prefs_card,
                    ai_card,
                    ft.Row([save_btn, self._save_status], spacing=12),
                ], spacing=16, horizontal_alignment=ft.CrossAxisAlignment.STRETCH),
                padding=30,
            ),
        ]

    def _on_theme_change(self, e):
        theme_map = {"dark": ft.ThemeMode.DARK, "light": ft.ThemeMode.LIGHT, "system": ft.ThemeMode.SYSTEM}
        self._page.theme_mode = theme_map.get(e.control.value, ft.ThemeMode.SYSTEM)
        self._page.update()

    def _update_slider_label(self, e, label: ft.Text, step: int = 1):
        val = int(round(e.control.value / step) * step) if step > 1 else int(e.control.value)
        label.value = str(val)
        self._page.update()

    async def _browse_recordings(self, e):
        path = await self._file_picker.get_directory_path(
            dialog_title="Select Recordings Directory"
        )
        if path:
            self._rec_input.value = path
            self._page.update()

    def _save(self, e):
        self._config._data["gui_theme"] = self._theme_dropdown.value or "system"
        self._config.anthropic_api_key = (self._anthropic_key.value or "").strip()
        self._config.deepgram_api_key = (self._deepgram_key.value or "").strip()
        self._config.claude_model = self._model_dropdown.value
        self._config.transcription_language = self._lang_dropdown.value
        self._config.sentence_window = int(self._sw_slider.value)
        self._config.silence_timeout = int(self._st_slider.value)
        self._config.proactive_answers = self._proactive_check.value
        self._config.auto_context_enabled = self._auto_ctx_check.value
        self._config.auto_context_interval = int(round(self._aci_slider.value / 5) * 5)
        self._config.recordings_dir = (self._rec_input.value or "").strip()
        self._config.setup_complete = True
        self._config.save()
        self._save_status.value = "Settings saved!"
        self._save_status.color = TEAL
        self._page.update()
