import streamlit as st
from .SendEmail import send_email
import time
import json
import re
import datetime

# reset all inputs
def clear_text():
    st.session_state["full_name"] = ""
    st.session_state["email"] = ""
    st.session_state["stu_major"] = None
    st.session_state["other_major"] = ""
    st.session_state["stu_year"] = None
    st.session_state["skills_selection"] = []
    st.session_state["other_skill"] = ""
    st.session_state["date"] = ""

def is_valid_email(email):
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return re.match(pattern, email)
        
@st.dialog("Review Your Information")
def review(review_info):
    st.write(review_info)
    confirm_btn = st.button("Confirm and Send Email", on_click=clear_text)
    if confirm_btn:
        # save new member info to json file
        try:
            with open('new_members.json', 'r+') as file:
                data = json.load(file)
                data.append(review_info)
                file.seek(0)
                json.dump(data, file, indent=4)
        except FileNotFoundError:
            with open('new_members.json', 'w') as file:
                json.dump([review_info], file, indent=4)
        
        # load email config from app_config.json
        with open('app_config.json') as config_file:
            config = json.load(config_file)
            email_config = config["send_email"]
            
        # send email to new member
        with st.spinner('📧 Sending Email...'):
            send_email(
                sender_email=email_config["sender_email"], 
                password=email_config["password"], 
                to_email=review_info["Email"], 
                subject=f"Welcome to join BuffTeks, {review_info['Full Name']}!"
            ) 
            time.sleep(3)
        st.success("🎉Thanks for submitting your information, you will receive an invitation email shortly. \
                    \nPlease contact Dr.Zhang (czhang@wtamu.edu) if you need any help.")
       
        progress_text = "⏱️ Window will be closed in 10 seconds..."
        my_bar = st.progress(0, text=progress_text)
        for percent_complete in range(99):
            time.sleep(0.1)
            my_bar.progress(percent_complete + 1, text=progress_text)
        time.sleep(1)
        st.rerun()
        
        
def join_us():
    st.title("Join Us")
    st.write("Thank you for your interest in the BuffTeks student organization! Please share your information below, \
        and our Faculty Advisor will send you an invitation to join our Discord channel. \
            If you have any questions, feel free to contact our Faculty Advisor, Dr. Carl Zhang, at czhang@wtamu.edu.")

    full_name = st.text_input("**Full Name**", key="full_name")
    email = st.text_input("**Email**", key="email", placeholder="WT email is preferred")
    major_list =  ["Accounting", "Computer Infromation Systems", "Economics", "Finance", "General Business", "Management", "Marketing", "Other"]
    stu_major = st.radio("**Major/Field of Study**",major_list, key="stu_major")
    if stu_major == "Other":
        other_major = st.text_input("Please specify the other major", key="other_major")
        stu_major = other_major

    year_of_study_list = ["Freshman", "Sophomore", "Junior", "Senior", "Graduate"]
    stu_year = st.radio("**Year of Study**", year_of_study_list, key="stu_year")

    skills_options = ["Programming", "Cybersecurity", "Web Development", "Mobile App Development", "machine Learning/AI", "Data Analysis", "Other"]
    skills_selection = st.multiselect(
        label= "**Technical Skills You Are Interested In (Please check all that apply)**", 
        options = skills_options,
        placeholder = "Choose all that apply",
        key="skills_selection")
    if "Other" in skills_selection:
        other_skill = st.text_input("**Please specify the other skills**", key="other_skill")
        skills_selection.remove("Other")
        skills_selection.append(f"{other_skill}")
        
    next_btn = st.button("Next")
    if next_btn:
        if not is_valid_email(email):
            st.error("Please enter a valid email address.")
            return
        st.session_state.review_info = {
            "Full Name": full_name,
            "Email": email,
            "Major/Field of Study": stu_major,
            "Year of Study": stu_year,
            "Technical Skills": skills_selection,
            "Date": str(datetime.date.today())
        }
        review(review_info=st.session_state.review_info)
