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

pub async fn show_development_blog(
    bot: Bot,
    dialogue: MasterDialogue,
    msg: Message,
) -> HandlerResult {
    show_development_blog_page(bot, dialogue, msg, 0).await
}

pub async fn show_development_blog_page(
    bot: Bot,
    dialogue: MasterDialogue,
    msg: Message,
    page: usize,
) -> HandlerResult {
    let content = include_str!("../../../static/blog.html");
    
    let mut blog_entries: Vec<&str> = content.split("<hr>").collect();
    blog_entries.reverse();
    
    if blog_entries.is_empty() {
        bot.send_message(msg.chat.id, "📭 Записи блога не найдены")
            .reply_markup(make_inline_keyboard(
                vec![("🔙 Вернуться в меню", AdminCallback::AdminMenu).into()],
                1,
            ))
            .await?;
        return Ok(());
    }
    
    if page >= blog_entries.len() {
        bot.edit_message_text(
            msg.chat.id,
            msg.id,
            "📭 На этой странице записей нет",
        )
        .reply_markup(make_inline_keyboard(
            vec![("🔙 Вернуться в меню", AdminCallback::AdminMenu).into()],
            1,
        ))
        .await?;
        return Ok(());
    }
    
    let current_entry = blog_entries[page].trim();
    let message_text = format!(
        "📖 <b>Блог разработки</b> (Страница {} из {})\n\n{}",
        page + 1,
        blog_entries.len(),
        current_entry
    );
    
    let keyboard = make_development_blog_keyboard(page, blog_entries.len());
    
    let result = bot.edit_message_text(msg.chat.id, msg.id, message_text.clone())
        .parse_mode(teloxide::types::ParseMode::Html)
        .reply_markup(keyboard.clone())
        .await;
    
    match result {
        Ok(_) => {
            dialogue.update_admin_kind(AdminStateKind::DevelopmentBlog { page }).await?;
        }
        Err(_) => {
            bot.send_message(msg.chat.id, message_text)
                .parse_mode(teloxide::types::ParseMode::Html)
                .reply_markup(keyboard)
                .await?;
            dialogue.update_admin_kind(AdminStateKind::DevelopmentBlog { page }).await?;
        }
    }
    
    Ok(())
}

fn make_development_blog_keyboard(page: usize, total_pages: usize) -> InlineKeyboardMarkup {
    let mut keyboard = InlineKeyboardMarkup::default();
    
    let mut nav_buttons = Vec::new();
    
    if page > 0 {
        nav_buttons.push(InlineKeyboardButton::callback(
            "⬅️ Предыдущая",
            AdminCallback::DevelopmentBlogPage { page: page - 1 }.to_string(),
        ));
    }
    
    if page + 1 < total_pages {
        nav_buttons.push(InlineKeyboardButton::callback(
            "Следующая ➡️",
            AdminCallback::DevelopmentBlogPage { 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
}
