"""Flet application entry point — Material Design 3 dark theme with navigation rail."""

from __future__ import annotations

import json
import threading
import urllib.request
from typing import TYPE_CHECKING

import flet as ft

if TYPE_CHECKING:
    from meeting_helper.config import Config


# ---------------------------------------------------------------------------
# Theme colours (matching overlay palette)
# ---------------------------------------------------------------------------
TEAL = "#4ec9b0"
ERROR_RED = "#f14c4c"
SURFACE = "#1e1e1e"
BG = "#0d0d0d"


def _poll_daemon_loop(port: int, callback):
    """Poll /health every 3 s and call *callback(daemon_running, session_active, meeting_name)*.
    Must be called via page.run_thread() so page.update() works."""
    while True:
        try:
            req = urllib.request.Request(f"http://127.0.0.1:{port}/health")
            with urllib.request.urlopen(req, timeout=1) as resp:
                data = json.loads(resp.read().decode())
            callback(True, data.get("session_active", False), data.get("meeting", ""))
        except Exception:
            callback(False, False, "")
        threading.Event().wait(3)


def run_flet_gui(config: "Config") -> None:
    """Launch the Flet-based GUI."""
    # Hide the Python host process from the macOS dock (only Flutter window should show)
    try:
        from AppKit import NSApplication, NSApplicationActivationPolicyAccessory
        NSApplication.sharedApplication().setActivationPolicy_(NSApplicationActivationPolicyAccessory)
    except Exception:
        pass

    def main(page: ft.Page):
        page.title = "Meeting Helper"

        # Theme from config (default: system)
        theme_pref = config._data.get("gui_theme", "system")
        _THEME_MAP = {"dark": ft.ThemeMode.DARK, "light": ft.ThemeMode.LIGHT, "system": ft.ThemeMode.SYSTEM}
        page.theme_mode = _THEME_MAP.get(theme_pref, ft.ThemeMode.SYSTEM)

        page.theme = ft.Theme(color_scheme_seed=TEAL)
        page.dark_theme = ft.Theme(
            color_scheme_seed=TEAL,
            color_scheme=ft.ColorScheme(
                primary=TEAL,
                on_primary="#ffffff",
                surface=SURFACE,
                on_surface="#cccccc",
                error=ERROR_RED,
            ),
        )
        page.window.width = 1200
        page.window.height = 800
        page.window.min_width = 1000
        page.window.min_height = 700

        # Center window on screen — hide until positioned
        page.window.wait_until_ready_to_show = True
        try:
            from AppKit import NSScreen
            f = NSScreen.mainScreen().frame()
            sw, sh = int(f.size.width), int(f.size.height)
            page.window.top = (sh - 800) // 2
            page.window.left = (sw - 1200) // 2
        except Exception:
            pass
        page.padding = 0

        # --- Screens ---
        from meeting_helper.flet_gui.screens import (
            DashboardScreen,
            RecordingsScreen,
            SettingsScreen,
            WorkspaceScreen,
        )

        dashboard = DashboardScreen(page, config)
        recordings = RecordingsScreen(page, config)
        settings_screen = SettingsScreen(page, config)
        workspace = WorkspaceScreen(page, config)

        screens = [dashboard, recordings, workspace, settings_screen]
        content_area = ft.Container(
            content=screens[0],
            expand=True,
            padding=0,
        )

        # --- Status indicator ---
        status_icon = ft.Icon(ft.Icons.CIRCLE, color="#5a5a5a", size=12)
        status_text = ft.Text("Stopped", size=11, color="#808080")

        def on_status(daemon_running: bool, session_active: bool, meeting_name: str):
            if session_active:
                status_icon.color = ERROR_RED
                status_text.value = "Recording"
                status_text.color = ERROR_RED
            elif daemon_running:
                status_icon.color = TEAL
                status_text.value = "Ready"
                status_text.color = TEAL
            else:
                status_icon.color = "#5a5a5a"
                status_text.value = "Stopped"
                status_text.color = "#808080"

            dashboard.update_status(daemon_running, session_active, meeting_name)
            try:
                page.update()
            except Exception:
                pass

        page.run_thread(_poll_daemon_loop, config.port, on_status)

        # --- Navigation rail ---
        def on_nav_change(e):
            idx = e.control.selected_index
            # Stop audio when leaving Recordings
            if content_area.content is recordings:
                recordings.cleanup()
            content_area.content = screens[idx]
            if hasattr(screens[idx], "on_activate"):
                screens[idx].on_activate()
            page.update()

        rail = ft.NavigationRail(
            selected_index=0,
            label_type=ft.NavigationRailLabelType.ALL,
            bgcolor=ft.Colors.SURFACE,
            min_width=100,
            min_extended_width=200,
            expand=True,
            destinations=[
                ft.NavigationRailDestination(
                    icon=ft.Icons.DASHBOARD_OUTLINED,
                    selected_icon=ft.Icons.DASHBOARD,
                    label="Dashboard",
                ),
                ft.NavigationRailDestination(
                    icon=ft.Icons.MIC_NONE_OUTLINED,
                    selected_icon=ft.Icons.MIC,
                    label="Recordings",
                ),
                ft.NavigationRailDestination(
                    icon=ft.Icons.FOLDER_OUTLINED,
                    selected_icon=ft.Icons.FOLDER,
                    label="Workspace",
                ),
                ft.NavigationRailDestination(
                    icon=ft.Icons.SETTINGS_OUTLINED,
                    selected_icon=ft.Icons.SETTINGS,
                    label="Settings",
                ),
            ],
            on_change=on_nav_change,
        )

        sidebar = ft.Container(
            content=ft.Column(
                [
                    rail,
                    ft.Container(
                        content=ft.Row(
                            [status_icon, status_text],
                            spacing=6,
                            alignment=ft.MainAxisAlignment.CENTER,
                        ),
                        padding=ft.padding.only(bottom=16, top=8),
                    ),
                ],
                spacing=0,
                expand=True,
            ),
            width=100,
            bgcolor=ft.Colors.SURFACE,
        )

        # Cleanup audio on window close
        def _on_disconnect(e):
            recordings.cleanup()

        page.on_disconnect = _on_disconnect

        page.add(
            ft.Row(
                [
                    sidebar,
                    ft.VerticalDivider(width=1),
                    content_area,
                ],
                expand=True,
                spacing=0,
            )
        )

    ft.app(target=main)
