import streamlit as st
from firebase_admin import firestore
import datetime

def app():
    if 'db' not in st.session_state:
        st.session_state.db = ''

    db = firestore.client()
    st.session_state.db = db

    ph = ''
    if st.session_state.username == '':
        ph = 'Login to be able to post!!'
    else:
        ph = 'Post your Work'

    post = st.text_area(label=' :orange[+ New Key Work Highlight]', placeholder=ph, height=None, max_chars=1000)

    if st.button('Post', use_container_width=True):
        if post != '':
            info = db.collection('Posts').document(st.session_state.username).get()
            current_time = datetime.datetime.now()

            if info.exists:
                info = info.to_dict()
                if 'Content' in info.keys():
                    pos = db.collection('Posts').document(st.session_state.username)
                    pos.update({
                        u'Content': firestore.ArrayUnion([u'{}'.format(post)]),
                        'Last Modified': current_time
                    })
                else:
                    data = {"Content": [post], 'Username': st.session_state.username, 'Last Modified': current_time}
                    db.collection('Posts').document(st.session_state.username).set(data)
            else:
                data = {"Content": [post], 'Username': st.session_state.username, 'Last Modified': current_time}
                db.collection('Posts').document(st.session_state.username).set(data)

            st.success('Work uploaded!!')

    st.header(' :violet[Latest Work Highlights] ')

    # Month selection
    month_selection = st.selectbox("Select Month", ["All", "January", "February", "March", "April", "May", "June", 
                                                     "July", "August", "September", "October", "November", "December"])

    docs = db.collection('Posts').get()
    filtered_docs = []

    # Filter documents based on the selected month
    selected_month = month_selection.lower()
    for doc in docs:
        d = doc.to_dict()
        d['Last Modified'] = d.get('Last Modified', datetime.datetime.now())  # Fallback in case it doesn't exist
        # Store all the posts for the displayed month
        if selected_month == "all" or d['Last Modified'].strftime("%B").lower() == selected_month:
            filtered_docs.append(d)

    # Sort by last modified date
    filtered_docs.sort(key=lambda x: x['Last Modified'], reverse=True)

    # Create a scrollable container
    with st.container():
        if filtered_docs:
            for d in filtered_docs:
                # Display each content item in the Content array
                for content in d['Content']:
                    try:
                        st.markdown("""
                            <style>
                            .stTextArea [data-baseweb=base-input] [disabled=""]{
                                -webkit-text-fill-color: black;
                            }
                            </style>
                            """, unsafe_allow_html=True)

                        st.text_area(label=':green[Posted by:] '+':orange[{}]'.format(d['Username']), 
                                      value=content, height=200, disabled=True)
                        st.write(f"**Date Posted:** {d['Last Modified'].strftime('%Y-%m-%d %H:%M:%S')}")
                    except Exception as e:
                        st.write(f"Error displaying post: {e}")
        else:
            st.write("No posts available for this month.")     in this the date posted is modifying each time we add a new post for all other exusting post also ...i wanted it to be the dtae and time at the time of posting that