import streamlit as st
from datetime import datetime, date, time, timedelta
from db import get_banks_for_currency
import time as time_module
import test


@st.dialog("📞 Auction - Call")
def call_auction_modal(row_data, execute_func):
    row_data = dict(row_data)
    #print("ROW DATA Auction - Call:", row_data)
    is_broadcast = st.session_state.get("AUCTION_MODE") == "BROADCAST"
    
    if is_broadcast:
        st.subheader("📢 Market Call (Broadcast)")
        st.info(f"Broadcasting request in **{row_data['Currency']}** to all eligible banks.")
    else:
        st.subheader(f"Direct Call: {row_data['BankName']}")

    # Date Handling
    today = date.today()
    orig_maturity = row_data.get('MaturityDate')
    
    # Ensure orig_maturity is a date object
    if isinstance(orig_maturity, str):
        try: orig_maturity = datetime.strptime(orig_maturity, '%Y-%m-%d').date()
        except: orig_maturity = today + timedelta(days=1)
    elif hasattr(orig_maturity, 'date'): 
        orig_maturity = orig_maturity.date()
    
    with st.form("modal_call_form", border=False):
        col1, col2 = st.columns(2)
        with col1:
            new_amount = st.number_input("Amount", value=float(row_data.get('Amount', 0.0)), format="%.2f")
            trade_date = st.date_input("Trade/Value Date", value=orig_maturity)            
            st.text_input("Basis", value=row_data.get('Basis', ''), disabled=True)
        with col2:
            new_rate = st.number_input("Call Rate (%)", value=float(row_data.get('Rate', 0.0)), step=0.01, format="%.2f")
            new_maturity = st.date_input("New Maturity Date", value=orig_maturity + timedelta(days=7))
            call_time = st.time_input("Call Time (09:00 - 17:00)", value=time(15, 0))
            
        time_valid = time(9, 0) <= call_time <= time(17, 0)
        tenor_days = (new_maturity - trade_date).days
        tenor_str = f"{tenor_days}D"
        
        if not time_valid: st.error("❌ Time must be between 09:00 and 17:00")
        if tenor_days <= 0: st.error("⚠️ Maturity must be at least 1 day after Trade Date.")
            
        st.info(f"📅 Calculated Tenor: **{tenor_str}**")
        st.write("---")
        
        submitted = st.form_submit_button(
            "Submit Call", 
            type="primary", 
            use_container_width=True, 
            disabled=(not time_valid or tenor_days <= 0)
        )

        if submitted:
            # ... (rest of submission logic remains unchanged)
            if is_broadcast:
                banks = get_banks_for_currency(row_data['IDClient'], row_data['Currency'])
                if not banks:
                    st.error("❌ No eligible banks found for this currency.")
                    time_module.sleep(2)
                else:
                    success_count = 0
                    for bank in banks:
                        b_data = row_data.copy()
                        b_data['IDBank'] = bank['IDBank']
                        b_data['BankName'] = bank['BankName']
                        b_data['BankEmail'] = bank['BankEmail']
                        if execute_func(b_data, new_amount, new_rate, trade_date, call_time, new_maturity, tenor_str):
                            success_count += 1
                    if success_count > 0:
                        st.success(f"✅ Broadcast sent to {success_count} bank(s)!")
                    else:
                        st.error("❌ All inserts failed. Check DB errors above.")
                    time_module.sleep(4)
            else:
                result = execute_func(row_data, new_amount, new_rate, trade_date, call_time, new_maturity, tenor_str)
                if result:
                    st.success("✅ Call submitted successfully!")
                else:
                    st.error("❌ Call failed — check the error above.")
                time_module.sleep(2)
            
            st.session_state.df_key = st.session_state.get('df_key', 0) + 1
            st.rerun()

@st.dialog("💰 Auction - Offer")
def bank_offer_modal(row_data, execute_func):
    
    row_data = dict(row_data)
    #print("DEBUG: row_data structure before execution:", row_data)

    st.write(f"### Respond to **{row_data['ClientName']}**")
    
    # Use columns to organize the "No-Modification" boxes
    col1, col2 = st.columns(2)
    
    with col1:
        # Amount with comma separators
        formatted_amount = f"{row_data['Amount']:,.2f} {row_data['Currency']}"
        st.text_input("Amount", value=formatted_amount, disabled=True)
        
        # Dates - clean string format
        st.text_input("Value Date", value=str(row_data['ValueDate']), disabled=True)
        st.text_input("Maturity", value=str(row_data['MaturityDate']), disabled=True)

    with col2:
        # Rates and Tenor
        st.text_input("Client's Call Rate (%)", value=f"{row_data['CallRate']}%", disabled=True)
        st.text_input("Tenor", value=row_data['Tenor'], disabled=True)
        st.text_input("Call Time", value=str(row_data['CallTime']), disabled=True)

    st.markdown("---")
    
    # THE EDITABLE FORM
    with st.form("modal_offer_form", border=False):
        st.write(f"### Respond to {row_data['ClientName']}")
        
        offer_rate = st.number_input("Offer Rate (%)", min_value=0.0, step=0.01, value=float(row_data.get('CallRate', 0)))
        
        # Calculation Logic using test.py
        tenor = int(str(row_data.get('Tenor', '30')).replace('D', ''))
        gross, tax, net = test.calc_interest(
            row_data['Amount'], 
            offer_rate, 
            tenor, 
            row_data.get('Basis', 'Act/365'), 
            row_data.get('BWithTax') # Tax can be 0 or dynamic if needed
        )
        
        st.write(f"**Gross Yield:** {gross:,.2f} | **Net Interest:** {net:,.2f}")

        col1, col2 = st.columns(2)
        submit = col1.form_submit_button("Submit Offer", type="primary", use_container_width=True)
        reject = col2.form_submit_button("Reject Request", use_container_width=True)

        if submit:
            # FIX: Calling with 5 arguments to match db.py definition
            if execute_func(row_data, offer_rate, gross, net, "Offer"):
                st.success("Offer submitted and email sent!")
                st.rerun()
        
        if reject:
            # Standardizing Bank Rejection as "BankRejected"
            if execute_func(row_data, 0, 0, 0, "BankRejected"):
                st.warning("Request rejected and client notified.")
                st.rerun()    

@st.dialog("🎯 Auction - Confirm")
def client_decision_modal(row_data, execute_func):
    st.write(f"### Review Offer from **{row_data['BankName']}**")
    
    col1, col2 = st.columns(2)
    with col1:
        st.text_input("Amount", value=f"{row_data['Amount']:,.2f} {row_data['Currency']}", disabled=True)
        st.text_input("Bank's Offered Rate", value=f"{row_data['OfferRate']}%", disabled=True)
        st.text_input("Net Interest (after tax)", value=f"{row_data['NetYield']:,.2f}", disabled=True)

    with col2:
        st.text_input("Tenor", value=row_data['Tenor'], disabled=True)
        st.text_input("Value Date", value=str(row_data['ValueDate']), disabled=True)
        st.text_input("Maturity Date", value=str(row_data['MaturityDate']), disabled=True)

    st.write("---")
    
    # Action Buttons
    c1, c2 = st.columns(2)
    
    with c1:
        if st.button("✅ Confirm", type="primary", width='stretch'):
            if execute_func(row_data, "Active"):
                st.toast("Trade Confirmed!")
                st.rerun()
    
    with c2:
        if st.button("❌ Reject", type="secondary", width='stretch'):
            if execute_func(row_data, "Rejected"):
                st.toast("Offer Rejected.")
                st.rerun()
                
    