"""Workspace screen — edit repos list + knowledge folder path."""

from __future__ import annotations

import json
from pathlib import Path

from PySide6.QtCore import Qt
from PySide6.QtWidgets import (
    QFileDialog,
    QFrame,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QListWidget,
    QPushButton,
    QVBoxLayout,
    QWidget,
)


class WorkspaceScreen(QWidget):
    """Edit repos list and knowledge folder for Claude context."""

    def __init__(self, parent=None):
        super().__init__(parent)
        self._config = None
        self._setup_ui()

    def _setup_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(30, 30, 30, 30)
        layout.setSpacing(20)

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

        subtitle = QLabel("Configure repos and knowledge docs for Claude context")
        subtitle.setStyleSheet("font-size: 13px; color: #808080;")
        layout.addWidget(subtitle)

        # Repos section
        repos_card = QFrame()
        repos_card.setStyleSheet("QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 15px; }")
        rc_layout = QVBoxLayout(repos_card)

        rc_header = QLabel("Repositories")
        rc_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #ffffff;")
        rc_layout.addWidget(rc_header)

        self._repos_list = QListWidget()
        self._repos_list.setMinimumHeight(120)
        rc_layout.addWidget(self._repos_list)

        repo_btns = QHBoxLayout()
        add_repo_btn = QPushButton("Add Repo")
        add_repo_btn.clicked.connect(self._add_repo)
        repo_btns.addWidget(add_repo_btn)

        remove_repo_btn = QPushButton("Remove")
        remove_repo_btn.setProperty("class", "secondary")
        remove_repo_btn.setStyleSheet("background-color: #2a2a2a; color: #d4d4d4;")
        remove_repo_btn.clicked.connect(self._remove_repo)
        repo_btns.addWidget(remove_repo_btn)
        repo_btns.addStretch()
        rc_layout.addLayout(repo_btns)

        layout.addWidget(repos_card)

        # Knowledge folder section
        knowledge_card = QFrame()
        knowledge_card.setStyleSheet("QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 15px; }")
        kc_layout = QVBoxLayout(knowledge_card)

        kc_header = QLabel("Knowledge Folder")
        kc_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #ffffff;")
        kc_layout.addWidget(kc_header)

        kc_desc = QLabel("Folder with .md and .txt files organized by topic")
        kc_desc.setStyleSheet("font-size: 12px; color: #808080;")
        kc_layout.addWidget(kc_desc)

        path_row = QHBoxLayout()
        self._knowledge_input = QLineEdit()
        self._knowledge_input.setPlaceholderText("/path/to/knowledge/folder")
        path_row.addWidget(self._knowledge_input, 1)

        browse_btn = QPushButton("Browse")
        browse_btn.setProperty("class", "secondary")
        browse_btn.setStyleSheet("background-color: #2a2a2a; color: #d4d4d4;")
        browse_btn.clicked.connect(self._browse_knowledge)
        path_row.addWidget(browse_btn)
        kc_layout.addLayout(path_row)

        layout.addWidget(knowledge_card)

        # Context info
        self._context_info = QLabel("")
        self._context_info.setStyleSheet("font-size: 12px; color: #808080;")
        layout.addWidget(self._context_info)

        # Save buttons
        save_row = QHBoxLayout()
        save_global_btn = QPushButton("Save Globally")
        save_global_btn.clicked.connect(self._save_global)
        save_row.addWidget(save_global_btn)

        apply_session_btn = QPushButton("Apply to Session")
        apply_session_btn.setStyleSheet("background-color: #0078d4; color: #ffffff;")
        apply_session_btn.clicked.connect(self._apply_session)
        save_row.addWidget(apply_session_btn)

        reload_btn = QPushButton("Reload Context")
        reload_btn.setProperty("class", "secondary")
        reload_btn.setStyleSheet("background-color: #2a2a2a; color: #d4d4d4;")
        reload_btn.clicked.connect(self._reload_context)
        save_row.addWidget(reload_btn)

        save_row.addStretch()
        layout.addLayout(save_row)

        layout.addStretch()

    def set_config(self, config):
        """Load from config object (meeting_helper.config.Config)."""
        self._config = config
        self._repos_list.clear()
        for repo in config.repos:
            self._repos_list.addItem(repo)
        self._knowledge_input.setText(config.knowledge_path)
        self._update_context_info()

    def _add_repo(self):
        path = QFileDialog.getExistingDirectory(self, "Select Repository")
        if path:
            self._repos_list.addItem(path)

    def _remove_repo(self):
        row = self._repos_list.currentRow()
        if row >= 0:
            self._repos_list.takeItem(row)

    def _browse_knowledge(self):
        path = QFileDialog.getExistingDirectory(self, "Select Knowledge Folder")
        if path:
            self._knowledge_input.setText(path)

    def _get_repos(self) -> list[str]:
        return [self._repos_list.item(i).text() for i in range(self._repos_list.count())]

    def _save_global(self):
        """Save workspace config globally."""
        if not self._config:
            return
        self._config.repos = self._get_repos()
        self._config.knowledge_path = self._knowledge_input.text().strip()
        self._config.save()
        self._update_context_info()
        self._context_info.setText("Saved globally!")
        self._context_info.setStyleSheet("color: #4ec9b0; font-size: 12px;")

    def _apply_session(self):
        """Apply to current session via daemon HTTP endpoint."""
        import urllib.request

        repos = self._get_repos()
        knowledge_path = self._knowledge_input.text().strip()

        try:
            port = self._config.port if self._config else 7891
            data = json.dumps({"repos": repos, "knowledge_path": knowledge_path}).encode()
            req = urllib.request.Request(
                f"http://127.0.0.1:{port}/config",
                data=data,
                headers={"Content-Type": "application/json"},
                method="POST",
            )
            with urllib.request.urlopen(req, timeout=5) as resp:
                result = json.loads(resp.read().decode())
            if result.get("changed"):
                self._context_info.setText("Applied to current session!")
                self._context_info.setStyleSheet("color: #4ec9b0; font-size: 12px;")
            else:
                self._context_info.setText("No changes to apply")
                self._context_info.setStyleSheet("color: #808080; font-size: 12px;")
        except Exception as exc:
            self._context_info.setText(f"Error: {exc}")
            self._context_info.setStyleSheet("color: #f14c4c; font-size: 12px;")

    def _reload_context(self):
        """Reload context by re-applying current settings to session."""
        self._apply_session()

    def _update_context_info(self):
        repos = self._get_repos()
        knowledge = self._knowledge_input.text().strip()
        parts = []
        if repos:
            parts.append(f"{len(repos)} repo(s)")
        if knowledge:
            knowledge_path = Path(knowledge).expanduser()
            if knowledge_path.is_dir():
                docs = list(knowledge_path.rglob("*.md")) + list(knowledge_path.rglob("*.txt"))
                parts.append(f"{len(docs)} knowledge doc(s)")
        self._context_info.setText(" | ".join(parts) if parts else "No workspace configured")
        self._context_info.setStyleSheet("color: #808080; font-size: 12px;")
