import streamlit as st
import pickle
from html_information2 import html2

st.set_page_config(layout="wide")

# Function to load pickle files
def read_pickle_files(pickle_file):
    with open(pickle_file, 'rb') as f:
        return pickle.load(f)

# Load the necessary pickle files
cross_sell_data = read_pickle_files("fynd.cross_sell_recommendations-000000000000000000000001s.pkl")
upsell_data = read_pickle_files("fynd.up_sell_recommendations_000000000000000000000002s.pkl")
uid_name_pairs = read_pickle_files("uid_name_pairs.pkl")
uid_image_html_pairs = read_pickle_files("uid_image_html_pairs.pkl")
item_costs_sephora_data = read_pickle_files("sephora_prices.pkl")


# Create a mapping from product_id to product name for dropdown
product_name_to_id = {name: uid for name, uid in uid_name_pairs.items()}
product_id_to_name = {uid: name for name, uid in uid_name_pairs.items()}

# Function to extract product list from recommendation data
def extract_product_list(recommendation_data):
    product_ids = [entry['product_id'] for entry in recommendation_data]
    # Map the product IDs to names for the dropdown
    return [product_id_to_name[product_id] for product_id in product_ids if product_id in product_id_to_name]

# Extract recommendations for a specific product_id
def get_recommendations(product_id, recommendation_data):
    for product in recommendation_data:
        if product['product_id'] == product_id:
            return product['recommendations']
    return []

# Streamlit App Layout
st.title("Cross-Sell & Up-Sell Recommendations")

# Dropdown for selecting recommendation type
recommendation_type = st.selectbox("Select recommendation type:", ["Cross-sell", "Up-sell"])

# Choose the appropriate data based on recommendation type
if recommendation_type == "Cross-sell":
    recommendations_data = cross_sell_data
elif recommendation_type == "Up-sell":
    recommendations_data = upsell_data

# Get the list of product names for the dropdown
product_list = extract_product_list(recommendations_data)

# Dropdown for selecting a product by name
selected_product_name = st.selectbox("Select a product:", product_list)

# Get the selected product's ID using the name
selected_product_id = product_name_to_id.get(selected_product_name)

# Display the image of the selected product using the image URL
if selected_product_id:
    #st.write(selected_product_id)
    #st.subheader(f"Selected Product: {selected_product_name}")
    
    # Check if the product's ID has an associated image HTML and use the image URL
    if selected_product_id in uid_image_html_pairs:
        image_url = uid_image_html_pairs[selected_product_id]
        st.image(image_url, use_column_width=False, width=450)  # Set width to make image smaller
        items_cost_is = item_costs_sephora_data[str(selected_product_id)]
        st.write("Product Price:",str(items_cost_is) )


# Display recommendations for the selected product
if selected_product_id:
    recommendations = get_recommendations(selected_product_id, recommendations_data)
    reccomendation_names = []
    reccomendation_images = []
    reccomendation_costs = []
    # reccomendation_ids = [recommendations.get("product_id","item missing") for item in recommendations]
    # item_costs_sephora = [item_costs_sephora_data.get(item, "cost missing") for item in reccomendation_ids]

    if recommendations:
        #st.subheader(f"Recommendations:")
        if len(recommendations)>10:
            recommendations= recommendations[:10]
        else:
            pass

        for recommendation in recommendations:
            product_name = recommendation.get('product_name')
            recommended_product_id = recommendation.get('product_id')
            recommended_product_cost = item_costs_sephora_data.get(str(recommended_product_id), "item missing")

            # Display the image of each recommended product using the image URL
            if recommended_product_id in uid_image_html_pairs:
                recommended_image_url = uid_image_html_pairs[recommended_product_id]
                #st.image(recommended_image_url, caption=product_name, use_column_width=False, width=150)  # Set width to make images smaller

            reccomendation_names.append(product_name)
            reccomendation_images.append(recommended_image_url)
            reccomendation_costs.append(recommended_product_cost)

            # Display the product name
    else:
        st.write("No recommendations found for this product.")
    
    mid_section = ""
    for index, value in enumerate(reccomendation_names):
        
        # Use <br> to display each line separately
        mid_section += f"""<div class="item">
                            <div id="image-container"><img src='{reccomendation_images[index]}' /></div>
                            <p style="font-size: 16px; font-weight: bold; white-space: normal; word-wrap: break-word;">{str(reccomendation_names[index])}</p>
                            <p>Product Price: {reccomendation_costs[index]}</p>
                        </div>"""
    mid_html = html2 + mid_section + """</div></div></body>"""
    st.markdown(mid_html, unsafe_allow_html=True)