"""
WhatsApp-Style Credit Card Chatbot
Built with Streamlit
"""

import os

import streamlit as st
from datetime import datetime
from recommender import ConversationSession

try:
    import google.generativeai as genai  # type: ignore
except ImportError:
    genai = None

# Page config
st.set_page_config(
    page_title="Card Advisor Bot",
    page_icon="",
    layout="centered",
    initial_sidebar_state="collapsed"
)

# WhatsApp-inspired CSS
st.markdown("""
<style>
    /* Hide Streamlit branding */
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    header {visibility: hidden;}
    
    /* Main container styling */
    .stApp {
        background-color: #0a1014;
    }
    
    /* Chat container */
    .chat-container {
        background: linear-gradient(to bottom, #0a1419 0%, #0d1721 100%);
        border-radius: 15px;
        padding: 20px;
        max-width: 600px;
        margin: 0 auto;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
    }
    
    /* Header styling */
    .chat-header {
        background: linear-gradient(135deg, #1e3a5f 0%, #2d5a7b 100%);
        color: white;
        padding: 15px 20px;
        border-radius: 12px 12px 0 0;
        margin: -20px -20px 20px -20px;
        display: flex;
        align-items: center;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
    }
    
    .chat-header-icon {
        font-size: 28px;
        margin-right: 12px;
    }
    
    .chat-header-text {
        flex: 1;
    }
    
    .chat-header-title {
        font-size: 18px;
        font-weight: 600;
        margin: 0;
    }
    
    .chat-header-status {
        font-size: 12px;
        opacity: 0.8;
        margin: 2px 0 0 0;
    }
    
    /* Message bubbles */
    .message {
        margin-bottom: 12px;
        display: flex;
        animation: slideIn 0.3s ease-out;
    }
    
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(10px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    .message.user {
        justify-content: flex-end;
    }
    
    .message.bot {
        justify-content: flex-start;
    }
    
    .message-bubble {
        max-width: 75%;
        padding: 10px 14px;
        border-radius: 12px;
        position: relative;
        word-wrap: break-word;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    }
    
    .message.user .message-bubble {
        background: linear-gradient(135deg, #005c4b 0%, #00846f 100%);
        color: white;
        border-bottom-right-radius: 4px;
    }
    
    .message.bot .message-bubble {
        background: linear-gradient(135deg, #1f2c34 0%, #2a3942 100%);
        color: #e9edef;
        border-bottom-left-radius: 4px;
    }
    
    .message-time {
        font-size: 10px;
        opacity: 0.7;
        margin-top: 4px;
        text-align: right;
    }
    
    .message.bot .message-time {
        text-align: left;
    }
    
    /* Input area */
    .stTextInput > div > div > input {
        background-color: #2a3942 !important;
        color: white !important;
        border: 1px solid #3d4a54 !important;
        border-radius: 24px !important;
        padding: 12px 20px !important;
        font-size: 15px !important;
    }
    
    .stTextInput > div > div > input:focus {
        border-color: #00a884 !important;
        box-shadow: 0 0 0 2px rgba(0, 168, 132, 0.2) !important;
    }
    
    /* Button styling */
    .stButton > button {
        background: linear-gradient(135deg, #00a884 0%, #00c9a7 100%) !important;
        color: white !important;
        border: none !important;
        border-radius: 24px !important;
        padding: 10px 24px !important;
        font-weight: 600 !important;
        transition: all 0.3s ease !important;
        box-shadow: 0 4px 12px rgba(0, 168, 132, 0.3) !important;
    }
    
    .stButton > button:hover {
        transform: translateY(-2px) !important;
        box-shadow: 0 6px 16px rgba(0, 168, 132, 0.4) !important;
    }
    
    /* Welcome message */
    .welcome-card {
        background: linear-gradient(135deg, #1e3a5f 0%, #2d5a7b 100%);
        padding: 20px;
        border-radius: 12px;
        margin-bottom: 20px;
        color: white;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    }
    
    .welcome-title {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        gap: 10px;
    }
    
    .welcome-text {
        font-size: 14px;
        opacity: 0.9;
        line-height: 1.6;
    }
    
    /* Quick suggestions */
    .quick-suggestions {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        margin-top: 12px;
    }
    
    .suggestion-chip {
        background: rgba(255, 255, 255, 0.1);
        color: white;
        padding: 6px 12px;
        border-radius: 16px;
        font-size: 13px;
        border: 1px solid rgba(255, 255, 255, 0.2);
        cursor: pointer;
        transition: all 0.2s;
    }
    
    .suggestion-chip:hover {
        background: rgba(255, 255, 255, 0.2);
        transform: translateY(-1px);
    }
</style>
""", unsafe_allow_html=True)

# Initialize session state
if 'messages' not in st.session_state:
    st.session_state.messages = []

if 'conversation' not in st.session_state:
    st.session_state.conversation = ConversationSession()

if 'show_welcome' not in st.session_state:
    st.session_state.show_welcome = True
if 'conversation_done' not in st.session_state:
    st.session_state.conversation_done = False


def handle_user_message(user_input: str) -> None:
    """Add user + bot messages to the chat history."""
    if not user_input:
        return

    # Hide welcome once user interacts
    st.session_state.show_welcome = False

    # Timestamp
    current_time = datetime.now().strftime("%H:%M")

    # Add user message
    st.session_state.messages.append({
        "role": "user",
        "content": user_input,
        "timestamp": current_time,
    })

    # Get bot response (rule-based + optional Gemini)
    bot_response = st.session_state.conversation.process_message(user_input)

    # Add bot message
    st.session_state.messages.append({
        "role": "bot",
        "content": bot_response,
        "timestamp": current_time,
    })

    # Mark conversation as done after a recommendation
    st.session_state.conversation_done = st.session_state.conversation.finished

# Main container
st.markdown('<div class="chat-container">', unsafe_allow_html=True)

# Chat header
st.markdown("""
<div class="chat-header">
    <div class="chat-header-icon"></div>
    <div class="chat-header-text">
        <div class="chat-header-title">Card Advisor Bot</div>
        <div class="chat-header-status">Online • Ready to help</div>
    </div>
</div>
""", unsafe_allow_html=True)

# Welcome message (only show once)
if st.session_state.show_welcome and len(st.session_state.messages) == 0:
    st.markdown("""
    <div class="welcome-card">
        <div class="welcome-title">
            <span>Welcome! I'm your Credit Card Advisor</span>
        </div>
        <div class="welcome-text">
            I will help you find the perfect credit card based on your needs. Just chat naturally, or use the quick actions below.
        </div>
    </div>
    """, unsafe_allow_html=True)

    # Interactive quick suggestion buttons (send predefined messages)
    col_a, col_b, col_c = st.columns(3)
    with col_a:
        if st.button("I want cashback", use_container_width=True):
            handle_user_message("I want a cashback card")
            st.rerun()
    with col_b:
        if st.button("I travel a lot", use_container_width=True):
            handle_user_message("I travel a lot")
            st.rerun()
    with col_c:
        if st.button("Best card for me", use_container_width=True):
            handle_user_message("best card for me")
            st.rerun()

# Display chat messages
for message in st.session_state.messages:
    role = message["role"]
    content = message["content"]
    timestamp = message.get("timestamp", "")
    
    # Replace markdown bold with HTML
    content_html = content.replace('*', '<strong>').replace('*', '</strong>')
    
    st.markdown(f"""
    <div class="message {role}">
        <div class="message-bubble">
            {content_html}
            <div class="message-time">{timestamp}</div>
        </div>
    </div>
    """, unsafe_allow_html=True)

# Input area / restart flow
if st.session_state.conversation_done:
    st.info("Recommendation shared. Start a new chat to get another suggestion.")
    if st.button("Start new chat", use_container_width=True, key="start_new_chat_main"):
        st.session_state.messages = []
        st.session_state.conversation.reset()
        st.session_state.show_welcome = True
        st.session_state.conversation_done = False
        st.rerun()
else:
    # Pressing Enter sends the message
    user_input = st.chat_input("Type your message...")
    if user_input:
        handle_user_message(user_input)
        st.rerun()

# Reset button in sidebar (for demo purposes)
with st.sidebar:
    st.markdown("### Controls")
    if st.button("Reset Chat", use_container_width=True):
        st.session_state.messages = []
        st.session_state.conversation.reset()
        st.session_state.show_welcome = True
        st.rerun()
    
    st.markdown("---")
    st.markdown("### Session Info")
    st.markdown(f"**Messages:** {len(st.session_state.messages)}")
    st.markdown(f"**Questions Asked:** {st.session_state.conversation.asked}/2")
    
    user_data = st.session_state.conversation.user
    if user_data:
        st.markdown("### User Preferences")
        if 'goal' in user_data:
            st.markdown(f"**Goal:** {user_data['goal']}")
        if 'monthlyIncome' in user_data:
            st.markdown(f"**Income:** ₹{user_data['monthlyIncome']:,}/month")

    st.markdown("---")
    st.markdown("### LLM Status")

    api_present = bool(os.getenv("GEMINI_API_KEY"))
    if not api_present:
        st.markdown("**API key:** not found (set `GEMINI_API_KEY` or .env).")
    else:
        st.markdown("**API key:** detected")

    if genai is None:
        st.markdown("**Library:** `google-generativeai` not installed.")
    else:
        st.markdown("**Library:** `google-generativeai` imported")

    if genai is not None and api_present:
        if st.button("Check Gemini connection", use_container_width=True):
            try:
                genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
                model = genai.GenerativeModel("gemini-flash-latest")
                resp = model.generate_content("Reply with a single word: Connected")
                text = getattr(resp, "text", "") or ""
                st.success(f"Gemini response: {text.strip()[:80]}")
            except Exception as e:
                st.error(f"Gemini check failed: {e}")

st.markdown('</div>', unsafe_allow_html=True)
# Footer
st.markdown("""
<div style="text-align: center; padding: 20px; color: #8696a0; font-size: 12px;">
    Powered by AI • Sample credit card data for demo purposes
</div>
""", unsafe_allow_html=True)
