import os
import streamlit as st
from dotenv import load_dotenv

load_dotenv()

# Constants
DATA_FOLDER = "data"
PREVIEW_FOLDER = "Preview"

def get_text_files_content(folder):
    """
    Reads all .txt files from a given folder and
    returns their combined text content.
    """
    text = ""
    if not os.path.exists(folder):
        return text
    for filename in os.listdir(folder):
        if filename.endswith(".txt"):
            file_path = os.path.join(folder, filename)
            with open(file_path, "r", encoding="utf-8") as file:
                text += file.read() + "\n"
    return text

def notes_page():
    st.header("CSS Edge - Notes Viewer :books:")

    subjects = [
        "A Trumped World", "Agri Tax in Punjab", "Assad's Fall in Syria",
        "Elusive National Unity", "Europe and Trump 2.0", "Going Down with Democracy",
        "Indonesia's Pancasila Philosophy", "Pakistan in Choppy Waters",
        "Pakistan's Semiconductor Ambitions", "Preserving Pakistan's Cultural Heritage",
        "Tackling Informal Economy", "Technical Education in Pakistan",
        "The Case for Solidarity Levies", "The Decline of the Sole Superpower",
        "The Power of Big Oil", "Trump 2.0 and Pakistan's Emerging Foreign Policy",
        "Trump and the World 2.0", "Trump vs BRICS", "US-China Trade War",
        "War on Humanity", "Women's Suppression in Afghanistan"
    ]

    # Create dict mapping from subject name -> folder path
    subject_folders = {
        subject: os.path.join(DATA_FOLDER, subject.replace(" ", "_"))
        for subject in subjects
    }
    preview_folders = {
        subject: os.path.join(PREVIEW_FOLDER, subject.replace(" ", "_"))
        for subject in subjects
    }

    # Initialize session state variables
    if "completed_subjects" not in st.session_state:
        st.session_state.completed_subjects = []
    if "current_subject_index" not in st.session_state:
        st.session_state.current_subject_index = 0
    if "grading_enabled" not in st.session_state:
        st.session_state.grading_enabled = False

    # --- CALCULATE AND DISPLAY PROGRESS ---
    total_subjects = len(subjects)
    completed_count = len(st.session_state.completed_subjects)
    progress_fraction = completed_count / total_subjects  # e.g. 0.5 means 50%
    progress_percentage = progress_fraction * 100

    # Show progress in the sidebar
    st.sidebar.title("Your Progress")
    st.sidebar.progress(progress_fraction)
    st.sidebar.write(f"You have completed {completed_count} out of {total_subjects} notes.")
    st.sidebar.write(f"Overall progress: {progress_percentage:.2f}%")

    # Separate completed and unread subjects
    unread_subjects = [sub for sub in subjects if sub not in st.session_state.completed_subjects]
    completed_subjects = st.session_state.completed_subjects

    # Dropdown to filter notes
    filter_option = st.sidebar.selectbox("Filter Notes:", ["All", "Unread", "Read"])

    if filter_option == "Unread":
        displayed_subjects = unread_subjects
    elif filter_option == "Read":
        displayed_subjects = completed_subjects
    else:
        displayed_subjects = subjects

    # If unread are filtered, allow direct jump
    if filter_option == "Unread" and unread_subjects:
        selected_unread_subject = st.sidebar.selectbox("Go to Unread Note:", unread_subjects)
        st.session_state.current_subject_index = subjects.index(selected_unread_subject)

    # Sidebar list of displayed subjects (with read/unread status)
    st.sidebar.subheader("All Subjects")
    for i, subject in enumerate(displayed_subjects):
        status = "✓" if subject in st.session_state.completed_subjects else ""
        st.sidebar.text(f"{i + 1}. {subject} {status}")

    # Show current subject in the sidebar
    selected_subject = subjects[st.session_state.current_subject_index]
    st.sidebar.subheader("Current Subject:")
    st.sidebar.text(selected_subject)

    # --- PREVIEW SECTION ---
    preview_folder_path = preview_folders[selected_subject]
    if os.path.exists(preview_folder_path):
        preview_text = get_text_files_content(preview_folder_path)
        st.subheader("Preview of Notes")
        st.text_area("Preview Content:", preview_text, height=300, disabled=True)
    else:
        st.error(f"No preview available for {selected_subject}.")

    # --- FULL NOTES SECTION ---
    subject_folder_path = subject_folders[selected_subject]
    if os.path.exists(subject_folder_path):
        raw_text = get_text_files_content(subject_folder_path)
        if raw_text:
            st.subheader("Notes")
            st.text_area("Notes Content:", raw_text, height=500, disabled=True)

            # Button to mark as completed
            if selected_subject not in st.session_state.completed_subjects:
                if st.button(f"Mark '{selected_subject}' as Read"):
                    st.session_state.completed_subjects.append(selected_subject)
                    st.success(f"Marked '{selected_subject}' as read!")
                    # Re-run to immediately update progress
                    st.experimental_rerun()

            # Check if all notes have been read
            if len(st.session_state.completed_subjects) == len(subjects):
                st.session_state.grading_enabled = True
                st.sidebar.success("All subjects completed. You can now proceed to the Grading Tool.")
                st.markdown("[Proceed to Grading Tool](https://thecssedge.com/wp-admin/admin.php?page=feedback-dashboard)")

            # Button to go to next subject
            if st.session_state.current_subject_index < len(subjects) - 1:
                if st.button("Go to Next Note"):
                    st.session_state.current_subject_index += 1
                    st.experimental_rerun()
        else:
            st.error(f"No text data found for {selected_subject}.")
    else:
        st.error(f"No data available for {selected_subject}.")

def main():
    st.sidebar.title("Navigation")
    page = st.sidebar.radio("Select a Page:", ["Notes"])

    if page == "Notes":
        notes_page()

if __name__ == "__main__":
    main()