import streamlit as st
import pandas as pd
import os
import numpy as np
# Load data
companies = pd.read_pickle('jobs-data.pkl')
similarity = pd.read_pickle('similarity.pkl')

# st.write("DataFrame Columns:", df.columns)

# Placeholder for user authentication
def login_frm():
    username = st.text_input('Username')
    password = st.text_input('Password', type='password')
    if st.button('Login'):
        if username == '1' and password == '2':
            st.session_state['authenticated'] = True
            st.success("Logged in successfully!")
        else:
            st.error("Invalid username or password")

# Recommendation Function    
def recommendation(applicants, companies, similarity, num_recommendations=3):
    try:
        recommendations = {}
        applicants['User ID'] = np.arange(len(applicants))
        for i, applicant in enumerate(applicants['User ID']):
            # Get the index of the highest similarity scores for this applicant
            sorted_company_indices = np.argsort(-similarity[i])  # Descending sort of scores
            recommended_companies = companies.iloc[sorted_company_indices]['Major'].values[:num_recommendations]  # Top 3 recommendations
            recommendations[applicant] = recommended_companies
        return recommendations
    except IndexError:
        return []

def send_email(job):
    # Dummy function to simulate email sending
    st.success(f"Job details sent to your email: {job['Title']}")

def export_recommendations(jobs):
    recommendations_df = pd.DataFrame(jobs)
    st.download_button(label="Download Recommendations", data=recommendations_df.to_csv().encode('utf-8'), file_name='recommendations.csv', mime='text/csv')

def setup_session_state():
    if 'authenticated' not in st.session_state:
        st.session_state['authenticated'] = False
    if 'view' not in st.session_state:
        st.session_state['view'] = 'home'
    if 'view_favorites' not in st.session_state:
        st.session_state['view_favorites'] = False
        
def side_bar():
    # Logo
    logo_path = 'logo.jpg'
    if os.path.exists(logo_path):
        st.sidebar.image(logo_path,use_column_width=1,caption="Bridge Jobs - CẦU NỐI ĐẾN TƯƠNG LAI")
    else:
        st.sidebar.write("Logo not found.")

    if st.sidebar.button('Home'):
        st.session_state['view'] = 'home'
    
    st.sidebar.button('Logout', on_click=lambda: st.session_state.update({'authenticated': False}))

def home_frm():
    st.markdown("# PTIT Job Recommendation")

    col1, col2 = st.columns([1, 1])
    # Job Search and Filter
    hard_skills = col1.text_input('Hard Skill, separated by a comma') # hard_skills = "Python, Machine Learning, Data Analysis"
    col1.write("Example hard skills: Python, Machine Learning, Data Analysis")
    soft_skills = col2.text_input('Soft Skill, separated by a comma') # "Teamwork, Communication, Problem-solving"
    col2.write("Example soft skills: Teamwork, Communication, Problem-solving")

    # Get recommendations
    if st.button("Gợi ý"):
        applicants = pd.DataFrame({
            'hard_skill': [hard_skills],
            'soft_skill': [soft_skills]
        })

        # Get recommendations
        if hard_skills and soft_skills:
            jobs = recommendation(applicants, companies, similarity)
            if jobs:
                st.write("Recommended Jobs:")
                for job in jobs.values():
                    for rec in job:
                        st.write(rec)
                st.button("Export Recommendations", on_click=export_recommendations, args=(jobs,), key='export')
            else:
                st.write("No recommendations found.")

def prepare():
    # Initialize session state
    setup_session_state()
    
    # Authentication
    if not st.session_state['authenticated']:
        login_frm()
    else:
        side_bar()
        if st.session_state['view'] == 'home':
            home_frm()
        elif st.session_state['view'] == 'details':
            job_details_frm(st.session_state['job_index'])
        elif st.session_state['view'] == 'favorites':
            view_favorites_frm()

if __name__ == "__main__":
    prepare()