import streamlit as st
import pandas as pd
from streamlit_float import *
from .discourse_process import process_discourse_input
from ..chatbot.chatbot import initialize_chatbot
from ..database.database_oldFromV2 import store_discourse_analysis_result
from ..text_analysis.discourse_analysis import perform_discourse_analysis
from ..utils.widget_utils import generate_unique_key

def display_discourse_interface(lang_code, nlp_models, t):
    st.subheader(t['discourse_title'])

    text_input = st.text_area(
        t['warning_message'],
        height=150,
        key=generate_unique_key("discourse", "text_area")
    )

    if st.button(
        t['results_title'],
        key=generate_unique_key("discourse", "analyze_button")
    ):
        if text_input:
            # Aquí iría tu lógica de análisis morfosintáctico
            # Por ahora, solo mostraremos un mensaje de placeholder
            st.info(t['analysis_placeholder'])
        else:
            st.warning(t['no_text_warning'])

'''
def display_discourse_interface(lang_code, nlp_models, t):
    st.subheader(t['title'])

    # Inicializar el chatbot si no existe
    if 'discourse_chatbot' not in st.session_state:
        st.session_state.discourse_chatbot = initialize_chatbot('discourse')

    # Mostrar el historial del chat
    chat_history = st.session_state.get('discourse_chat_history', [])
    for message in chat_history:
        with st.chat_message(message["role"]):
            st.write(message["content"])
            if "visualization" in message:
                st.pyplot(message["visualization"])

    # Input del usuario
    user_input = st.chat_input(t['discourse_initial_message'], key=generate_unique_key('discourse', st.session_state.username))

    if user_input:
        # Procesar el input del usuario
        response, visualization = process_discourse_input(user_input, lang_code, nlp_models[lang_code], st.session_state.get('file_contents'), t)

        # Actualizar el historial del chat
        chat_history.append({"role": "user", "content": user_input})
        chat_history.append({"role": "assistant", "content": response, "visualization": visualization})
        st.session_state.discourse_chat_history = chat_history

        # Mostrar el resultado más reciente
        with st.chat_message("assistant"):
            st.write(response)
            if visualization:
                st.pyplot(visualization)

    # Botón para limpiar el historial del chat
    if st.button(t['clear_chat'], key=generate_unique_key('discourse', 'clear_chat')):
        st.session_state.discourse_chat_history = []
        st.rerun()

    # Sección para cargar archivos
    col1, col2 = st.columns(2)
    with col1:
        uploaded_file1 = st.file_uploader(t['file_uploader1'], type=['txt', 'pdf', 'docx', 'doc', 'odt'])
    with col2:
        uploaded_file2 = st.file_uploader(t['file_uploader2'], type=['txt', 'pdf', 'docx', 'doc', 'odt'])

    if uploaded_file1 and uploaded_file2:
        file_contents1 = uploaded_file1.getvalue().decode('utf-8')
        file_contents2 = uploaded_file2.getvalue().decode('utf-8')
        st.session_state.file_contents = (file_contents1, file_contents2)

        if st.button(t['analyze_button']):
            result = perform_discourse_analysis(file_contents1, file_contents2, nlp_models[lang_code], lang_code)
            st.session_state.discourse_result = result
            display_discourse_results(result, lang_code, t)
            store_discourse_analysis_result(st.session_state.username, file_contents1, file_contents2, result)

def display_discourse_results(result, lang_code, t):
    if result is None:
        st.warning(t.get('no_results', "No hay resultados disponibles."))
        return

    col1, col2 = st.columns(2)

    with col1:
        with st.expander(t.get('file_uploader1', "Documento 1"), expanded=True):
            st.subheader(t.get('key_concepts', "Conceptos Clave"))
            if 'key_concepts1' in result:
                df1 = pd.DataFrame(result['key_concepts1'], columns=['Concepto', 'Frecuencia'])
                df1['Frecuencia'] = df1['Frecuencia'].round(2)
                st.table(df1)

            if 'graph1' in result:
                st.pyplot(result['graph1'])

    with col2:
        with st.expander(t.get('file_uploader2', "Documento 2"), expanded=True):
            st.subheader(t.get('key_concepts', "Conceptos Clave"))
            if 'key_concepts2' in result:
                df2 = pd.DataFrame(result['key_concepts2'], columns=['Concepto', 'Frecuencia'])
                df2['Frecuencia'] = df2['Frecuencia'].round(2)
                st.table(df2)

            if 'graph2' in result:
                st.pyplot(result['graph2'])

    # Relación de conceptos entre ambos documentos (Diagrama de Sankey)
    st.subheader(t.get('comparison', "Relación de conceptos entre ambos documentos"))
    if 'key_concepts1' in result and 'key_concepts2' in result:
        # Código para generar el diagrama de Sankey (como en la función original)
        pass
    else:
        st.warning(t.get('comparison_not_available', "La comparación no está disponible."))


        '''