from pathlib import Path

from PyQt6.QtWidgets import (
    QMainWindow,
    QWidget,
    QVBoxLayout,
    QHBoxLayout,
    QLabel,
    QPushButton,
    QFileDialog,
    QMessageBox,
    QTableView,
    QComboBox,
)

from analysis.io import load_csv
from analysis.stats import basic_statistics
from gui.dataframe_model import DataFrameModel
from gui.mpl_canvas import MplCanvas


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("Wood Analysis Tool")
        self.resize(1200, 700)

        central = QWidget()
        main_layout = QVBoxLayout()

        # ---- Controls ----
        controls = QHBoxLayout()

        load_button = QPushButton("Load CSV")
        load_button.clicked.connect(self.load_csv_file)

        self.column_selector = QComboBox()
        self.column_selector.setEnabled(False)

        stats_button = QPushButton("Compute Statistics")
        stats_button.clicked.connect(self.compute_stats)
        stats_button.setEnabled(False)

        plot_button = QPushButton("Plot Histogram")
        plot_button.clicked.connect(self.plot_histogram)
        plot_button.setEnabled(False)

        controls.addWidget(load_button)
        controls.addWidget(QLabel("Column:"))
        controls.addWidget(self.column_selector)
        controls.addWidget(stats_button)
        controls.addWidget(plot_button)

        # ---- Outputs ----
        self.status_label = QLabel("No file loaded.")
        self.stats_label = QLabel("")
        self.stats_label.setStyleSheet("font-size: 14px;")

        self.table = QTableView()
        self.canvas = MplCanvas(self)

        main_layout.addLayout(controls)
        main_layout.addWidget(self.status_label)
        main_layout.addWidget(self.table)
        main_layout.addWidget(self.stats_label)
        main_layout.addWidget(self.canvas)

        central.setLayout(main_layout)
        self.setCentralWidget(central)

        # ---- State ----
        self.df = None
        self.model = None
        self.stats_button = stats_button
        self.plot_button = plot_button

    def load_csv_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "Select CSV file",
            "",
            "CSV files (*.csv)"
        )

        if not file_path:
            return

        try:
            path = Path(file_path)
            self.df = load_csv(path)

            self.model = DataFrameModel(self.df)
            self.table.setModel(self.model)

            self.column_selector.clear()
            self.column_selector.addItems(self.df.columns)
            self.column_selector.setEnabled(True)

            self.stats_button.setEnabled(True)
            self.plot_button.setEnabled(True)

            self.status_label.setText(
                f"Loaded: {path.name} ({len(self.df)} rows)"
            )
            self.stats_label.setText("")
            self.canvas.ax.clear()
            self.canvas.draw()

        except Exception as e:
            QMessageBox.critical(self, "Error loading file", str(e))

    def compute_stats(self):
        column = self.column_selector.currentText()

        try:
            stats = basic_statistics(self.df, column)

            self.stats_label.setText(
                f"<b>Statistics for '{column}'</b><br>"
                f"Mean: {stats['mean']:.2f}<br>"
                f"Std: {stats['std']:.2f}<br>"
                f"Min: {stats['min']:.2f}<br>"
                f"Max: {stats['max']:.2f}"
            )

        except Exception as e:
            QMessageBox.critical(self, "Statistics error", str(e))

    def plot_histogram(self):
        column = self.column_selector.currentText()

        try:
            self.canvas.ax.clear()
            self.canvas.ax.hist(self.df[column].dropna(), bins=15)
            self.canvas.ax.set_title(f"Histogram of {column}")
            self.canvas.ax.set_xlabel(column)
            self.canvas.ax.set_ylabel("Frequency")
            self.canvas.fig.tight_layout()
            self.canvas.draw()

        except Exception as e:
            QMessageBox.critical(self, "Plot error", str(e))
