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

pub async fn show_promo_menu(
    bot: Bot,
    _dialogue: MasterDialogue,
    msg: Message,
    settings: HandlerSettings,
) -> HandlerResult {
    let message = "🎫 <b>Управление промокодами</b>\n\nВыберите действие:";
    let ln = &settings.language;

    let buttons = vec![
        vec![t8x!(Ru, "🎫Создать для Траффика", ln, "menu-button"), t8x!(Ru, "💯Создать для Скидки", ln, "menu-button")],
        vec![t8x!(Ru, "🗑️Удалить промокоды",    ln, "menu-button")],
        vec![t8x!(Ru, "🔙 Назад в панель",      ln, "menu-button")],
    ];

    let keyboard = make_keyboard_from_vec(buttons);

    bot.send_message(msg.chat.id, message)
        .parse_mode(teloxide::types::ParseMode::Html)
        .reply_markup(keyboard)
        .await?;

    Ok(())
}

pub async fn add_discount_promo_handler(
    _bot: Bot,
    _dialogue: MasterDialogue,
    _msg: Message,
) -> HandlerResult {
    Ok(())
}

pub async fn delete_promos_handler(
    bot: Bot,
    dialogue: MasterDialogue,
    update: Update,
    msg: Message,
) -> HandlerResult {
    show_delete_promos_page(bot, dialogue, update, msg, 0).await?;
    Ok(())
}

/// Admin promo handler - clean and simple
pub async fn admin_promo_handler(
    bot: Bot,
    msg: Message,
    dialogue: MasterDialogue,
) -> HandlerResult {
    let config = admin_promo_config();
    promo_handler_with_config(bot, msg, dialogue, config).await
}

/// Admin promo creation handler
pub async fn admin_promo_create_handler(
    bot: Bot,
    dialogue: MasterDialogue,
    msg: Message,
    selected_pool: PoolType,
) -> HandlerResult {
    promo_create_handler_with_config(bot, dialogue, msg, selected_pool, PromoCreateConfig::Admin).await
}

pub async fn show_delete_promos_page(
    bot: Bot,
    dialogue: MasterDialogue,
    update: Update,
    msg: Message,
    page: usize,
) -> HandlerResult {
    bot.send_message(msg.chat.id, "⏳ Загрузка промокодов...")
        .await?;

    match api::get_promo_codes(page, PROMOS_PER_PAGE, update.from().unwrap().id.0 as i64).await {
        Ok(promo_codes) => {
            if promo_codes.is_empty() && page == 0 {
                bot.send_message(msg.chat.id, "📭 Промокоды не найдены")
                    .reply_markup(make_inline_keyboard(
                        vec![("🔙 Вернуться в меню", AdminCallback::AdminMenu)
                            .into()],
                        1,
                    ))
                    .await?;
                return Ok(());
            }

            let message = format_promo_list_message(&promo_codes, page);
            let keyboard = make_delete_promos_keyboard(&promo_codes, page);

            bot.send_message(msg.chat.id, message)
                .reply_markup(keyboard)
                .await?;

            dialogue.update_admin_kind(AdminStateKind::DeletePromos { page }).await?;
        }
        Err(e) => {
            bot.send_message(
                msg.chat.id,
                format!("❌ Ошибка загрузки промокодов: {}", e),
            )
            .reply_markup(make_inline_keyboard(
                vec![("🔙 Вернуться в меню", AdminCallback::AdminMenu).into()],
                1,
            ))
            .await?;
        }
    }

    Ok(())
}


fn make_delete_promos_keyboard(
    promo_codes: &[PromoCode],
    page: usize,
) -> InlineKeyboardMarkup {
    let mut keyboard = InlineKeyboardMarkup::default();

    for chunk in promo_codes.chunks(2) {
        let mut row = Vec::new();
        for promo in chunk {
            let button_text = format!("🗑️ {}", promo.promo_name);
            row.push(InlineKeyboardButton::callback(
                button_text,
                AdminCallback::DeletePromo {
                    promo_name: promo.promo_name.clone(),
                }
                .to_string(),
            ));
        }
        keyboard = keyboard.append_row(row);
    }

    let mut nav_buttons = Vec::new();

    if page > 0 {
        nav_buttons.push(InlineKeyboardButton::callback(
            "⬅️ Предыдущая",
            AdminCallback::DeletePromosPage { page: page - 1 }.to_string(),
        ));
    }

    if promo_codes.len() == PROMOS_PER_PAGE {
        nav_buttons.push(InlineKeyboardButton::callback(
            "Следующая ➡️",
            AdminCallback::DeletePromosPage { page: page + 1 }.to_string(),
        ));
    }

    if !nav_buttons.is_empty() {
        keyboard = keyboard.append_row(nav_buttons);
    }

    keyboard = keyboard.append_row(vec![InlineKeyboardButton::callback(
        "🔙 Вернуться в меню",
        AdminCallback::AdminMenu.to_string(),
    )]);

    keyboard
}

pub async fn delete_promos_state_handler(
    _bot: Bot,
    _msg: Message,
    _dialogue: MasterDialogue,
) -> HandlerResult {
    Ok(())
}

pub async fn handle_delete_promos_page(
    bot: Bot,
    dialogue: MasterDialogue,
    msg: Message,
    update: Update,
    page: usize,
) -> HandlerResult {
    match api::get_promo_codes(page, PROMOS_PER_PAGE, update.from().unwrap().id.0 as i64).await {
        Ok(promo_codes) => {
            if promo_codes.is_empty() {
                bot.edit_message_text(
                    msg.chat.id,
                    msg.id,
                    "📭 На этой странице промокодов нет",
                )
                .reply_markup(make_inline_keyboard(
                    vec![("🔙 Вернуться в меню", AdminCallback::AdminMenu)
                        .into()],
                    1,
                ))
                .await?;
                return Ok(());
            }

            let message = format_promo_list_message(&promo_codes, page);
            let keyboard = make_delete_promos_keyboard(&promo_codes, page);

            bot.edit_message_text(msg.chat.id, msg.id, message)
                .reply_markup(keyboard)
                .await?;

            dialogue.update_admin_kind(AdminStateKind::DeletePromos { page }).await?;
        }
        Err(e) => {
            bot.edit_message_text(
                msg.chat.id,
                msg.id,
                format!("❌ Ошибка загрузки промокодов: {}", e),
            )
            .reply_markup(make_inline_keyboard(
                vec![("🔙 Вернуться в меню", AdminCallback::AdminMenu).into()],
                1,
            ))
            .await?;
        }
    }

    Ok(())
}

pub async fn handle_delete_promo_confirmation(
    bot: Bot,
    msg: Message,
    promo_name: String,
) -> HandlerResult {
    let message = format!(
        indoc! {r#"
            ⚠️ <b>Подтверждение удаления</b>
            
            Вы действительно хотите удалить промокод <b>{}</b>?
            
            ❗ Это действие необратимо!
        "#},
        promo_name
    );

    let buttons = vec![
        (
            "✅ Да, удалить",
            AdminCallback::ConfirmDeletePromo {
                promo_name: promo_name.clone(),
            },
        )
            .into(),
        ("❌ Отмена", AdminCallback::DeletePromosPage { page: 0 }).into(),
    ];

    let keyboard = make_inline_keyboard(buttons, 2);

    bot.edit_message_text(msg.chat.id, msg.id, message)
        .reply_markup(keyboard)
        .await?;

    Ok(())
}

pub async fn handle_confirm_delete_promo(
    bot: Bot,
    _dialogue: MasterDialogue,
    msg: Message,
    promo_name: String,
) -> HandlerResult {
    bot.edit_message_text(
        msg.chat.id,
        msg.id,
        format!("⏳ Удаление промокода {}...", promo_name),
    )
    .await?;

    match api::delete_promo_code(promo_name.clone()).await {
        Ok(_) => {
            bot.edit_message_text(
                msg.chat.id,
                msg.id,
                format!("✅ Промокод <b>{}</b> успешно удален!", promo_name),
            )
            .reply_markup(make_inline_keyboard(
                vec![
                    (
                        "🗑️ Удалить еще",
                        AdminCallback::DeletePromosPage { page: 0 },
                    )
                        .into(),
                    ("🔙 Вернуться в меню", AdminCallback::AdminMenu).into(),
                ],
                2,
            ))
            .await?;
        }
        Err(e) => {
            bot.edit_message_text(
                msg.chat.id,
                msg.id,
                format!("❌ Ошибка удаления промокода {}: {}", promo_name, e),
            )
            .reply_markup(make_inline_keyboard(
                vec![
                    (
                        "🔄 Попробовать снова",
                        AdminCallback::DeletePromo { promo_name },
                    )
                        .into(),
                    ("🔙 Вернуться в меню", AdminCallback::AdminMenu).into(),
                ],
                2,
            ))
            .await?;
        }
    }

    Ok(())
}
