"""Builder for snapshot and storage actions section."""

from __future__ import annotations

from PyQt6.QtWidgets import (
    QGridLayout,
    QGroupBox,
    QHBoxLayout,
    QLabel,
    QLineEdit,
    QPushButton,
    QSizePolicy,
    QSpinBox,
    QVBoxLayout,
)


def build_data_actions_group(owner) -> QGroupBox:
    """Create snapshot save controls section."""
    group = QGroupBox("Data Actions")
    layout = QVBoxLayout(group)
    layout.setSpacing(8)
    data_defaults = owner._gui_defaults.data_actions

    save_button = QPushButton("Save Dataset")
    save_button.clicked.connect(owner._save_snapshot)
    save_button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
    save_vna_json_button = QPushButton("Save JSON")
    save_vna_json_button.clicked.connect(owner._save_vna_history_json)
    save_vna_json_button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
    remove_last_button = QPushButton("Remove Last Measurement")
    remove_last_button.clicked.connect(owner._remove_last_runtime_history)
    remove_last_button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
    capture_tmp_reference_button = QPushButton("Capture Tmp Reference")
    capture_tmp_reference_button.clicked.connect(owner._capture_tmp_reference)
    capture_tmp_reference_button.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed)
    owner._save_count = QSpinBox()
    owner._save_count.setMinimum(1)
    owner._save_count.setMaximum(10_000)
    owner._save_count.setValue(int(data_defaults.save_count))

    button_grid = QGridLayout()
    button_grid.setHorizontalSpacing(8)
    button_grid.setVerticalSpacing(8)
    button_grid.addWidget(save_button, 0, 0)
    button_grid.addWidget(save_vna_json_button, 0, 1)
    button_grid.addWidget(remove_last_button, 1, 0)
    button_grid.addWidget(capture_tmp_reference_button, 1, 1)
    button_grid.setColumnStretch(0, 1)
    button_grid.setColumnStretch(1, 1)
    layout.addLayout(button_grid)

    count_row = QHBoxLayout()
    count_row.setSpacing(8)
    count_row.addWidget(QLabel("Number of Measurements to Save"))
    count_row.addWidget(owner._save_count)
    count_row.addStretch(1)
    layout.addLayout(count_row)

    path_row = QHBoxLayout()
    path_row.setSpacing(8)
    owner._save_path_input = QLineEdit(str(data_defaults.save_path))
    browse_button = QPushButton("Browse")
    browse_button.clicked.connect(owner._browse_save_path)
    path_row.addWidget(QLabel("Path"))
    path_row.addWidget(owner._save_path_input, stretch=1)
    path_row.addWidget(browse_button)
    layout.addLayout(path_row)

    name_row = QHBoxLayout()
    name_row.setSpacing(8)
    owner._save_name_input = QLineEdit(str(data_defaults.save_name))
    name_row.addWidget(QLabel("Name"))
    name_row.addWidget(owner._save_name_input, stretch=1)
    layout.addLayout(name_row)
    return group
