#!/usr/bin/env python3
"""
Settings Tab for neo-pod-desktop.
"""

import os
from typing import Optional

from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QLabel, QLineEdit,
    QComboBox, QCheckBox, QSpinBox, QGroupBox, QHeaderView,
    QTableWidget, QTableWidgetItem, QFileDialog, QMessageBox,
)
from PyQt6.QtCore import Qt, pyqtSignal

from hotkeys import HotkeyManager, KeyCaptureDialog


class SettingsTab(QWidget):
    """Settings tab widget."""

    hide_library_buttons_changed = pyqtSignal(bool)
    auto_detect_changed = pyqtSignal(bool)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.hotkey_manager: Optional[HotkeyManager] = None
        self._setup_ui()

    def set_hotkey_manager(self, hm: HotkeyManager):
        self.hotkey_manager = hm

    def _setup_ui(self):
        layout = QVBoxLayout(self)

        library_group = QGroupBox("Library")
        library_layout = QVBoxLayout(library_group)

        output_layout = QHBoxLayout()
        output_label = QLabel("Output Directory:")
        self.output_dir_input = QLineEdit()
        self.output_dir_input.setText(os.path.join(os.path.expanduser("~"), "Music", "iPod"))
        browse_btn = QPushButton("Browse...")
        browse_btn.clicked.connect(self._on_browse_output_clicked)
        output_layout.addWidget(output_label)
        output_layout.addWidget(self.output_dir_input)
        output_layout.addWidget(browse_btn)
        library_layout.addLayout(output_layout)

        convert_layout = QHBoxLayout()
        convert_format_label = QLabel("Convert Format:")
        self.format_combo = QComboBox()
        self.format_combo.addItems(["mp3", "m4a"])
        convert_quality_label = QLabel("Quality (kbps):")
        self.quality_spin = QSpinBox()
        self.quality_spin.setRange(128, 320)
        self.quality_spin.setValue(256)
        self.quality_spin.setSingleStep(32)
        convert_layout.addWidget(convert_format_label)
        convert_layout.addWidget(self.format_combo)
        convert_layout.addWidget(convert_quality_label)
        convert_layout.addWidget(self.quality_spin)
        convert_layout.addStretch()
        library_layout.addLayout(convert_layout)

        layout.addWidget(library_group)

        metadata_group = QGroupBox("Metadata Options")
        metadata_layout = QVBoxLayout(metadata_group)

        self.embed_artwork_check = QCheckBox("Embed Album Artwork")
        self.embed_artwork_check.setChecked(True)
        metadata_layout.addWidget(self.embed_artwork_check)

        layout.addWidget(metadata_group)

        advanced_group = QGroupBox("Advanced Options")
        advanced_layout = QVBoxLayout(advanced_group)

        self.clean_temp_check = QCheckBox("Clean Temporary Files After Transfer")
        self.clean_temp_check.setChecked(True)
        advanced_layout.addWidget(self.clean_temp_check)

        self.auto_detect_check = QCheckBox("Auto-Detect iPod")
        self.auto_detect_check.setChecked(True)
        self.auto_detect_check.toggled.connect(self.auto_detect_changed.emit)
        advanced_layout.addWidget(self.auto_detect_check)

        self.hide_library_buttons_check = QCheckBox("Hide Library Toolbar Buttons")
        self.hide_library_buttons_check.setChecked(False)
        self.hide_library_buttons_check.toggled.connect(self._on_hide_buttons_toggled)
        advanced_layout.addWidget(self.hide_library_buttons_check)

        layout.addWidget(advanced_group)

        shortcuts_group = QGroupBox("Keyboard Shortcuts")
        shortcuts_layout = QVBoxLayout(shortcuts_group)

        self.shortcuts_table = QTableWidget()
        self.shortcuts_table.setColumnCount(2)
        self.shortcuts_table.setHorizontalHeaderLabels(["Action", "Shortcut"])
        self.shortcuts_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.shortcuts_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        self.shortcuts_table.setEditTriggers(QTableWidget.EditTrigger.NoEditTriggers)
        self.shortcuts_table.setAlternatingRowColors(True)
        self.shortcuts_table.cellDoubleClicked.connect(self._on_shortcut_double_clicked)
        shortcuts_header = self.shortcuts_table.horizontalHeader()
        shortcuts_header.setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
        shortcuts_header.setSectionResizeMode(1, QHeaderView.ResizeMode.ResizeToContents)
        shortcuts_layout.addWidget(self.shortcuts_table)

        reset_shortcuts_btn = QPushButton("Reset to Defaults")
        reset_shortcuts_btn.clicked.connect(self._on_reset_shortcuts_clicked)
        shortcuts_layout.addWidget(reset_shortcuts_btn)

        layout.addWidget(shortcuts_group)

        layout.addStretch()

        about_label = QLabel(
            "neo-pod-desktop\n"
            "Version 1.0.0\n\n"
            "Desktop application for downloading, converting, managing and transferring music to iPod Nano devices."
        )
        about_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        layout.addWidget(about_label)

    def _on_hide_buttons_toggled(self, checked: bool):
        self.hide_library_buttons_changed.emit(checked)

    def _on_browse_output_clicked(self):
        directory = QFileDialog.getExistingDirectory(
            self, "Select Output Directory",
            self.output_dir_input.text()
        )
        if directory:
            self.output_dir_input.setText(directory)

    def load_settings(self, config):
        self.output_dir_input.setText(
            config.get("General", "output_dir",
                       fallback=os.path.join(os.path.expanduser("~"), "Music", "iPod"))
        )
        self.format_combo.setCurrentText(config.get("General", "format", fallback="m4a"))
        self.quality_spin.setValue(config.get_int("General", "quality", fallback=256))
        self.embed_artwork_check.setChecked(
            config.get_boolean("Metadata", "embed_artwork", fallback=True)
        )
        self.clean_temp_check.setChecked(
            config.get_boolean("Advanced", "clean_temp", fallback=True)
        )
        self.auto_detect_check.setChecked(
            config.get_boolean("Device", "auto_detect", fallback=True)
        )
        hide_library_buttons = config.get_boolean("Advanced", "hide_library_buttons", fallback=False)
        self.hide_library_buttons_check.setChecked(hide_library_buttons)

    def save_settings(self, config):
        config.set("General", "output_dir", self.output_dir_input.text())
        config.set("General", "format", self.format_combo.currentText())
        config.set("General", "quality", str(self.quality_spin.value()))
        config.set("Metadata", "embed_artwork", str(self.embed_artwork_check.isChecked()).lower())
        config.set("Advanced", "clean_temp", str(self.clean_temp_check.isChecked()).lower())
        config.set("Device", "auto_detect", str(self.auto_detect_check.isChecked()).lower())
        config.set("Advanced", "hide_library_buttons", str(self.hide_library_buttons_check.isChecked()).lower())

    def refresh_shortcuts_table(self):
        if self.hotkey_manager is None:
            return
        names = self.hotkey_manager.all_action_names()
        self.shortcuts_table.setRowCount(len(names))
        for row, name in enumerate(names):
            label = self.hotkey_manager.get_label(name)
            key = self.hotkey_manager.get_current_key_string(name)
            self.shortcuts_table.setItem(row, 0, QTableWidgetItem(label))
            item = QTableWidgetItem(key if key else "\u2014")
            self.shortcuts_table.setItem(row, 1, item)

    def _on_shortcut_double_clicked(self, row: int, _col: int):
        if self.hotkey_manager is None:
            return
        names = self.hotkey_manager.all_action_names()
        if row < 0 or row >= len(names):
            return
        action_name = names[row]
        current = self.hotkey_manager.get_current_key_string(action_name)
        dialog = KeyCaptureDialog(self, current=current)
        if dialog.exec() == KeyCaptureDialog.DialogCode.Accepted:
            seq = dialog.captured_sequence()
            self.hotkey_manager.set_shortcut_seq(action_name, seq)
            self.refresh_shortcuts_table()

    def _on_reset_shortcuts_clicked(self):
        if self.hotkey_manager is None:
            return
        reply = QMessageBox.question(
            self, "Reset Shortcuts",
            "Reset all keyboard shortcuts to their default values?",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        if reply == QMessageBox.StandardButton.Yes:
            self.hotkey_manager.reset_to_defaults()
            self.refresh_shortcuts_table()
            QMessageBox.information(self, "Done", "Shortcuts reset to defaults.")
