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'
    
    # Create the template with uppercase field labels
    default_template = """MATTER NAME : 

Overview: 

Role of S&A: 

Outcome/Impact: 
"""
    
    # Store the post submission status in session_state
    if 'post_submitted' not in st.session_state:
        st.session_state.post_submitted = False
    
    # Use the template as the default value in the text area
    # Reset to default template if a post was just submitted
    if st.session_state.post_submitted:
        post = st.text_area(label=' :orange[+ New Key Work Highlight]', 
                        value=default_template,
                        height=200, 
                        max_chars=1000)
        st.session_state.post_submitted = False
    else:
        post = st.text_area(label=' :orange[+ New Key Work Highlight]', 
                        value=default_template,
                        height=200, 
                        max_chars=1000)
    
    if st.button('Post', use_container_width=True):
        if post != '' and post != default_template:
            current_time = datetime.datetime.now()
            
            # Structure the post with its own timestamp
            new_post = {
                "content": post,
                "timestamp": current_time
            }
            
            info = db.collection('Posts').document(st.session_state.username).get()
            
            if info.exists:
                info = info.to_dict()
                if 'Posts' in info.keys():
                    pos = db.collection('Posts').document(st.session_state.username)
                    # Add the new post to the array with its own timestamp
                    pos.update({
                        u'Posts': firestore.ArrayUnion([new_post]),
                        'Last Modified': current_time
                    })
                else:
                    data = {"Posts": [new_post], 'Username': st.session_state.username, 'Last Modified': current_time}
                    db.collection('Posts').document(st.session_state.username).set(data)
            else:
                data = {"Posts": [new_post], 'Username': st.session_state.username, 'Last Modified': current_time}
                db.collection('Posts').document(st.session_state.username).set(data)
            
            st.success('Work uploaded!!')
            # Set flag to reset the text area on next rerun
            st.session_state.post_submitted = True
            # Use the current rerun function instead of experimental_rerun
            st.rerun()
    
    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()
    all_posts = []
    
    # Extract all posts with their metadata
    for doc in docs:
        d = doc.to_dict()
        username = d.get('Username', '')
        
        # Handle the case for existing data that might have 'Content' instead of 'Posts'
        if 'Posts' in d:
            posts = d['Posts']
            for post_item in posts:
                # For new structured posts
                if isinstance(post_item, dict) and 'content' in post_item and 'timestamp' in post_item:
                    all_posts.append({
                        'content': post_item['content'],
                        'timestamp': post_item['timestamp'],
                        'username': username
                    })
        # Handle legacy data format
        elif 'Content' in d:
            posts = d['Content']
            doc_timestamp = d.get('Last Modified', datetime.datetime.now())
            for post_content in posts:
                all_posts.append({
                    'content': post_content,
                    'timestamp': doc_timestamp,  # Using the document timestamp for legacy posts
                    'username': username
                })
    
    # Filter and sort posts
    selected_month = month_selection.lower()
    filtered_posts = []
    
    for post in all_posts:
        if selected_month == "all" or post['timestamp'].strftime("%B").lower() == selected_month:
            filtered_posts.append(post)
    
    # Helper function to handle different timestamp formats
    def get_timestamp_for_sorting(post):
        ts = post['timestamp']
        
        # For datetime objects and objects with timestamp methods (like DatetimeWithNanoseconds)
        if hasattr(ts, 'timestamp'):
            try:
                # Convert to timestamp first then to datetime to standardize
                return datetime.datetime.fromtimestamp(ts.timestamp())
            except (AttributeError, TypeError):
                # If timestamp() exists but doesn't work as expected
                pass
        
        # If it's a standard datetime
        if isinstance(ts, datetime.datetime):
            return ts
        
        # If it's a string, try to convert it to datetime
        elif isinstance(ts, str):
            try:
                return datetime.datetime.fromisoformat(ts)
            except ValueError:
                try:
                    return datetime.datetime.strptime(ts, '%Y-%m-%d %H:%M:%S')
                except ValueError:
                    # Return a default datetime if conversion fails
                    return datetime.datetime(1970, 1, 1)
        
        # Return a default datetime for any other case
        return datetime.datetime(1970, 1, 1)
    
    # Sort by timestamp, newest first
    filtered_posts.sort(key=get_timestamp_for_sorting, reverse=True)
    
    # Add CSS to make field labels bold
    st.markdown("""
        <style>
        .post-container {
            max-height: 600px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
        }
        .post-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 5px;
        }
        .stTextArea [data-baseweb=base-input] [disabled=""] {
            -webkit-text-fill-color: black;
        }
        /* Custom styling for text area */
        textarea {
            font-family: sans-serif;
        }
        /* Bold label fields in text area */
        textarea::placeholder {
            font-weight: bold;
        }
        </style>
    """, unsafe_allow_html=True)
    
    # Display posts in a scrollable container
    with st.container():
        if filtered_posts:
            with st.container():
                for post in filtered_posts:
                    try:
                        # Custom header with username and date on the same line
                        timestamp_display = post['timestamp']
                        # Make sure timestamp is formatted properly for display
                        if hasattr(timestamp_display, 'strftime'):
                            formatted_date = timestamp_display.strftime('%Y-%m-%d %H:%M')
                        else:
                            # Fallback if timestamp is not a datetime object
                            formatted_date = str(timestamp_display)
                            
                        st.markdown(
                            f"""<div class="post-header">
                                <span style="color:orange">Posted by: {post['username']}</span>
                                <span style="color:gray">Date: {formatted_date}</span>
                            </div>""", 
                            unsafe_allow_html=True
                        )
                        
                        # Post content
                        st.text_area("", value=post['content'], height=200, disabled=True)
                        st.markdown("---")  # Divider between posts
                    except Exception as e:
                        st.write(f"Error displaying post: {e}")
        else:


            st.write("No posts available for this month.")   in this along with month i wanted one more filet for names 

import streamlit as st
from firebase_admin import firestore

  
def app():
    db=firestore.client()


    try:
        st.title('Posted by: '+st.session_state['username'] )

            
        result = db.collection('Posts').document(st.session_state['username']).get()
        r=result.to_dict()
        content = r['Content']
            
        
        def delete_post(k):
            c=int(k)
            h=content[c]
            try:
                db.collection('Posts').document(st.session_state['username']).update({"Content": firestore.ArrayRemove([h])})
                st.warning('Post deleted')
            except:
                st.write('Something went wrong..')
                
        for c in range(len(content)-1,-1,-1):
            st.text_area(label='',value=content[c])
            st.button('Delete Post', on_click=delete_post, args=([c] ), key=c)        

        
    except:
        if st.session_state.username=='':
            st.text('Please Login first')            u can get the userbames for the list like  this