"""Dashboard screen — live status, transcript preview, Ask Claude, context selector."""

from __future__ import annotations

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

import flet as ft

from meeting_helper.flet_gui.components.context_selector import ContextSelector

if TYPE_CHECKING:
    from meeting_helper.config import Config

TEAL = "#4ec9b0"
ERROR_RED = "#f14c4c"


class DashboardScreen(ft.Column):
    """Shows daemon/meeting status, live transcript, Ask Claude, and context selector."""

    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
        self._port = config.port

        # --- Status card ---
        self._status_icon = ft.Icon(ft.Icons.CIRCLE, color=ft.Colors.OUTLINE, size=24)
        self._status_text = ft.Text("Daemon not running", size=16, weight=ft.FontWeight.W_500)
        self._status_detail = ft.Text(
            "Start the daemon with: meeting-helper start",
            size=13, color=ft.Colors.ON_SURFACE_VARIANT,
        )

        status_card = ft.Card(
            content=ft.Container(
                content=ft.Column([
                    ft.Row([self._status_icon, self._status_text], spacing=10),
                    self._status_detail,
                ], spacing=8),
                padding=20,
            ),
        )

        # --- Live transcript ---
        self._transcript_text = ft.Text(
            "No active meeting",
            size=13,
            selectable=True,
        )
        transcript_card = ft.Card(
            content=ft.Container(
                content=ft.Column([
                    ft.Text("Live Transcript", size=14, weight=ft.FontWeight.W_600, color=ft.Colors.ON_SURFACE_VARIANT),
                    ft.Container(self._transcript_text, padding=ft.padding.symmetric(vertical=10)),
                ], spacing=4),
                padding=20,
            ),
        )

        # --- Context selector ---
        self._context_selector = ContextSelector(page, config)

        ctx_card = ft.Card(
            content=ft.Container(
                content=self._context_selector,
                padding=20,
            ),
        )

        # --- Ask Claude ---
        self._query_input = ft.TextField(
            hint_text="Type a question for Claude... (Enter to send)",
            dense=True,
            border_radius=8,
            text_size=13,
            on_submit=self._send_query,
            expand=True,
        )
        self._send_btn = ft.ElevatedButton(
            "Send",
            bgcolor="#238636",
            color="white",
            on_click=self._send_query,
        )
        self._response_area = ft.TextField(
            read_only=True,
            multiline=True,
            min_lines=4,
            max_lines=8,
            border_radius=8,
            text_size=13,
            hint_text="Claude's response will appear here...",
            expand=True,
        )

        ask_card = ft.Card(
            content=ft.Container(
                content=ft.Column([
                    ft.Text("Ask Claude", size=14, weight=ft.FontWeight.W_600, color=ft.Colors.ON_SURFACE_VARIANT),
                    ft.Row([self._query_input, self._send_btn], spacing=10),
                    self._response_area,
                ], spacing=10),
                padding=20,
            ),
        )

        # --- Workspace info ---
        self._workspace_info = ft.Text("No workspace configured", size=13)
        workspace_card = ft.Card(
            content=ft.Container(
                content=ft.Column([
                    ft.Text("Active Workspace", size=14, weight=ft.FontWeight.W_600, color=ft.Colors.ON_SURFACE_VARIANT),
                    self._workspace_info,
                ], spacing=8),
                padding=20,
            ),
        )

        # Populate workspace info
        parts = []
        if config.repos_workspaces:
            parts.append(f"Repos: {', '.join(config.repos_workspaces)}")
        if config.knowledge_paths:
            parts.append(f"Knowledge: {', '.join(config.knowledge_paths)}")
        self._workspace_info.value = "\n".join(parts) if parts else "No workspace configured"

        # Make all cards stretch full width
        for card in (status_card, transcript_card, ctx_card, ask_card, workspace_card):
            card.expand = True

        self.controls = [
            ft.Container(
                content=ft.Column([
                    ft.Text("Dashboard", size=22, weight=ft.FontWeight.W_600),
                    status_card,
                    transcript_card,
                    ctx_card,
                    ask_card,
                    workspace_card,
                ], spacing=16, horizontal_alignment=ft.CrossAxisAlignment.STRETCH),
                padding=30,
            ),
        ]

        # Start transcript polling
        self._start_polling()

    def update_status(self, daemon_running: bool, session_active: bool, meeting_name: str):
        self._context_selector.set_session_active(session_active)
        if session_active:
            self._status_icon.color = ERROR_RED
            self._status_icon.name = ft.Icons.FIBER_MANUAL_RECORD
            self._status_text.value = f"Recording: {meeting_name}"
            self._status_detail.value = "Meeting in progress. Audio is being recorded and transcribed."
        elif daemon_running:
            self._status_icon.color = TEAL
            self._status_icon.name = ft.Icons.CHECK_CIRCLE
            self._status_text.value = "Ready"
            self._status_detail.value = "Daemon is running. Waiting for a meeting to start."
        else:
            self._status_icon.color = ft.Colors.OUTLINE
            self._status_icon.name = ft.Icons.CIRCLE
            self._status_text.value = "Daemon not running"
            self._status_detail.value = "Start the daemon with: meeting-helper start"

    def _start_polling(self):
        def _poll():
            while True:
                self._poll_transcript()
                self._poll_auto_context()
                threading.Event().wait(2)

        self._page.run_thread(_poll)

    def _poll_transcript(self):
        try:
            req = urllib.request.Request(f"http://127.0.0.1:{self._port}/transcript?n=5")
            with urllib.request.urlopen(req, timeout=1) as resp:
                data = json.loads(resp.read().decode())
            sentences = data.get("sentences", [])
            interim = data.get("interim")
            if sentences or interim:
                lines = list(sentences)
                if interim:
                    lines.append(f"[{interim}]")
                self._transcript_text.value = "\n".join(lines[-5:])
                self._transcript_text.color = "#3fb950"
                try:
                    self._page.update()
                except Exception:
                    pass
        except Exception:
            pass

    def _poll_auto_context(self):
        try:
            req = urllib.request.Request(f"http://127.0.0.1:{self._port}/auto-context")
            with urllib.request.urlopen(req, timeout=1) as resp:
                data = json.loads(resp.read().decode())
            selection = data.get("selection", {})
            repos = selection.get("repos", [])
            knowledge = selection.get("knowledge", [])
            if repos or knowledge:
                self._context_selector.sync_selection(repos, knowledge)
                try:
                    self._page.update()
                except Exception:
                    pass
        except Exception:
            pass

    def _send_query(self, e):
        text = self._query_input.value.strip() if self._query_input.value else ""
        if not text:
            return
        self._query_input.value = ""
        self._response_area.value = "Thinking..."
        self._page.update()

        def _do():
            try:
                body = json.dumps({"text": text}).encode()
                req = urllib.request.Request(
                    f"http://127.0.0.1:{self._port}/query",
                    data=body,
                    headers={"Content-Type": "application/json"},
                )
                urllib.request.urlopen(req, timeout=120)

                req2 = urllib.request.Request(f"http://127.0.0.1:{self._port}/last_response")
                with urllib.request.urlopen(req2, timeout=3) as resp:
                    data = json.loads(resp.read().decode())
                self._response_area.value = data.get("text", "") or "(empty response)"
            except Exception as exc:
                self._response_area.value = f"Error: {exc}"
            try:
                self._page.update()
            except Exception:
                pass

        self._page.run_thread(_do)
