import streamlit as st
import pandas as pd
import numpy as np
import functions
from dotenv import load_dotenv
from openai import OpenAI
import os


# Load environment variables from .env file
load_dotenv()


######### Set up the introduction page: arrange texts (titles, subtitles, lists), images, and structure the layout.

def first_page():

#     # Splits the app page into two parts
#     left_part, right_part = st.columns(2)
#     with left_part:
#         # Display the title using the Markdown syntax
#         st.write("""
#         # GlucoCare Mom 
#         ## Your Guide to Gestational Diabetes Management
#         """)
#     with right_part:
#         # Insert an image :
#         # Open the image file using the open() function from the os package
#         image = open('./images/logo2.png', 'rb').read()

#         # Display the image, with custom size
#         st.image(image, width=300)
#     # End of the split

# #     # Write the introduction text with titles, text and a list using Markdown syntax : 
#     st.write("""
#     Welcome to **GlucoCare Mom**! 🤰

#     Our goal is to help you manage your gestational diabetes with ease and confidence. With our user-friendly tools and personalized advice, you'll be equipped to navigate this journey smoothly. Let's make managing gestational diabetes a breeze! 💪

#     ### Important Information
#     - **Please consult your healthcare provider** for expert medical advice. 🩺
#     - **Keep track of your glucose levels** regularly. 📈
#     - **Follow a healthy diet** tailored to your needs. 🥗

#     For any questions or assistance, feel free to reach out. We're here to support you every step of the way. 🌟

#     """)
# # # #--------------------------

# # # # ######### Read/upload data

#     # Create a widget to allow the user to upload a .csv file : 
#     # Return an error if not a .csv file
#     # We will upload the data file `example_data_1_subject.csv` in the ./cgm_data folder
#     uploaded_file = st.file_uploader("Add your glucose data (as CSV file)", type="csv")    

#     if uploaded_file is not None:
#         data = pd.read_csv(uploaded_file) # Read the data using Pandas.read_csv() function
#         data["Time"] = pd.to_datetime(data["Time"]) # We can work with the data just like in any Python code

#         # Since he CGM data was successfully uploaded :
#         st.success("Data uploaded successfully!")  # Show a 'success' widget 
#         st.session_state.data = data   # Store the data in the Session State
#         st.session_state.uploaded = True  # Keep in the Session state that it was successfully uploaded.

# # # #--------------------------

# # # ######### Create an interactive questionnaire for health data collection

#         # The questionnaire consists of a series of widgets that enable users to provide input.
#         # Users are not required to answer every question.
#         # In order to manage that, we nitialize the questionnaire variables
#         # in order to allow the user to skip questions
#         age=None
#         weeks_pregnant=None
#         height=None
#         weight=None
#         current_symptoms=None

#         # Create a dictionnary to store the health information
#         personal_data = {}
        
#         # Ask for personal info 
#         st.write("""
#         # We need some informations about you ! 
#         """)


#         weeks_pregnant = st.text_input("In which week of pregnancy are you ?") # Create a text entry widget (single line)
#         if weeks_pregnant is not None and weeks_pregnant.strip() != "":  # We check if an information is given
#             personal_data["pregnany_week"] = weeks_pregnant              # and store it into the healh information dictionnary.

#         age = st.text_input("How old are you ?")
#         if age is not None and age.strip() != "":
#             personal_data["age"] = age

#         height = st.text_input("What is your height ?")
#         if height is not None and height.strip() != "":
#             personal_data["height"] = height
        
#         weight = st.text_input("What is your actual weight ?")
#         if weight is not None and weight.strip() != "":
#             personal_data["weight"] = weight
        
#         current_symptoms = st.text_input("Do you have any current symptoms ? ")
#         if current_symptoms is not None and current_symptoms.strip() != "":
#             personal_data["current_symptoms"] = current_symptoms

#         medications = st.text_area("List any medications or supplements you are currently taking:") # Create a 'text area' widget (allows long text inputs)
#         if medications is not None and medications.strip() != "":
#             personal_data["medications"] = medications
        
#         nausea_level = st.slider('Rate your nausea level', min_value=0, max_value=10) # Create slider widget : allows to enter numbers without having to type them explicitly.
#         fatigue_level = st.slider('Rate your fatigue level', min_value=0, max_value=10) # The user can only enter a natural number, in [[min_value, max_value]]
#         sleep_quality = st.slider('Rate your sleep quality', min_value=0, max_value=10)
        
#         # Since the sliders already have a value by default, we can store the input without having to verify them.
#         personal_data["nausea_level"] = nausea_level
#         personal_data["fatigue_level"] = fatigue_level
#         personal_data["sleep_quality"] = sleep_quality

#         exercise_frequency = st.radio("Did you do some physical activity recently?", ["Yes", "No"]) # Create a radio widget (button)
#         personal_data["exercise_recently"] = exercise_frequency

#         # Create a 'multiple answer' widget, with predefined values.
#         mood_options = ["Happy", "Sad", "Anxious", "Angry", "Excited", "Calm"]
#         selected_mood = st.multiselect('Mood', mood_options) 
#         personal_data["mood"] = selected_mood


#         # End of the questionnaire
#         # We save the health information dictionnary within the Session State
#         st.session_state.personal_data = personal_data


#         if st.button("Show the data"): # If the user clicks on the button,

#             # We store the information in the Session State that we will have to launch the second page when the application is re-executed
#             st.session_state.show_results = True 

    return None
# # #--------------------------


# # ######### Set up the second to display the data analysis results.

def second_page():

#     # Before initializing the second page, we want to ensure that
#     # the CGM data file is stored in the State 
#     if 'data' in st.session_state and st.session_state.uploaded == True : # Syntax depending on the variable type in the Sesssion State

#         # First, we start with the creation of a sidebar
#         # Shows the logo and titles
#         image = open('./images/logo2.png', 'rb').read()
#         st.sidebar.image(image, width=100)

#         st.sidebar.write("""
#         # GlucoCare Mom 
#         ## Your Guide to Gestational Diabetes Management
#         """)

#         st.sidebar.header("Health Tips")
#         st.sidebar.info("💡 Tip: Monitor your blood glucose levels regularly to manage your gestational diabetes effectively.")

#         # Sidebar with recipes
#         st.sidebar.header("Diabetes Plate Method")
#         image2 = open('./images/platemethod.png', 'rb').read()
#         st.sidebar.image(image2, width=300)
#         st.sidebar.write("""
#         1. Fill half your plate with non-starchy vegetables
#         2. One quarter of the plate with protein foods  
#         3. Last quarter with carbohydrate foods
#         4. Top it off with a glass of water or another zero-calorie drink                                                 
#         """)
#         st.sidebar.markdown ("[More about the Diabetes Plate Method](https://www.diabetesfoodhub.org/articles/what-is-the-diabetes-plate-method)")

#         st.sidebar.header("Superstar foods 🌟 good for diabetes and pregnancy")
#         st.sidebar.markdown("""
#         Superfoods like:
#         - Beans
#         - Dark green leafy vegetables
#         - Citrus fruits
#         - Berries
#         - Tomatoes
#         - Fish high in omega-3 fatty acids
#         - Nuts
#         - Whole grains
#         - Milk and yogurt

#         🥦🍊🍓
#         """)

#         st.sidebar.markdown ("[Learn more about diabetes superfoods](https://diabetes.org/food-nutrition/food-and-blood-sugar/diabetes-superstar-foods)")

#         st.sidebar.header("Healthy Recipes")
#         st.sidebar.write("**Breakfast:** Oatmeal with berries and nuts")
#         st.sidebar.write("**Lunch:** Grilled chicken salad with a variety of vegetables (spinach, cherry tomatoes, bell peppers and cucumber)")
#         st.sidebar.write("**Dinner:** Baked salmon with quinoa and steamed broccoli")

#         st.sidebar.subheader("More Recipes")
#         st.sidebar.markdown("[Recipes from Diabetes Food Hub®](https://www.diabetesfoodhub.org/diabetes-diabetic-breakfast-recipes.html)")

#         st.sidebar.info("💡 Remember to speak with your healthcare provider or a dietitian to create a balanced meal plan tailored to your specific needs during pregnancy. 🌟🤰")

#         # End of the sidebar setup

# #--------------------------

# ######### Data analysis and data visualization

#         # Plot the glucose graph using the plot_glucose_graph function (see the functions.py file)
#         st.write("### Here are your glucose levels : ")
#         functions.plot_glucose_graph(st.session_state.data) 

#         # Display the table with custom formatting
#         st.write("**Glucose Range Summary:**")
#         glucose_ranges= functions.calculate_glucose_range(st.session_state.data) # returns glucose ranges (see the functions.py file)
#         df_glucose_ranges = pd.DataFrame(glucose_ranges)
#         # Rename rows (index)
#         df_glucose_ranges = df_glucose_ranges.rename(index={0: '', 1: 'Time/Day', 2: '% Time in a Day'})
#         # Define column-specific background colors
#         column_colors = {
#             'Very High': 'red',  
#             'High': 'pink',   
#             'Target Range': 'green',
#             'Low': 'yellow' ,  
#             'Very Low': 'orange' 
#         }

#         # Display the table of glucose range with custom styling
#         df_formatted = df_glucose_ranges.applymap(lambda x: '{:.2f}'.format(x) if isinstance(x, float) else x)
#         st.table(functions.style_table(df_formatted, column_colors))

#         # Compute glucose metrics
#         if "metrics" not in st.session_state :
#             with st.spinner('Calculating glucose metrics...'):  # Display a spinner during the loading. 

#                 # We store the glucose metrics in the session state
#                 st.session_state.metrics = functions.calculate_glucose_metrics(st.session_state.data) # Compute glucose metrics (see the functions.py file)
#                 st.session_state.hyper_episodes = functions.identify_hyperglycemia_episodes(st.session_state.data) # Compute hyperglycemia episodes (see the functions.py file)
        
# #--------------------------

# ######### Create an AI-powered Chatbot

#         # Display insights using an LLM based on the provided health information
#         # There are two levels of explanations : 
#         #  - "Basic" if the user want simple, straightforward explanations
#         #  - "Advanced" using more technical explanations.
#         # Once chosen, the LLM provides an insight, we store it into the Session State,
#         # Such that once generated, we don't generate it a second time, and allow the user to switch between the Basic and Advanced insights.
#         st.write("### Insights \n ")
#         option = st.selectbox("Choose a level of complexity", ["Basic", "Advanced"]) # Set a selectbox widget to chose the level of explanation

#         # Create the session state keys for both options
#         basic_key = "insight_text_basic"
#         advanced_key = "insight_text_advanced"

#         # Initialize any missing keys
#         if basic_key not in st.session_state:
#             st.session_state[basic_key] = None
#         if advanced_key not in st.session_state:
#             st.session_state[advanced_key] = None

#         # Get the current key based on selection
#         current_key = f"insight_text_{option.lower()}"

#         # Only generate the insight if not already generated
#         if st.session_state[current_key] is None:
#             with st.spinner("Almost there 🤰✨ we're analysing your glucose levels..."):
#                 insight = functions.generate_insight(
#                     st.session_state.metrics,
#                     st.session_state.personal_data,
#                     st.session_state.hyper_episodes,
#                     level=option)
#                 st.session_state[current_key] = insight

#         # Display the insight for the selected option
#         st.write(st.session_state[current_key])

#         # Add the chatbot feature (see the functions.py file)
#         st.write("### GlucoCare assistant 👩🏼‍⚕️ \n ")
#         functions.access_chatbot(st.session_state.metrics, st.session_state.personal_data, st.session_state.hyper_episodes) # (see the functions.py file)

#     else:

#         # If no data was uploaded or an error happened during the uploading
#         # We tells the user with a warning.
#         st.warning("No data uploaded yet.")

    return None




# ######### Control the page flow
# There are different ways to control the page flow, 
# We chose to set a condition test, to allow the integration of more pages in the future, 
# and control the flow outside of the page functions


# Ensure the user remains on the first page until the user asks to see the analyses results
if "show_results" not in st.session_state or st.session_state.show_results is None:
    # The user didn't ask to see the results yet, we stay on the first page
    first_page()
else:
    # The user asked to see the analyses results : we display the second page.
    second_page()

#--------------------------