use super::*;
use crate::ui::prelude::*;

pub async fn callback_handler(
    bot: Bot,
    dialogue: MasterDialogue,
    q: CallbackQuery,
    update: Update,
    settings: HandlerSettings,
) -> HandlerResult {
    let Some(data) = q.data.clone() else {
        log::error!("AdminSupportCallback data is None");
        return Err("AdminSupportCallback data is None".into());
    };

    bot.answer_callback_query(q.id.clone()).await?;
    let Some(message) = get_callback_message(q.clone()) else {
        log::error!("Message does not exist");
        return Err("Message does not exist".into());
    };

    use SupportCallback::*;
    let callback: SupportCallback = serde_json::from_str(&data)?;
    match callback {
        AdminMenu => {
            bot.delete_message(message.chat.id, message.id).await?;
            support_entrypoint(bot, dialogue, message, settings).await?
        }
        PromoSelectPool { pool } => {
            support_promo_create_handler(bot, dialogue, message, pool).await?
        }
        DeletePromos => {
            show_delete_promos_page(bot, dialogue, message, update, 0).await?
        }
        DeletePromosPage { page } => {
            handle_delete_promos_page(bot, dialogue, message, update, page)
                .await?
        }
        DeletePromo { promo_name } => {
            handle_delete_promo_confirmation(bot, message, promo_name)
                .await?
        }
        ConfirmDeletePromo { promo_name } => {
            handle_confirm_delete_promo(
                bot, dialogue, message, promo_name,
            )
            .await?
        }
        AddTraffic { user_id, pool } => {
            match pool {
                Some(pool) => {
                    bot.edit_message_text(
                        message.chat.id,
                        message.id,
                        format!(
                            "📊 <b>Добавление трафика</b>\n\n<b>Пользователь:</b> <code>{}</code>\n<b>Пул:</b> <code>{}</code>\n\n💬 Введите количество ГБ трафика для добавления:",
                            user_id,
                            pool.display_name(&Language::Ru)
                        )
                    )
                    .parse_mode(teloxide::types::ParseMode::Html)
                    .reply_markup(make_inline_keyboard(
                        vec![("🔙 Отмена", SupportCallback::AdminMenu).into()],
                        1,
                    ))
                    .await?;
                    
                    dialogue.update_support_kind(SupportStateKind::AddTrafficReceiveAmount { user_id, pool }).await?;
                }
                None => {
                    select_pool_handler_constructor(
                        bot, 
                        message, 
                        |pool| SupportCallback::AddTraffic { user_id: user_id.clone(), pool: Some(pool) }.to_string(), 
                        Some(Callback::DeleteThisMessage.to_string()),
                        SelectPoolHandlerSettings::from(settings)
                        .include_pools(PoolType::all())
                        .with_message(t8x!("<b>Select pool</b>", &settings.language)))
                    .await?
                }
            }
        }
        UserWeeklyStats { user_id, pool } => {
            handle_user_detailed_stats(bot, message, user_id, pool, "week").await?
        }
        UserMonthlyStats { user_id, pool } => {
            handle_user_detailed_stats(bot, message, user_id, pool, "month").await?
        }
        UserWeeklyStatsPoolChoice { user_id, pools } => {
            select_pool_handler_constructor(
                bot, 
                message, 
                |pool| SupportCallback::UserWeeklyStats { user_id: user_id.clone(), pool }.to_string(), 
                Some(Callback::DeleteThisMessage.to_string()),
                SelectPoolHandlerSettings::from(settings)
                .include_pools(pools)
                .with_message(t8x!("<b>Only pools with purchased traffic available</b>", &settings.language)))
            .await?
        }
        UserMonthlyStatsPoolChoice { user_id, pools } => {
            select_pool_handler_constructor(
                bot, 
                message, 
                |pool| SupportCallback::UserMonthlyStats { user_id: user_id.clone(), pool }.to_string(), 
                Some(Callback::DeleteThisMessage.to_string()),
                SelectPoolHandlerSettings::from(settings)
                .include_pools(pools)
                .with_message(t8x!("<b>Only pools with purchased traffic available</b>", &settings.language)))
            .await?
        }
        PromoMenu => {
            bot.delete_message(message.chat.id, message.id).await?;
            show_promo_menu(bot, dialogue, message, settings).await?
        }
        ChangePricePool { pool } => {
            handle_change_price_pool(bot, dialogue, message, pool).await?
        }
        DropBalance { user_id, pool } => {
            match pool {
                Some(pool) => {
                    handle_drop_balance_confirmation(bot, message, user_id, pool).await?
                }
                None => {
                    select_pool_handler_constructor(
                        bot,
                        message,
                        |pool| SupportCallback::DropBalance { user_id: user_id.clone(), pool: Some(pool) }.to_string(),
                        Some(Callback::DeleteThisMessage.to_string()),
                        SelectPoolHandlerSettings::from(settings)
                        .include_pools(PoolType::all())
                        .with_message(t8x!("<b>Select pool to drop balance</b>", &settings.language)))
                    .await?
                }
            }
        }
        ConfirmDropBalance { user_id, pool } => {
            handle_confirm_drop_balance(bot, dialogue, message, user_id, pool).await?
        }
    }

    Ok(())
}
