# /frontend/app.py
import dash
from dash import Dash, html, dcc, callback, Input, Output, State
import dash_bootstrap_components as dbc
from dash.exceptions import PreventUpdate
from config import QUESTIONS
import os

DEBUG = os.environ.get("DEBUG", "false").lower() == "true"

# --- Adiciona o link para a folha de estilos dos ícones Font Awesome ---
FA = "https://use.fontawesome.com/releases/v5.15.4/css/all.css"

# --- Inicialização da Aplicação Dash ---
app = Dash(
    __name__,
    use_pages=True,
    external_stylesheets=[dbc.themes.BOOTSTRAP, FA],
    suppress_callback_exceptions=True
)
app.title = "RE/MAX Portal Chatbot"
server = app.server

# --- Conteúdo Dinâmico para a Sidebar ---
def get_chatbot_sidebar_content():
    """Retorna o layout das configurações do chatbot (com scroll na lista de exemplos)."""
    return html.Div([
        html.H5("⚙️ Configurações do Chat"),
        html.P(id='session-id-display', className="text-muted small"),

        html.H5("🔄 Limpar histórico"),
        dbc.Button("Limpar Histórico", id="clear-history-btn", color="danger", className="mb-3 w-100"),
        dbc.Alert("Histórico limpo com sucesso!", color="success", id="confirm-reset-alert", is_open=False, duration=4000),

        html.Hr(),

        html.H5("💬 Exemplos de Perguntas"),
        dbc.Checkbox(id="auto-send-checkbox", label="🚀 Enviar automaticamente", value=True),

        # Scroller dedicado para a lista de exemplos
        html.Div(
            id="chatbot-questions-scroller",
            style={"maxHeight": "45vh", "overflowY": "auto", "paddingRight": "2px"},
            children=html.Div(
                [
                    dbc.Button(q, id={"type": "question-btn", "index": i}, color="primary", className="mb-1 w-100")
                    for i, q in enumerate(QUESTIONS)
                ],
                className="d-grid gap-2"
            )
        ),
    ])

def get_conversations_sidebar_content():
    """Slot vazio que será preenchido por conversations.py após autenticação."""
    return html.Div(id="conv-sidebar-proxy")

# --- Layout da Barra Lateral Global ---
sidebar = html.Div(
    id="global-sidebar",
    children=[
        html.Div([
            html.Span([
                html.Span("RE", style={'color':'#e30613'}),
                html.Span("/", style={'color':'#003da5'}),
                html.Span("MAX", style={'color':'#e30613'}),
            ], className="brand-text h4 mb-0"),
            dbc.Button(html.I(className="fas fa-bars"), id="sidebar-toggle", n_clicks=0, color="light")
        ], className="sidebar-header"),
        
        html.Div(className="sidebar-nav-container", children=dbc.Nav([
            dbc.NavLink([html.I(className="fas fa-home"), html.Span("Página Inicial", className="nav-text")], href="/", active="exact"),
            dbc.NavLink([html.I(className="fas fa-comments"), html.Span("Chatbot", className="nav-text")], href="/chatbot", active="exact"),
            dbc.NavLink([html.I(className="fas fa-history"), html.Span("Histórico", className="nav-text")], href="/conversations", active="exact"),
        ], vertical=True, pills=True)),
        html.Div(id="sidebar-extra-content", className="sidebar-extra-container"),
    ]
)

# --- Layout Principal da Aplicação ---
app.layout = html.Div(id="app-container", children=[
    dcc.Store(id='sidebar-state', data=False),

    # Location adicional para empurrar/alterar a URL
    dcc.Location(id="router", refresh=False),

    # Armazenamento de estado global
    dcc.Store(id='session-id-store'),
    dcc.Store(id='auth-store', storage_type='session'),
    dcc.Store(id='chat-history-store', data=[]),

    # Stores globais auxiliares
    dcc.Store(id='chatbot-mounted', data=False, storage_type='memory'),
    dcc.Store(id='auto-send-store', data=True, storage_type='session'),
    dcc.Store(id='search-term-store', data=""),

    # === THEME STORE (persiste em localStorage) ===
    dcc.Store(id='theme-store', data={'dark': False}, storage_type='local'),

    # >>> Stores e modal GLOBAIS para a página de Histórico
    dcc.Store(id='auth-store-conv', storage_type='session'),

    dbc.Modal([
        dbc.ModalHeader(dbc.ModalTitle("🔐 Autenticação Necessária")),
        dbc.ModalBody([
            dbc.Input(id="username-input-conv", type="text", placeholder="Digite o usuário..."),
            dbc.Input(id="password-input-conv", type="password", placeholder="Digite a senha..."),
            dbc.FormFeedback("Dados inválidos", type="invalid")
        ]),
        dbc.ModalFooter(dbc.Button("Entrar", id="password-submit-conv")),
    ], id="auth-modal-conv", is_open=False, backdrop="static"),

    # Modal de Autenticação Global (usado pelo chatbot, se/quando ligar auth)
    dbc.Modal([
        dbc.ModalHeader(dbc.ModalTitle("🔐 Autenticação Necessária")),
        dbc.ModalBody([
            dbc.Input(id="password-input", type="password", placeholder="Digite a senha..."),
            dbc.FormFeedback("Senha incorreta", type="invalid")
        ]),
        dbc.ModalFooter(dbc.Button("Entrar", id="password-submit")),
    ], id="auth-modal", is_open=False, backdrop="static"),

    sidebar,

    # === Botão de Toggle do Tema (fixo canto superior direito) ===
    dbc.Button(
        [html.I(id="theme-toggle-icon", className="fas fa-moon me-2"), html.Span("Modo escuro")],
        id="theme-toggle",
        color="secondary",
        outline=True,
        size="sm",
        className="theme-toggle"
    ),

    html.Div(id="page-content", children=[
        html.Div(className="content-body", children=[dash.page_container]),
        html.Footer("© 2025 RE/MAX Copyright", className="footer")
    ])
])

# --- Callbacks Globais ---
@callback(
    Output("global-sidebar", "className"),
    Output("sidebar-toggle", "children"),
    Output("sidebar-state", "data"),
    Input("sidebar-toggle", "n_clicks"),
    State("sidebar-state", "data"),
    prevent_initial_call=True
)
def toggle_sidebar_callback(n_clicks, is_collapsed):
    new_state = not is_collapsed
    className = "collapsed" if new_state else ""
    icon = html.I(className="fas fa-bars") if new_state else html.I(className="fas fa-times")
    return className, icon, new_state

@callback(
    Output("sidebar-extra-content", "children"),
    Input("_pages_location", "pathname"),
    State("chatbot-mounted", "data"),
    prevent_initial_call=False,
)
def render_extra_sidebar_content(pathname, chatbot_ready):
    # Página Chatbot: só renderiza a sidebar quando a página já estiver montada
    if pathname == "/chatbot":
        if chatbot_ready:
            return get_chatbot_sidebar_content()
        return None
    # Página Histórico: usa o slot proxy
    if pathname == "/conversations":
        return get_conversations_sidebar_content()
    return None

@callback(
    Output('session-id-display', 'children'),
    Input('session-id-store', 'data'),
    prevent_initial_call=True
)
def update_session_id_display(session_id):
    if session_id:
        return f"ID: {session_id[:8]}..."
    return "Nenhuma sessão ativa."

# Sincroniza o estado do checkbox (quando existir) para um Store global sempre presente
@callback(
    Output('auto-send-store', 'data'),
    Input('auto-send-checkbox', 'value'),
    prevent_initial_call=False,
    allow_missing=True
)
def sync_auto_send_checkbox(val):
    return True if val is None else bool(val)

# === Callbacks do Tema ===

# 1) Aplica o tema ao app-container e ajusta ícone/label do botão
@callback(
    Output('app-container', 'className'),
    Output('theme-toggle-icon', 'className'),
    Output('theme-toggle', 'children'),
    Input('theme-store', 'data'),
)
def apply_theme(theme_data):
    dark = bool(theme_data.get('dark')) if theme_data else False
    app_class = "dark" if dark else ""

    icon_class = "fas fa-sun me-2" if dark else "fas fa-moon me-2"
    label = "Modo claro" if dark else "Modo escuro"
    children = [html.I(id="theme-toggle-icon", className=icon_class), html.Span(label)]
    return app_class, icon_class, children

# 2) Toggle do tema: inverte o estado salvo em localStorage
@callback(
    Output('theme-store', 'data'),
    Input('theme-toggle', 'n_clicks'),
    State('theme-store', 'data'),
    prevent_initial_call=True
)
def toggle_theme(n, theme_data):
    theme_data = theme_data or {'dark': False}
    theme_data['dark'] = not bool(theme_data.get('dark'))
    return theme_data

# --- Validation Layout (stubs para todos os IDs usados em callbacks) ---
app.validation_layout = html.Div([
    # Estrutura global mínima
    html.Div(id="app-container", children=[
        dcc.Store(id='sidebar-state'),
        dcc.Location(id="router"),
        dcc.Store(id='session-id-store'),
        dcc.Store(id='auth-store'),
        dcc.Store(id='chat-history-store'),
        dcc.Store(id='auth-store-conv'),
        dcc.Store(id='chatbot-mounted'),
        dcc.Store(id='auto-send-store'),
        dcc.Store(id='search-term-store'),
        dcc.Store(id='theme-store'),

        # Modais globais
        dbc.Modal(id="auth-modal", children=[
            dbc.ModalBody(dbc.Input(id="password-input")),
            dbc.ModalFooter(dbc.Button(id="password-submit")),
        ]),
        dbc.Modal(id="auth-modal-conv", children=[
            dbc.ModalBody(dbc.Input(id="password-input-conv")),
            dbc.ModalFooter(dbc.Button(id="password-submit-conv")),
        ]),

        html.Div(id="global-sidebar"),
        html.Div(id="sidebar-extra-content"),
        html.Div(id="page-content"),
        dbc.Button(id="theme-toggle", children=[html.I(id="theme-toggle-icon")]),

        # ids internos do dash pages
        dcc.Location(id="_pages_location"),
        dcc.Store(id="_pages_store"),
        html.Div(id="_pages_content"),
        html.Div(id="_pages_dummy"),
    ]),

    # STUBS da página Chatbot
    html.Div(className="chat-area-container", children=[
        dcc.Interval(id="wait-ui-timer"),
        dcc.Loading(id="loading-chat", children=html.Div(id="chat-conversation")),
        html.Div(className="chat-input-bar", children=dbc.InputGroup([
            dbc.Input(id="chat-input"),
            dbc.Button(id="send-button"),
        ])),
        html.Div(id="chatbot-questions-scroller"),
        dbc.Button(id="clear-history-btn"),
        dbc.Alert(id="confirm-reset-alert"),
        html.P(id='session-id-display'),
    ]),

    # STUBS da página Conversations
    html.Div(id="conv-sidebar-proxy"),
    html.Div(children=[
        dcc.Store(id='selected-session-store'),
        dbc.Input(id="search-input"),
        dbc.Button(id="search-btn"),
        dbc.Button(id="clear-search-btn"),
        html.Div(id="session-list"),
        html.Div(id="history-display"),
        dbc.Button(id="open-in-chat-btn"),
    ]),
])

if __name__ == "__main__":
    app.run(debug=DEBUG)
