#  Copyright 2026 European Union
#  Author: Bulgheroni Antonio (antonio.bulgheroni@ec.europa.eu)
#  SPDX-License-Identifier: EUPL-1.2
"""Dialog that lets the user review validation issues and optionally save anyway."""

from __future__ import annotations

from typing import Sequence

from PySide6.QtWidgets import (
    QAbstractItemView,
    QDialog,
    QDialogButtonBox,
    QHeaderView,
    QLabel,
    QTableWidget,
    QTableWidgetItem,
    QVBoxLayout,
    QWidget,
)

from mafw.mafw_errors import ValidationIssue


class ValidationIssuesDialog(QDialog):
    """Present every validation issue and allow the user to cancel or save anyway."""

    def __init__(self, issues: Sequence[ValidationIssue], parent: QWidget | None = None) -> None:
        super().__init__(parent)
        self.setWindowTitle('Validation Issues')
        layout = QVBoxLayout(self)
        layout.addWidget(QLabel('The steering file has validation problems:'))
        self._table = QTableWidget(self)
        self._table.setColumnCount(2)
        self._table.setHorizontalHeaderLabels(['Issue', 'Details'])
        self._table.setRowCount(len(issues))
        self._table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
        self._table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
        for row, issue in enumerate(issues):
            self._table.setItem(row, 0, QTableWidgetItem(issue.__class__.__name__))
            self._table.setItem(row, 1, QTableWidgetItem(str(issue)))
        layout.addWidget(self._table)
        self._adjust_column_widths()
        self._table.resizeColumnsToContents()
        buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel)
        save_button = buttons.button(QDialogButtonBox.StandardButton.Save)
        save_button.setText('Save Anyway')
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

    def _adjust_column_widths(self) -> None:
        """Resize each column once so every issue text fits."""

        header = self._table.horizontalHeader()
        for column in range(self._table.columnCount()):
            header.setSectionResizeMode(column, QHeaderView.ResizeMode.ResizeToContents)
            self._table.resizeColumnToContents(column)
        header.setStretchLastSection(True)
        total_width = sum(header.sectionSize(column) for column in range(self._table.columnCount()))
        scrollbar_width = self._table.verticalScrollBar().sizeHint().width()
        self._table.setMinimumWidth(total_width + scrollbar_width + self._table.verticalHeader().width())
