from __future__ import annotations

import uuid
from urllib.parse import quote

import gradio as gr

from .chat_service import ChatService


CUSTOM_CSS = """
.gradio-container {
    max-width: 100% !important;
    padding: 0 !important;
    background: #0b0e11 !important;
}
#title-banner {
    text-align: center;
    padding: 16px 0 10px 0;
    background: linear-gradient(135deg, #0b0e11 0%, #141a22 100%);
    border-bottom: 2px solid #00c87644;
}
#title-main {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
    flex-wrap: wrap;
}
#title-logo {
    display: block;
    width: 3.3rem;
    height: 2.2rem;
    flex: 0 0 3.3rem;
    object-fit: contain;
}
#title-banner h1 {
    font-size: 2.2rem !important;
    font-weight: 800 !important;
    margin: 0 !important;
    color: #00c876;
    letter-spacing: 1px;
}
#title-banner p {
    color: #8899aa;
    margin: 4px 0 0 0 !important;
    font-size: 0.95rem;
}
#sidebar {
    background: #0d1117 !important;
    border-right: 1px solid #1e2a38 !important;
    min-height: calc(100vh - 110px) !important;
}
#history-label {
    color: #8899aa;
    font-size: 1rem;
    margin: 12px 0 6px 4px !important;
}
#new-chat-btn {
    background: #00c876 !important;
    border-color: #00c876 !important;
    color: #0b0e11 !important;
    font-weight: 700 !important;
}
#new-chat-btn:hover {
    background: #00b86d !important;
    border-color: #00b86d !important;
}
footer {
    display: none !important;
}
"""


TITLE_LOGO_SVG = (
    '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 90 60" preserveAspectRatio="xMidYMid meet">'
    '<polygon fill="#2ecc71" points="30 0 0 30 30 60 60 30 90 0 30 0"/>'
    '<polygon fill="#27ae60" points="30 60 60 30 90 60 30 60"/>'
    '</svg>'
)
TITLE_LOGO_SRC = f"data:image/svg+xml,{quote(TITLE_LOGO_SVG, safe='')}"
TITLE_BANNER_HTML = (
    '<div id="title-banner">'
        '<div id="title-main">'
            f'<img id="title-logo" src="{TITLE_LOGO_SRC}" alt="" aria-hidden="true" />'
            '<h1>OpenKite - Trading Assistant</h1>'
        '</div>'
        '<p>Powered by Zerodha Kite MCP &bull; Firecrawl &bull; Screener.in</p>'
    '</div>'
)


EXAMPLES = [
    ["Login to Kite "],
    ["Show my current holdings with live prices, day change, unrealised P&L, and portfolio weights."],
    ["Analyze my portfolio and suggest which stocks I should consider selling"],
    ["Suggest 3 stocks I can buy today based on fundamentals and market momentum"],
    ["Show the last 4 quarters for HDFCBANK and tell me whether revenue, profit, and return ratios are improving or weakening."],
    ["Summarize the most important Reliance Industries news from the last 7 days and explain the likely market impact."],
    ["Which stocks are trending with high volume and strong fundamentals ?"],
    ["Review my top holdings by value using fundamentals and recent news and highlight key risks and opportunities"],
]


def build_demo(chat_service: ChatService) -> gr.Blocks:
    """Build and return the Gradio application."""

    def _on_new_chat():
        new_sid = str(uuid.uuid4())
        return [], [], new_sid, gr.update(choices=chat_service.history_choices(), value=None)

    def _on_load_conversation(selected_sid: str):
        if not selected_sid:
            return gr.update(), gr.update(), gr.update()
        messages = chat_service.load_history(selected_sid)
        return messages, messages, selected_sid

    session_id_state = gr.State(value="")

    with gr.Blocks(css=CUSTOM_CSS, title="OpenKite Trading Assistant", theme=gr.themes.Base()) as demo:
        gr.HTML(TITLE_BANNER_HTML)

        with gr.Row():
            with gr.Column(scale=1, min_width=230, elem_id="sidebar"):
                new_chat_btn = gr.Button("+ New Chat", elem_id="new-chat-btn")
                gr.HTML('<div id="history-label">History</div>')
                history_radio = gr.Radio(
                    choices=chat_service.history_choices(),
                    value=None,
                    label="",
                    show_label=False,
                    interactive=True,
                )

            with gr.Column(scale=4):
                chat_interface = gr.ChatInterface(
                    fn=chat_service.chat,
                    chatbot=gr.Chatbot(
                        elem_id="chatbot",
                        height="calc(100vh - 210px)",
                        buttons=["copy"],
                        render_markdown=True,
                    ),
                    additional_inputs=[session_id_state],
                    additional_inputs_accordion=gr.Accordion(visible=False),
                    additional_outputs=[session_id_state, history_radio],
                    examples=EXAMPLES,
                )

        demo.load(
            fn=lambda: gr.update(choices=chat_service.history_choices()),
            outputs=[history_radio],
        )

        new_chat_btn.click(
            fn=_on_new_chat,
            inputs=[],
            outputs=[chat_interface.chatbot, chat_interface.chatbot_state, session_id_state, history_radio],
            queue=False,
        )

        history_radio.change(
            fn=_on_load_conversation,
            inputs=[history_radio],
            outputs=[chat_interface.chatbot, chat_interface.chatbot_state, session_id_state],
            queue=False,
        )

    return demo
