from __future__ import annotations

from typing import TYPE_CHECKING, Optional

if TYPE_CHECKING:
    from .chatbot import Chatbot

ACCENT_COLORS: dict[str, str] = {
    "indigo": "#6366f1",
    "violet": "#8b5cf6",
    "rose": "#f43f5e",
    "emerald": "#10b981",
    "amber": "#f59e0b",
    "blue": "#3b82f6",
    "cyan": "#06b6d4",
    "slate": "#64748b",
}

_CSS = """
/* ── ArielAI UI v2 ── */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');

:root {{
    --bg:          {bg};
    --surface:     {surface};
    --surface2:    {surface2};
    --border:      {border};
    --accent:      {accent};
    --accent-dim:  {accent}22;
    --accent-glow: {accent}44;
    --text:        {text};
    --text-muted:  {text_muted};
    --user-bg:     {accent};
    --bot-bg:      {surface2};
    --radius:      18px;
    --radius-sm:   10px;
}}

*, *::before, *::after {{ box-sizing: border-box; }}

body, .gradio-container, .gradio-container > .main {{
    background: var(--bg) !important;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, system-ui, sans-serif !important;
    color: var(--text) !important;
    min-height: 100vh;
    margin: 0 !important;
    padding: 0 !important;
}}

.gradio-container {{
    max-width: 860px !important;
    margin: 0 auto !important;
    padding: 24px 0 !important;
}}

/* ── Header ── */
.ariel-header {{
    background: var(--surface);
    border: 1px solid var(--border);
    border-bottom: none;
    border-radius: var(--radius) var(--radius) 0 0;
    padding: 18px 22px;
    display: flex;
    align-items: center;
    gap: 14px;
}}

.ariel-avatar {{
    width: 40px; height: 40px;
    border-radius: 12px;
    background: linear-gradient(135deg, var(--accent), {accent}99);
    display: flex; align-items: center; justify-content: center;
    font-size: 20px; flex-shrink: 0;
    box-shadow: 0 0 20px var(--accent-glow);
}}

.ariel-title {{
    font-size: 17px; font-weight: 700;
    color: var(--text); letter-spacing: -0.01em;
}}

.ariel-subtitle {{
    font-size: 12px; color: var(--text-muted); margin-top: 2px;
}}

.ariel-status {{
    margin-left: auto;
    display: flex; align-items: center; gap: 7px;
    font-size: 12px; color: #22c55e; font-weight: 500;
}}

.ariel-dot {{
    width: 7px; height: 7px; border-radius: 50%; background: #22c55e;
    animation: pulse-dot 2s ease-in-out infinite;
}}

@keyframes pulse-dot {{
    0%, 100% {{ opacity: 1; transform: scale(1); }}
    50% {{ opacity: 0.5; transform: scale(0.85); }}
}}

/* ── Chat wrap ── */
.ariel-chat-wrap {{
    background: var(--surface);
    border: 1px solid var(--border);
    border-top: none;
    border-radius: 0 0 var(--radius) var(--radius);
    overflow: hidden;
}}

/* ── Chat bubbles ── */
#ariel-chatbot {{
    background: var(--bg) !important;
    border: none !important;
    min-height: 420px;
}}

#ariel-chatbot .message-wrap {{
    padding: 6px 18px !important;
}}

#ariel-chatbot .user .message,
#ariel-chatbot .user > div {{
    background: var(--user-bg) !important;
    color: white !important;
    border-radius: var(--radius) var(--radius) 4px var(--radius) !important;
    box-shadow: 0 2px 14px var(--accent-glow) !important;
    max-width: 78% !important;
    margin-left: auto !important;
    padding: 10px 14px !important;
    font-size: 14px !important;
    line-height: 1.55 !important;
    border: none !important;
}}

#ariel-chatbot .bot .message,
#ariel-chatbot .bot > div {{
    background: var(--bot-bg) !important;
    color: var(--text) !important;
    border-radius: var(--radius) var(--radius) var(--radius) 4px !important;
    border: 1px solid var(--border) !important;
    max-width: 78% !important;
    padding: 10px 14px !important;
    font-size: 14px !important;
    line-height: 1.55 !important;
    box-shadow: none !important;
}}

/* ── Input area ── */
.ariel-input-area {{
    background: var(--surface) !important;
    border-top: 1px solid var(--border) !important;
    padding: 14px 18px !important;
}}

#ariel-chatbot ~ div textarea,
.ariel-input-area textarea {{
    background: var(--bg) !important;
    color: var(--text) !important;
    border: 1px solid var(--border) !important;
    border-radius: var(--radius-sm) !important;
    font-size: 14px !important;
    font-family: inherit !important;
    padding: 10px 14px !important;
    resize: none !important;
    transition: border-color 0.15s;
}}

#ariel-chatbot ~ div textarea:focus,
.ariel-input-area textarea:focus {{
    border-color: var(--accent) !important;
    outline: none !important;
    box-shadow: 0 0 0 3px var(--accent-dim) !important;
}}

/* Send button */
.ariel-input-area button.primary,
button#submit-btn,
.submit-btn {{
    background: var(--accent) !important;
    border: none !important;
    border-radius: var(--radius-sm) !important;
    color: white !important;
    font-weight: 600 !important;
    font-size: 14px !important;
    transition: opacity 0.15s, transform 0.1s;
    box-shadow: 0 2px 10px var(--accent-glow) !important;
}}

.ariel-input-area button.primary:hover,
button#submit-btn:hover {{
    opacity: 0.9 !important;
    transform: translateY(-1px) !important;
}}

/* Clear/retry buttons */
.ariel-input-area button.secondary {{
    background: var(--surface2) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-muted) !important;
    border-radius: var(--radius-sm) !important;
}}

/* Examples */
.ariel-input-area .examples-list button {{
    background: var(--surface2) !important;
    border: 1px solid var(--border) !important;
    color: var(--text-muted) !important;
    border-radius: var(--radius-sm) !important;
    font-size: 13px !important;
    transition: border-color 0.15s;
}}

.ariel-input-area .examples-list button:hover {{
    border-color: var(--accent) !important;
    color: var(--text) !important;
}}

/* ── Footer ── */
.ariel-footer {{
    text-align: center;
    font-size: 11px;
    color: var(--text-muted);
    padding: 10px;
    border-top: 1px solid var(--border);
}}

.ariel-footer a {{ color: var(--accent); text-decoration: none; }}

/* ── Hide Gradio clutter ── */
footer, .footer, .svelte-1ipelgc {{ display: none !important; }}
.contain {{ max-width: 100% !important; padding: 0 !important; }}
"""

_DARK_VARS = dict(
    bg="#0d0d14",
    surface="#13131f",
    surface2="#1a1a28",
    border="#ffffff0d",
    text="#e2e8f0",
    text_muted="#64748b",
)

_LIGHT_VARS = dict(
    bg="#f8fafc",
    surface="#ffffff",
    surface2="#f1f5f9",
    border="#e2e8f0",
    text="#0f172a",
    text_muted="#64748b",
)


class ChatUI:
    """
    Polished, branded Gradio Blocks frontend for ArielAI chatbots.

    Usage::

        from arielai import Chatbot, ChatUI

        bot = Chatbot()
        ui = ChatUI(bot, brand_name="Nova", accent="violet", dark_mode=True)
        ui.launch()
    """

    def __init__(
        self,
        chatbot: "Chatbot",
        *,
        brand_name: Optional[str] = None,
        brand_emoji: str = "🤖",
        tagline: Optional[str] = None,
        accent: str = "indigo",
        dark_mode: bool = True,
        show_footer: bool = True,
        footer_text: str = "Built with ArielAI",
        footer_link: str = "https://pypi.org/project/arielai/",
        extra_css: str = "",
    ) -> None:
        self._bot = chatbot
        self.brand_name = brand_name or chatbot.title
        self.brand_emoji = brand_emoji
        self.tagline = tagline or (
            f"Model: {chatbot.model} · {chatbot.backend_name}"
        )
        self.accent = ACCENT_COLORS.get(accent, accent)
        self.dark_mode = dark_mode
        self.show_footer = show_footer
        self.footer_text = footer_text
        self.footer_link = footer_link
        self.extra_css = extra_css
        self._demo = None
        self._css_str = None
        self._theme = None

    def _build_css(self) -> str:
        palette = _DARK_VARS if self.dark_mode else _LIGHT_VARS
        css = _CSS.format(accent=self.accent, **palette)
        if self.extra_css:
            css += f"\n{self.extra_css}"
        return css

    def build(self):
        try:
            import gradio as gr
        except ImportError as exc:
            raise ImportError("pip install arielai") from exc

        self._css_str = self._build_css()
        self._theme = gr.themes.Base()

        with gr.Blocks(title=self.brand_name) as demo:

            # Header
            gr.HTML(
                f'<div class="ariel-header">'
                f'  <div class="ariel-avatar">{self.brand_emoji}</div>'
                f'  <div>'
                f'    <div class="ariel-title">{self.brand_name}</div>'
                f'    <div class="ariel-subtitle">{self.tagline}</div>'
                f'  </div>'
                f'  <div class="ariel-status"><div class="ariel-dot"></div>Online</div>'
                f'</div>'
            )

            # Chat + Input inside wrapper
            with gr.Column(elem_classes=["ariel-chat-wrap"]):
                gr.ChatInterface(
                    fn=self._bot.chat,
                    chatbot=gr.Chatbot(
                        elem_id="ariel-chatbot",
                        height=460,
                        render=False,
                        bubble_full_width=False,
                    ),
                    textbox=gr.Textbox(
                        placeholder=self._bot.placeholder,
                        container=False,
                        scale=7,
                        render=False,
                    ),
                    examples=self._bot.examples,
                    fill_height=False,
                )

                if self.show_footer:
                    gr.HTML(
                        f'<div class="ariel-footer">'
                        f'<a href="{self.footer_link}" target="_blank">{self.footer_text}</a>'
                        f'</div>'
                    )

        self._demo = demo
        return demo

    def launch(
        self,
        share: bool = False,
        server_name: str = "0.0.0.0",
        server_port: Optional[int] = None,
        inbrowser: bool = True,
        **kwargs,
    ) -> None:
        demo = self.build()
        demo.launch(
            share=share,
            server_name=server_name,
            server_port=server_port,
            inbrowser=inbrowser,
            css=self._css_str,
            theme=self._theme,
            **kwargs,
        )

    def close(self) -> None:
        if self._demo is not None:
            self._demo.close()

    def __enter__(self): return self
    def __exit__(self, *a): self.close()

    @staticmethod
    def list_accents() -> dict[str, str]:
        return dict(ACCENT_COLORS)
