import streamlit as st

from streamlit_option_menu import option_menu
import os
from dotenv import load_dotenv
load_dotenv()

import home, trending, account, your, about, buy_me_a_coffee
st.set_page_config(
        page_title="Pondering",
)


st.markdown(
    """
        <!-- Global site tag (gtag.js) - Google Analytics -->
        <script async src=f"https://www.googletagmanager.com/gtag/js?id={os.getenv('analytics_tag')}"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', os.getenv('analytics_tag'));
        </script>
    """, unsafe_allow_html=True)
print(os.getenv('analytics_tag'))


class MultiApp:

    def __init__(self):
        self.apps = []

    def add_app(self, title, func):

        self.apps.append({
            "title": title,
            "function": func
        })

    def run():
        # app = st.sidebar(
        with st.sidebar:        
            app = option_menu(
                menu_title='Pondering ',
                options=['Home','Account','Trending','Your Posts','about','Buy_me_a_coffee'],
                icons=['house-fill','person-circle','trophy-fill','chat-fill','info-circle-fill'],
                menu_icon='chat-text-fill',
                default_index=1,
                styles={
                    "container": {"padding": "5!important","background-color":'black'},
        "icon": {"color": "white", "font-size": "23px"}, 
        "nav-link": {"color":"white","font-size": "20px", "text-align": "left", "margin":"0px", "--hover-color": "blue"},
        "nav-link-selected": {"background-color": "#02ab21"},}
                
                )

        
        if app == "Home":
            home.app()
        if app == "Account":
            account.app()    
        if app == "Trending":
            trending.app()        
        if app == 'Your Posts':
            your.app()
        if app == 'about':
            about.app()    
        if app=='Buy_me_a_coffee':
            buy_me_a_coffee.app()    
             
          
             
    run()            
         
     like this i wanted the sidebar of my code import pandas as pd
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
import os
import streamlit as st

# Paths to the Word templates and additional DOCX files
TEMPLATE_PATH_NO = r"C:\Users\Administrator\Desktop\Chambers.docx"  # Template for No rows
TEMPLATE_PATH_YES = r"C:\Users\Administrator\Desktop\Chambers - Copy.docx"  # Template for Yes rows
AFTER_DOCX_PATH = r"C:\Users\Administrator\Desktop\new\After.docx"

# Function to append Word documents
def append_docs(doc_list, output_doc):
    combined_doc = Document()
    for doc in doc_list:
        sub_doc = Document(doc)
        for element in sub_doc.element.body:
            combined_doc.element.body.append(element)
    combined_doc.save(output_doc)

def create_individual_document(template_path, data, matter_count, output_path):
    """Create an individual document for a row of data based on a template."""
    doc = Document(template_path)

    identifier_text = f"Matter {matter_count}"

    # Update table content dynamically
    doc.tables[0].cell(1, 0).text = identifier_text
    cell = doc.tables[0].cell(1, 0)
    
    # Formatting
    for paragraph in cell.paragraphs:
        for run in paragraph.runs:
            run.font.name = 'Times New Roman'
            run.font.size = Pt(12)
            run.font.bold = True
            
    cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

    # Populate the document with data
    doc.tables[0].cell(2, 0).text = f" {data['Client Name '].strip()}"
    doc.tables[0].cell(3, 0).text = f" {data['Description  (in 500 words)'].strip()}"
    doc.tables[0].cell(4, 0).text = f" {data['Value '].strip()}"
    doc.tables[0].cell(6, 0).text = f" {data['Lead partners'].strip()}"
    doc.tables[0].cell(7, 0).text = f" {data['Team Members'].strip()}"
    doc.tables[0].cell(8, 0).text = f" {data['Other Firms/counsels Involved'].strip()}"
    doc.tables[0].cell(9, 0).text = f" {data['Current Status (ongoing / completed )'].strip()}"

    # Save the document
    doc.save(output_path)
    return output_path

def populate_chambers(excel_file, output_path):
    """Generate documents based on the Excel input."""
    try:
        df = pd.read_excel(excel_file)
        individual_docs_no = []
        individual_docs_yes = []

        df_no = df[df['Confidential / Publishable '].str.strip().str.lower() == 'no']
        df_yes = df[df['Confidential / Publishable '].str.strip().str.lower() == 'yes']

        for index, row in df_no.iterrows():
            temp_output_path = f"temp_publishable_no_{index}.docx"
            individual_docs_no.append(create_individual_document(TEMPLATE_PATH_NO, row, index + 1, temp_output_path))

        for index, row in df_yes.iterrows():
            temp_output_path = f"temp_publishable_yes_{index}.docx"
            individual_docs_yes.append(create_individual_document(TEMPLATE_PATH_YES, row, index + 1, temp_output_path))

        append_docs(individual_docs_no + [AFTER_DOCX_PATH] + individual_docs_yes, output_path)

        for doc_path in individual_docs_no + individual_docs_yes:
            os.remove(doc_path)

    except Exception as e:
        st.error(f"Error occurred: {e}")

# Placeholder for Legal Era functionality
def populate_legal_era(excel_file):
    st.warning("Legal Era functionality is not implemented yet.")

# Streamlit App
def main():
    st.set_page_config(page_title="Document Automation", layout="wide")

    st.markdown(
        """
        <style>
            /* Sidebar styling */
            [data-testid="stSidebar"] {
                background-color: #fdfcfc";
                 width: 70px !important; # Set the width to your desired value
                padding-top: 20px;
                
            }
            /* Sidebar title */
            [data-testid="stSidebar"] h1 {
                font-size: 22px !important;
                color: black;
                text-align: center;
            }
            /* Sidebar radio buttons */
            .stRadio > label {
                font-size: 18px !important;
                color: #5d3aa0;
                font-weight: bold;
                padding: 10px 5px;
                display: block;
                text-align: left;
            }
            .stRadio div[role="radiogroup"] label {
                font-size: 16px !important;
                margin-bottom: 10px;
                padding: 8px;
                border-radius: 5px;
                transition: background-color 0.3s ease-in-out;
            }
            /* Hover effect */
            .stRadio div[role="radiogroup"] label:hover {
                background-color: #e0e0e0;
            }
        </style>
        """,
        unsafe_allow_html=True,
    )

    st.markdown(
    """
    <style>
        section[data-testid="stSidebar"] {
            width: 50px !important; # Set the width to your desired value
        }
    </style>
    """,
    unsafe_allow_html=True,
)

    st.sidebar.title("S&A SUBMISSIONS")
    pages = {
        "Home": "home",
        "ALB Asia IP Rankings": "alb",
        "Chambers": "chambers",
        "Legal Era": "legal_era",
        "IFLR 1000": "iflr",
        "Legal 500": "legal_500"
    }

    selected_option = st.sidebar.radio("", list(pages.keys()))

    if selected_option == "Home":
        st.header("Welcome to the Document Automation Tool!")
        st.markdown("""
        This tool automates legal document generation for various submissions.
        Currently, forms are under testing, and this is a trial version.
        """)
        st.markdown("Only the BLUEPRINT we will make the changes as per the discussion")

    elif selected_option == "Chambers":
        st.header("Chambers Submission")
        st.markdown("🔧 **This implementation is still in progress. The production version is not yet live.** For testing, use this link: [Click Here](http://localhost:8501/)", unsafe_allow_html=True)

        excel_file = st.file_uploader("Upload Excel File for Chambers", type=["xlsx", "xls"])

        if st.button("Generate Chambers Form"):
            if excel_file:
                output_path = "Chambers_Submission.docx"
                populate_chambers(excel_file, output_path)

                if os.path.exists(output_path):
                    st.success("Chambers Form generated successfully!")
                    with open(output_path, "rb") as f:
                        st.download_button(
                            label="Download Form",
                            data=f,
                            file_name="Chambers.docx",
                            mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
                        )
                else:
                    st.error("Error generating document.")
            else:
                st.error("Please upload an Excel file.")

    elif selected_option == "Legal Era":
        st.header("Legal Era Submission")
        excel_file = st.file_uploader("Upload Excel File for Legal Era", type=["xlsx", "xls"])

        if st.button("Generate Legal Era Form"):
            if excel_file:
                populate_legal_era(excel_file)
                st.success("Processing completed (Placeholder).")
            else:
                st.error("Please upload an Excel file.")

    elif selected_option == "IFLR 1000":
        st.header("IFLR 1000 Submission")
        excel_file = st.file_uploader("Upload Excel File for IFLR 1000", type=["xlsx", "xls"])

        if st.button("Generate IFLR 1000 Form"):
            if excel_file:
                st.success("Processing completed (Placeholder).")
            else:
                st.error("Please upload an Excel file.")

    elif selected_option == "IFLR 1000":
        st.header("IFLR 1000 Submission")
        excel_file = st.file_uploader("Upload Excel File for IFLR 1000", type=["xlsx", "xls"])

        if st.button("Generate IFLR 1000 Form"):
            if excel_file:
                st.success("Processing completed (Placeholder).")
            else:
                st.error("Please upload an Excel file.") 

    elif selected_option == "ALB Asia IP Rankings":
        st.header("Under Development")
        # excel_file = st.file_uploader("Upload Excel File for IFLR 1000", type=["xlsx", "xls"])

        # if st.button("Generate IFLR 1000 Form"):
        #     if excel_file:
        #         st.success("Processing completed (Placeholder).")
        #     else:
        #         st.error("Please upload an Excel file.")
        # 
    elif selected_option == "Legal 500":
        st.header("Under Development")                       

if __name__ == "__main__":
    main()
    in this remove th chmbers populatr code for the chmbers page from this....make it like above so that in chmbers and other foms i can write their fucnotnality when we clcik them