"""Settings screen — API keys, preferences."""

from __future__ import annotations

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


class SettingsScreen(QWidget):
    """API keys, model selection, and other preferences."""

    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("Settings")
        header.setStyleSheet("font-size: 22px; font-weight: 600; color: #ffffff;")
        layout.addWidget(header)

        # API Keys card
        api_card = QFrame()
        api_card.setStyleSheet("QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 15px; }")
        ac_layout = QVBoxLayout(api_card)

        ac_header = QLabel("API Keys")
        ac_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #ffffff;")
        ac_layout.addWidget(ac_header)

        # Anthropic key
        ac_layout.addWidget(QLabel("Anthropic API Key"))
        self._anthropic_key = QLineEdit()
        self._anthropic_key.setEchoMode(QLineEdit.Password)
        self._anthropic_key.setPlaceholderText("sk-ant-...")
        ac_layout.addWidget(self._anthropic_key)

        # Deepgram key
        ac_layout.addWidget(QLabel("Deepgram API Key"))
        self._deepgram_key = QLineEdit()
        self._deepgram_key.setEchoMode(QLineEdit.Password)
        self._deepgram_key.setPlaceholderText("Deepgram API key (for live transcription)")
        ac_layout.addWidget(self._deepgram_key)

        layout.addWidget(api_card)

        # Model & preferences card
        prefs_card = QFrame()
        prefs_card.setStyleSheet("QFrame { background-color: #0d0d0d; border: 1px solid #2a2a2a; border-radius: 8px; padding: 15px; }")
        pc_layout = QVBoxLayout(prefs_card)

        pc_header = QLabel("Preferences")
        pc_header.setStyleSheet("font-size: 14px; font-weight: 600; color: #ffffff;")
        pc_layout.addWidget(pc_header)

        # Claude model
        model_row = QHBoxLayout()
        model_row.addWidget(QLabel("Claude Model"))
        self._model_combo = QComboBox()
        self._model_combo.addItems(["sonnet", "opus", "haiku"])
        model_row.addWidget(self._model_combo)
        model_row.addStretch()
        pc_layout.addLayout(model_row)

        # Transcription language
        lang_row = QHBoxLayout()
        lang_row.addWidget(QLabel("Transcription Language"))
        self._lang_combo = QComboBox()
        self._lang_combo.addItems(["en", "es", "pt", "fr", "de", "it", "ja", "ko", "zh", "auto"])
        lang_row.addWidget(self._lang_combo)
        lang_row.addStretch()
        pc_layout.addLayout(lang_row)

        # Sentence window
        sw_row = QHBoxLayout()
        sw_row.addWidget(QLabel("Sentence Window"))
        self._sw_slider = QSlider(Qt.Horizontal)
        self._sw_slider.setMinimum(1)
        self._sw_slider.setMaximum(10)
        self._sw_slider.setValue(5)
        self._sw_slider.setFixedWidth(200)
        sw_row.addWidget(self._sw_slider)
        self._sw_label = QLabel("5")
        self._sw_label.setFixedWidth(30)
        sw_row.addWidget(self._sw_label)
        self._sw_slider.valueChanged.connect(lambda v: self._sw_label.setText(str(v)))
        sw_row.addStretch()
        pc_layout.addLayout(sw_row)

        # Silence timeout
        st_row = QHBoxLayout()
        st_row.addWidget(QLabel("Silence Timeout (s)"))
        self._st_slider = QSlider(Qt.Horizontal)
        self._st_slider.setMinimum(10)
        self._st_slider.setMaximum(120)
        self._st_slider.setValue(30)
        self._st_slider.setFixedWidth(200)
        st_row.addWidget(self._st_slider)
        self._st_label = QLabel("30")
        self._st_label.setFixedWidth(30)
        st_row.addWidget(self._st_label)
        self._st_slider.valueChanged.connect(lambda v: self._st_label.setText(str(v)))
        st_row.addStretch()
        pc_layout.addLayout(st_row)

        # Recordings directory
        rec_row = QHBoxLayout()
        rec_row.addWidget(QLabel("Recordings Directory"))
        self._rec_input = QLineEdit()
        self._rec_input.setPlaceholderText("~/meetings")
        rec_row.addWidget(self._rec_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_recordings)
        rec_row.addWidget(browse_btn)
        pc_layout.addLayout(rec_row)

        layout.addWidget(prefs_card)

        # Save button
        save_row = QHBoxLayout()
        save_btn = QPushButton("Save Settings")
        save_btn.clicked.connect(self._save)
        save_row.addWidget(save_btn)

        self._save_status = QLabel("")
        self._save_status.setStyleSheet("color: #808080; font-size: 12px;")
        save_row.addWidget(self._save_status)
        save_row.addStretch()
        layout.addLayout(save_row)

        layout.addStretch()

    def set_config(self, config):
        """Load settings from config."""
        self._config = config
        self._anthropic_key.setText(config.anthropic_api_key)
        self._deepgram_key.setText(config.deepgram_api_key)

        # Model alias
        model = config._data.get("claude_model", "sonnet")
        idx = self._model_combo.findText(model)
        if idx >= 0:
            self._model_combo.setCurrentIndex(idx)

        self._lang_combo.setCurrentText(config.transcription_language)
        self._sw_slider.setValue(config.sentence_window)
        self._sw_label.setText(str(config.sentence_window))
        self._st_slider.setValue(config.silence_timeout)
        self._st_label.setText(str(config.silence_timeout))
        self._rec_input.setText(str(config.recordings_dir))

    def _browse_recordings(self):
        path = QFileDialog.getExistingDirectory(self, "Select Recordings Directory")
        if path:
            self._rec_input.setText(path)

    def _save(self):
        if not self._config:
            return

        self._config.anthropic_api_key = self._anthropic_key.text().strip()
        self._config.deepgram_api_key = self._deepgram_key.text().strip()
        self._config.claude_model = self._model_combo.currentText()
        self._config.transcription_language = self._lang_combo.currentText()
        self._config.sentence_window = self._sw_slider.value()
        self._config.silence_timeout = self._st_slider.value()
        self._config.recordings_dir = self._rec_input.text().strip()
        self._config.setup_complete = True
        self._config.save()

        self._save_status.setText("Settings saved!")
        self._save_status.setStyleSheet("color: #4ec9b0; font-size: 12px;")
