"""Workspace screen — repos workspace folder + 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):
    """Configure repos workspace 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("Set your repos workspace and knowledge folder. Repos are selected per-meeting.")
        subtitle.setStyleSheet("font-size: 13px; color: #808080;")
        subtitle.setWordWrap(True)
        layout.addWidget(subtitle)

        # Repos workspace 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("Repos Workspace")
        rc_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #ffffff;")
        rc_layout.addWidget(rc_header)

        rc_desc = QLabel("Folder containing your repos. Each subfolder will appear as a selectable repo in the context panel.")
        rc_desc.setStyleSheet("font-size: 12px; color: #808080;")
        rc_desc.setWordWrap(True)
        rc_layout.addWidget(rc_desc)

        repos_path_row = QHBoxLayout()
        self._repos_workspace_input = QLineEdit()
        self._repos_workspace_input.setPlaceholderText("/path/to/workspace")
        repos_path_row.addWidget(self._repos_workspace_input, 1)

        repos_browse_btn = QPushButton("Browse")
        repos_browse_btn.setStyleSheet("background-color: #2a2a2a; color: #d4d4d4;")
        repos_browse_btn.clicked.connect(self._browse_repos_workspace)
        repos_path_row.addWidget(repos_browse_btn)
        rc_layout.addLayout(repos_path_row)

        # Preview of discovered repos
        self._repos_preview = QListWidget()
        self._repos_preview.setMaximumHeight(120)
        self._repos_preview.setStyleSheet("""
            QListWidget { background: #1a1a1a; border: 1px solid #2a2a2a; border-radius: 4px; color: #808080; font-size: 12px; }
        """)
        self._repos_preview.setEnabled(False)
        rc_layout.addWidget(self._repos_preview)
        self._repos_workspace_input.textChanged.connect(self._refresh_repos_preview)

        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 subfolders.")
        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.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)

        # Status
        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)

        save_row.addStretch()
        layout.addLayout(save_row)

        layout.addStretch()

    def set_config(self, config):
        self._config = config
        self._repos_workspace_input.setText(config.repos_workspace)
        self._knowledge_input.setText(config.knowledge_path)
        self._refresh_repos_preview(config.repos_workspace)

    def _browse_repos_workspace(self):
        path = QFileDialog.getExistingDirectory(self, "Select Repos Workspace Folder")
        if path:
            self._repos_workspace_input.setText(path)

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

    def _refresh_repos_preview(self, workspace_path: str = ""):
        """Show discovered repos from the workspace folder."""
        self._repos_preview.clear()
        path = Path(workspace_path.strip()).expanduser() if workspace_path.strip() else None
        if not path or not path.is_dir():
            self._repos_preview.addItem("— enter a workspace folder to see repos —")
            return
        try:
            from meeting_helper.context_loader import get_repos_from_workspace
            repos = get_repos_from_workspace(str(path))
            if repos:
                for r in repos:
                    self._repos_preview.addItem(f"  {r['sanitized_name']}  ({r['name']})")
            else:
                self._repos_preview.addItem("— no subdirectories found —")
        except Exception:
            self._repos_preview.addItem("— could not scan folder —")

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

    def _apply_session(self):
        import urllib.request
        repos_workspace = self._repos_workspace_input.text().strip()
        knowledge_path = self._knowledge_input.text().strip()
        try:
            port = self._config.port if self._config else 7891
            data = json.dumps({
                "repos_workspace": repos_workspace,
                "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 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;")
