import os

from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton, QFileDialog

from hdsemg_pipe.config.config_enums import Settings
from hdsemg_pipe.config.config_manager import config


def init_workfolder_widget(parent):
    layout = QVBoxLayout()

    # Information label
    info_label = QLabel("Specify the directory where the application will create and search for a work folder.\n"
                        "This folder will store all files generated by the application.")
    layout.addWidget(info_label)

    # Create a horizontal layout for the work folder path
    workfolder_layout = QHBoxLayout()

    # Label prompting for work folder path
    workfolder_label = QLabel("Work Folder Path:")
    workfolder_layout.addWidget(workfolder_label)

    # QLineEdit for entering the folder path
    workfolder_line_edit = QLineEdit()
    workfolder_line_edit.setPlaceholderText("Enter or select a folder path...")
    workfolder_layout.addWidget(workfolder_line_edit)

    browse_button = QPushButton("Browse")
    workfolder_layout.addWidget(browse_button)

    # QLabel to display the validity indicator
    validity_indicator = QLabel()
    validity_indicator.setFixedWidth(30)
    workfolder_layout.addWidget(validity_indicator)

    # Add the work folder layout to the main layout
    layout.addLayout(workfolder_layout)

    # Function to update the validity indicator based on folder status
    def update_validity():
        folder_path = workfolder_line_edit.text().strip()
        if os.path.isdir(folder_path):
            config.set(Settings.WORKFOLDER_PATH, folder_path)
            validity_indicator.setText("✔")
            validity_indicator.setStyleSheet("color: green; font-size: 20px;")
        else:
            validity_indicator.setText("✖")
            validity_indicator.setStyleSheet("color: red; font-size: 20px;")

    # Update validity whenever the text changes
    workfolder_line_edit.textChanged.connect(update_validity)
    if config.get(Settings.WORKFOLDER_PATH) is not None:
        workfolder_line_edit.setText(config.get(Settings.WORKFOLDER_PATH))
        update_validity()

    def open_folder_dialog():
        # Opens a folder dialog
        folder_path = QFileDialog.getExistingDirectory(parent, "Select Folder")
        if folder_path:
            workfolder_line_edit.setText(folder_path)

    # Connect the browse button to the folder dialog function
    browse_button.clicked.connect(open_folder_dialog)

    return layout
