"""Dashboard screen — live status, meeting info, transcript preview."""

from __future__ import annotations

import json
import urllib.request

from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import (
    QFrame,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QScrollArea,
    QTextEdit,
    QVBoxLayout,
    QWidget,
)


class DashboardScreen(QWidget):
    """Shows current daemon/meeting status and live transcript preview."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self._port = 7891
        self._setup_ui()
        self._start_transcript_polling()

    def _setup_ui(self):
        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setFrameShape(QFrame.Shape.NoFrame)

        content = QWidget()
        layout = QVBoxLayout(content)
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(20)

        # Header
        header = QLabel("Dashboard")
        header.setStyleSheet("font-size: 22px; font-weight: 600; color: #ffffff;")
        layout.addWidget(header)

        # Status card
        status_card = QFrame()
        status_card.setProperty("class", "panel")
        status_card.setStyleSheet("""
            QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 20px; }
        """)
        sc_layout = QVBoxLayout(status_card)

        status_row = QHBoxLayout()
        self._status_dot = QLabel("\u25cf")
        self._status_dot.setStyleSheet("color: #5a5a5a; font-size: 28px;")
        status_row.addWidget(self._status_dot)

        self._status_text = QLabel("Daemon not running")
        self._status_text.setStyleSheet("font-size: 16px; font-weight: 500; color: #d4d4d4;")
        status_row.addWidget(self._status_text)
        status_row.addStretch()
        sc_layout.addLayout(status_row)

        self._status_details = QLabel("Start the daemon with: meeting-helper start")
        self._status_details.setStyleSheet("font-size: 13px; color: #808080;")
        self._status_details.setWordWrap(True)
        sc_layout.addWidget(self._status_details)

        layout.addWidget(status_card)

        # Transcript preview card
        transcript_card = QFrame()
        transcript_card.setStyleSheet("""
            QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 20px; }
        """)
        tc_layout = QVBoxLayout(transcript_card)

        tc_header = QLabel("Live Transcript")
        tc_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #808080;")
        tc_layout.addWidget(tc_header)

        self._transcript_preview = QLabel("No active meeting")
        self._transcript_preview.setStyleSheet("font-size: 13px; color: #d4d4d4; padding: 10px 0;")
        self._transcript_preview.setWordWrap(True)
        self._transcript_preview.setMinimumHeight(80)
        self._transcript_preview.setAlignment(Qt.AlignTop)
        tc_layout.addWidget(self._transcript_preview)

        layout.addWidget(transcript_card)

        # Context selector (per-meeting repo + knowledge picker)
        from meeting_helper.gui.widgets.context_selector import ContextSelector
        self._context_selector = ContextSelector()
        layout.addWidget(self._context_selector)

        # Ask Claude card
        ask_card = QFrame()
        ask_card.setStyleSheet("""
            QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 20px; }
        """)
        ac_layout = QVBoxLayout(ask_card)

        ac_header = QLabel("Ask Claude")
        ac_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #808080;")
        ac_layout.addWidget(ac_header)

        input_row = QHBoxLayout()
        self._query_input = QLineEdit()
        self._query_input.setPlaceholderText("Type a question for Claude... (Enter to send)")
        self._query_input.setStyleSheet("""
            QLineEdit {
                background: #1a1a1a; border: 1px solid #333; border-radius: 6px;
                color: #d4d4d4; padding: 8px 12px; font-size: 13px;
            }
            QLineEdit:focus { border-color: #58a6ff; }
        """)
        self._query_input.returnPressed.connect(self._send_query)
        input_row.addWidget(self._query_input)

        send_btn = QPushButton("Send")
        send_btn.setFixedWidth(70)
        send_btn.setCursor(Qt.PointingHandCursor)
        send_btn.setStyleSheet("""
            QPushButton {
                background: #238636; color: white; border: none; border-radius: 6px;
                padding: 8px; font-size: 13px; font-weight: 500;
            }
            QPushButton:hover { background: #2ea043; }
        """)
        send_btn.clicked.connect(self._send_query)
        input_row.addWidget(send_btn)
        ac_layout.addLayout(input_row)

        self._response_area = QTextEdit()
        self._response_area.setReadOnly(True)
        self._response_area.setStyleSheet("""
            QTextEdit {
                background: #1a1a1a; border: 1px solid #333; border-radius: 6px;
                color: #d4d4d4; padding: 8px; font-size: 13px;
            }
        """)
        self._response_area.setMinimumHeight(100)
        self._response_area.setMaximumHeight(200)
        self._response_area.setPlaceholderText("Claude's response will appear here...")
        ac_layout.addWidget(self._response_area)

        layout.addWidget(ask_card)

        # Workspace info card
        workspace_card = QFrame()
        workspace_card.setStyleSheet("""
            QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 20px; }
        """)
        wc_layout = QVBoxLayout(workspace_card)

        wc_header = QLabel("Active Workspace")
        wc_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #808080;")
        wc_layout.addWidget(wc_header)

        self._workspace_info = QLabel("No workspace configured")
        self._workspace_info.setStyleSheet("font-size: 13px; color: #d4d4d4;")
        self._workspace_info.setWordWrap(True)
        wc_layout.addWidget(self._workspace_info)

        layout.addWidget(workspace_card)
        layout.addStretch()

        scroll.setWidget(content)
        outer = QVBoxLayout(self)
        outer.setContentsMargins(0, 0, 0, 0)
        outer.addWidget(scroll)

    def set_port(self, port: int):
        """Set daemon port for query requests."""
        self._port = port
        self._context_selector.set_port(port)

    def _start_transcript_polling(self):
        """Poll daemon /transcript endpoint every 2s for live transcript."""
        self._transcript_timer = QTimer(self)
        self._transcript_timer.timeout.connect(self._poll_transcript)
        self._transcript_timer.start(2000)

    def _poll_transcript(self):
        """Fetch latest transcript sentences from daemon."""
        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}]")
                display = "\n".join(lines[-5:])
                self._transcript_preview.setText(display)
                self._transcript_preview.setStyleSheet(
                    "font-size: 13px; color: #3fb950; padding: 10px 0;"
                )
            else:
                # Don't overwrite if there's already text showing
                pass
        except Exception:
            pass

    def _send_query(self):
        """Send manual query to daemon."""
        text = self._query_input.text().strip()
        if not text:
            return
        self._query_input.clear()
        self._response_area.setPlainText("Thinking...")

        import threading
        threading.Thread(target=self._post_query, args=(text,), daemon=True).start()

    def _post_query(self, text: str):
        """POST query in background thread, then fetch response."""
        import json
        import urllib.request

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

            # Query is done — fetch the actual response
            req2 = urllib.request.Request(f"http://127.0.0.1:{port}/last_response")
            with urllib.request.urlopen(req2, timeout=3) as resp:
                data = json.loads(resp.read().decode())
            response_text = data.get("text", "")

            from PySide6.QtCore import QMetaObject, Qt as QtConst, Q_ARG
            QMetaObject.invokeMethod(
                self._response_area, "setPlainText",
                QtConst.ConnectionType.QueuedConnection,
                Q_ARG(str, response_text or "(empty response)"),
            )
        except Exception as exc:
            from PySide6.QtCore import QMetaObject, Qt as QtConst, Q_ARG
            QMetaObject.invokeMethod(
                self._response_area, "setPlainText",
                QtConst.ConnectionType.QueuedConnection,
                Q_ARG(str, f"Error: {exc}"),
            )

    def update_status(self, daemon_running: bool, session_active: bool, meeting_name: str):
        """Update status display."""
        self._context_selector.set_session_active(session_active)
        if session_active:
            self._status_dot.setStyleSheet("color: #f14c4c; font-size: 28px;")
            self._status_text.setText(f"Recording: {meeting_name}")
            self._status_details.setText("Meeting in progress. Audio is being recorded and transcribed.")
        elif daemon_running:
            self._status_dot.setStyleSheet("color: #4ec9b0; font-size: 28px;")
            self._status_text.setText("Ready")
            self._status_details.setText("Daemon is running. Waiting for a meeting to start.")
        else:
            self._status_dot.setStyleSheet("color: #5a5a5a; font-size: 28px;")
            self._status_text.setText("Daemon not running")
            self._status_details.setText("Start the daemon with: meeting-helper start")

    def update_transcript_preview(self, text: str):
        """Update the transcript preview text."""
        self._transcript_preview.setText(text or "No active meeting")

    def update_workspace_info(self, repos: list[str], knowledge_path: str):
        """Update workspace info display."""
        parts = []
        if repos:
            parts.append(f"Repos: {len(repos)}")
        if knowledge_path:
            parts.append(f"Knowledge: {knowledge_path}")
        self._workspace_info.setText("\n".join(parts) if parts else "No workspace configured")
        self._context_selector.set_config(repos, knowledge_path, self._port)
