import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QTabWidget, QFileDialog, QTableWidgetItem
from PyQt6.QtGui import QColor
from ui_design import create_upload_tab, create_dashboard_tab, create_analytics_tab, create_help_tab
from data_handler import load_csv, filter_referrals, reset_table
from visualizer import display_graphs

class CCUDashboard(QMainWindow):
    """
    Main GUI Application class, it allowes the users to upload a CSV file, 
    view the patients data and their individual values for each datapoint(such as bmi etc.)
    filter which patients need referral and which dont, and visualize through
    the analytics tab with a few charts the data.
    """
    def __init__(self):
        super().__init__()
        # Set up main window values
        self.setWindowTitle("CCU Patients Data Dashboard")
        self.setGeometry(100, 100, 1500, 1000)
        
        self.tabs = QTabWidget()
        self.setCentralWidget(self.tabs)
        
        self.df = None  # Stores the loaded data 
        self.filtered_df = None  # Stores filtered data for patients that need referral
        
        # Initialize the ui tab using functions imported from the ui_design.py
        self.csvuploading_tab = create_upload_tab(self)
        self.dashboard_tab = create_dashboard_tab(self)
        self.analytics_tab = create_analytics_tab(self)
        self.help_tab = create_help_tab()
        
        # Add tabs to the interface
        self.tabs.addTab(self.csvuploading_tab, "Upload CSV File")
        self.tabs.addTab(self.dashboard_tab, "View Dashboard")
        self.tabs.addTab(self.analytics_tab, "Analytics")
        self.tabs.addTab(self.help_tab, "Help")

    def load_csv_file(self):
        """
        Opens a file dialog to allow the user to select a CSV file.
        Loads the selected CSV file and updates the UI with the data.
        """
        file_path, _ = QFileDialog.getOpenFileName(self, "Open CSV", "", "CSV Files (*.csv)")
        
        if not file_path:  # Ensure a valid file path is selected
            print("No file selected.")
            return
        
        self.file_label.setText(f"You have succesfully uploaded the CSV: {file_path}")
        self.df = load_csv(file_path)   #Load the data from the csv file
        self.filtered_df = self.df.copy()
        self.display_data() #Update the dashboard with the data
        display_graphs(self.df, self.analytics_tab)  # Update graphs

    def filter_referrals(self):
        """Filter to show only patients needing referral."""
        if self.df is not None:
            self.filtered_df = filter_referrals(self.df)
            self.display_data()

    def reset_table(self):
        """Reset the table to show all patients."""
        if self.df is not None:
            self.filtered_df = reset_table(self.df)
            self.display_data()

    def display_data(self):
        """Update the table with the current data."""
        if self.filtered_df is None:
            return

        self.table_widget.setRowCount(self.filtered_df.shape[0])
        self.table_widget.setColumnCount(self.filtered_df.shape[1])
        self.table_widget.setHorizontalHeaderLabels(self.filtered_df.columns)

        for row in range(self.filtered_df.shape[0]):
            for col in range(self.filtered_df.shape[1]):
                cell_value = str(self.filtered_df.iat[row, col])
                item = QTableWidgetItem(cell_value)
                
                # Modify the referral column to identify with red and green colour the outcome
                if "referral" in self.filtered_df.columns and self.filtered_df.columns[col] == "referral":
                    if cell_value == "Need Referral":
                        item.setBackground(QColor(255, 102, 102))  # Red for need Referral
                    elif cell_value == "No Need for Referral":
                        item.setBackground(QColor(144, 238, 144))  # Green for No Need for Referral
                
                self.table_widget.setItem(row, col, item)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = CCUDashboard()
    window.show()
    sys.exit(app.exec())