use crate::ui::prelude::*;
use teloxide::types::PreCheckoutQuery;
use serde_json;
use teloxide::types::Update;

/// Handle pre-checkout query for Telegram Stars payments
pub async fn handle_pre_checkout_query(
    bot: Bot,
    query: PreCheckoutQuery,
) -> HandlerResult {
    log::info!("Received pre-checkout query: {:?}", query);
    
    bot.answer_pre_checkout_query(query.id, true).await?;
    
    Ok(())
}

#[derive(Serialize)]
pub struct SuccessfulPaymentRequestData {
    pub order_id: String,
    pub stars_amount: u64,
    pub user_id: i64,
    pub amount_gb: u32,
    pub pool_type: String,
    pub promocode: Option<String>,
}

/// Handle successful payment for Telegram Stars
/// This also handles pre_checkout_query due to teloxide-core bug with XTR currency
pub async fn handle_successful_payment(
    bot: Bot,
    msg: Message,
) -> HandlerResult {
    let ln = Language::Ru;
    
    let Some(successful_payment) = msg.successful_payment() else {
        log::error!("Message has no successful payment data");
        return Ok(());
    };
    
    log::info!("Received successful payment: {:?}", successful_payment);
    
    let currency_str = format!("{:?}", successful_payment.currency);
    if !currency_str.contains("XTR") {
        log::debug!("Not a Telegram Stars payment, currency: {:?}", successful_payment.currency);
        return Ok(());
    }
    
    let order_data = match serde_json::from_str::<serde_json::Value>(&successful_payment.invoice_payload) {
        Ok(data) => data,
        Err(e) => {
            log::error!("Failed to parse invoice payload: {}", e);
            bot.send_message(msg.chat.id, t8x!(Ru, "❌ Ошибка обработки платежа", &ln))
                .await?;
            return Ok(());
        }
    };
    
    let user_id = order_data.get("uid")
        .and_then(|v| v.as_i64())
        .ok_or("Missing user_id")?;

    let order_id = order_data.get("oid")
        .and_then(|v| v.as_str())
        .ok_or("Missing order_id")?
        .to_string();
    
    let amount_gb = order_data.get("gb")
        .and_then(|v| v.as_u64())
        .ok_or("Missing amount_gb")? as u32;
    
    let pool_type = order_data.get("pool")
        .and_then(|v| v.as_str())
        .ok_or("Missing pool_type")?
        .to_string();
    
    let promocode = order_data.get("promocode")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());
    
    let payment_data = SuccessfulPaymentRequestData {
        order_id,
        stars_amount: successful_payment.total_amount as u64,
        user_id,
        amount_gb,
        pool_type: pool_type.clone(),
        promocode,
    };
    
    match api::process_telegram_stars_payment(payment_data).await {
        Ok(()) => {
            let success_message = strfmt!(t8x!(Ru, r#"
                ✅ <b>Платеж успешно выполнен!</b>
                
                💰 Оплачено: {stars_amount} ⭐
                📊 Количество: {amount_gb} GB
                🧊 Тип прокси: {pool_type}
                
                Трафик добавлен на ваш баланс.
            "#, &ln),
            stars_amount => successful_payment.total_amount,
            amount_gb => amount_gb,
            pool_type => pool_type
            )?;
            
            bot.send_message(user_id.to_string(), success_message)
                .await?;
        }
        Err(e) => {
            log::error!("Failed to process Telegram Stars payment: {}", e);
            bot.send_message(msg.chat.id, t8x!(Ru, "❌ Ошибка обработки платежа. Обратитесь в поддержку.", &ln))
                .await?;
        }
    }
    
    Ok(())
}

/// Send Telegram Stars invoice
pub async fn send_telegram_stars_invoice(
    bot: Bot,
    chat_id: ChatId,
    order_data: serde_json::Value,
    _ln: Language,
) -> HandlerResult {
    let order_id = order_data.get("order_id")
        .and_then(|v| v.as_str())
        .ok_or("Missing order_id")?;
    
    let stars_amount = order_data.get("stars_amount")
        .and_then(|v| v.as_u64())
        .ok_or("Missing stars_amount")? as u32;
    
    let description = order_data.get("description")
        .and_then(|v| v.as_str())
        .unwrap_or("Proxy traffic purchase");
    
    let invoice_payload = serde_json::json!({
        "oid": order_id,
        "uid": chat_id.0,
        "gb": order_data.get("amount_gb").and_then(|v| v.as_u64()).unwrap_or(0),
        "pool": order_data.get("pool_type").and_then(|v| v.as_str()).unwrap_or(""),
        "method": "telegram_stars"
    }).to_string();
    
    let price = teloxide::types::LabeledPrice::new(
        format!("{} GB прокси", order_data.get("amount_gb").and_then(|v| v.as_u64()).unwrap_or(0)),
        stars_amount
    );
    
    bot.send_invoice(
        chat_id,
        format!("Покупка прокси: {} GB", order_data.get("amount_gb").and_then(|v| v.as_u64()).unwrap_or(0)),
        description.to_string(),
        invoice_payload,
        "XTR", // currency - XTR for Telegram Stars
        vec![price],
    ).await?;
    
    Ok(())
}

/// Handle raw update for pre_checkout_query (workaround for teloxide-core bug)
pub async fn handle_raw_update(
    bot: Bot,
    update: Update,
    pre_checkout_query: PreCheckoutQuery,
) -> HandlerResult {
    log::info!("Received pre_checkout_query: {:?}", pre_checkout_query);
    bot.answer_pre_checkout_query(pre_checkout_query.id, true).await?;
    
    Ok(())
}
