use crate::ui::prelude::*;
use rust_shared::repository::model::Location;
use std::sync::Arc;
use super::*;

pub struct DefaultLocationSelectionConfig {
    pub header: String,
    pub icon: String,
    pub location_type_name: String,
    pub location_type_name_singular: String,
    pub location_type: LocationType,
    pub select_callback: Arc<dyn Fn(PoolType, usize) -> DefaultProxySettingsCallback + Send + Sync>,
    pub page_callback: Arc<dyn Fn(PoolType, usize) -> DefaultProxySettingsCallback + Send + Sync>,
    pub back_callback: DefaultProxySettingsCallback,
}

const ITEMS_PER_PAGE: usize = 10;
const ITEMS_PER_ROW: usize = 2;

pub async fn manage_default_proxy_settings_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    
    let current_settings = match get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };

    let mut buttons: Vec<InlineButton<DefaultProxySettingsCallback>> = vec![
        (t8x!(Ru, "🌍 Страны 🌍", &ln), DefaultProxySettingsCallback::EditCountries { pool }).into(),
    ];

    if !current_settings.countries.is_empty() {
        buttons.push((t8x!(Ru, "🗺️ Расширенные настройки локации 🗺️", &ln), DefaultProxySettingsCallback::AdvancedLocationSettings { pool }).into());
    }

    buttons.extend(vec![
        (t8x!(Ru, "🕶️ Анонимный фильтр 🕶️", &ln), DefaultProxySettingsCallback::ToggleAnonymousFilter { pool }).into(),
        (t8x!(Ru, "⏱️ Интервал ротации ⏱️", &ln), DefaultProxySettingsCallback::EditRotationInterval { pool }).into(),
        (t8x!(Ru, "🔄 Сбросить к умолчанию 🔄", &ln), DefaultProxySettingsCallback::ResetToDefaults { pool }).into(),
        (t8x!(Ru, "🔙Назад к управлению🔙", &ln), DefaultProxySettingsCallback::Back { pool }).into(),
    ]);

    let keyboard = if current_settings.countries.is_empty() {
        let mut keyboard = InlineKeyboardMarkup::default();
        
        keyboard = keyboard.append_row(vec![
            InlineKeyboardButton::callback(
                t8x!(Ru, "🌍 Страны 🌍", &ln),
                DefaultProxySettingsCallback::EditCountries { pool }.to_string()
            )
        ]);
        
        let remaining_buttons: Vec<InlineButton<DefaultProxySettingsCallback>> = vec![
            (t8x!(Ru, "🕶️ Анонимный фильтр 🕶️", &ln), DefaultProxySettingsCallback::ToggleAnonymousFilter { pool }).into(),
            (t8x!(Ru, "⏱️ Интервал ротации ⏱️", &ln), DefaultProxySettingsCallback::EditRotationInterval { pool }).into(),
            (t8x!(Ru, "🔄 Сбросить к умолчанию 🔄", &ln), DefaultProxySettingsCallback::ResetToDefaults { pool }).into(),
            (t8x!(Ru, "🔙Назад к управлению🔙", &ln), DefaultProxySettingsCallback::Back { pool }).into(),
        ];
        let remaining_keyboard = make_inline_keyboard(remaining_buttons, 2);
        
        for row in remaining_keyboard.inline_keyboard {
            keyboard = keyboard.append_row(row);
        }
        
        keyboard
    } else {
        make_inline_keyboard(buttons, 2)
    };

    let value_template = t8x!(Ru, "{value} выбрано", &ln);
    let empty_template = t8x!(Ru, "(пусто)", &ln);

    let countries_display = if current_settings.countries.is_empty() {
        empty_template.to_string()
    } else {
        strfmt!(value_template, value => current_settings.countries.len())?
    };

    let cities_display = if current_settings.cities.is_empty() {
        empty_template.to_string()
    } else {
        strfmt!(value_template, value => current_settings.cities.len())?
    };

    let states_display = if current_settings.states.is_empty() {
        empty_template.to_string()
    } else {
        strfmt!(value_template, value => current_settings.states.len())?
    };

    let zip_codes_display = if current_settings.zipcodes.is_empty() {
        empty_template.to_string()
    } else {
        strfmt!(value_template, value => current_settings.zipcodes.len())?
    };

    let asns_display = if current_settings.asns.is_empty() {
        empty_template.to_string()
    } else {
        strfmt!(value_template, value => current_settings.asns.len())?
    };

    let anonymous_filter_display = if current_settings.anonymous_filter {
        t8x!(Ru, "✅ Включен", &ln)
    } else {
        t8x!(Ru, "❌ Выключен", &ln)
    };

    let rotation_interval_display = match current_settings.rotation_interval {
        Some(interval) => strfmt!(t8x!(Ru, "{interval} минут", &ln), interval)?,
        None => t8x!(Ru, "(не установлен)", &ln).to_string(),
    };

    let advanced_settings_note = if current_settings.countries.is_empty() {
        t8x!(Ru, "\n💡 <i>Выберите страны, чтобы получить доступ к расширенным настройкам локации</i>", &ln)
    } else {
        ""
    };

    let message = strfmt!(
        t8x!(Ru, r#"
            ⚙️ <b>Настройки прокси по умолчанию</b> ⚙️

            📋 <b>Текущие настройки:</b>
            🌍 <b>Страны:</b> {countries_display}
            🏙️ <b>Города:</b> {cities_display}
            🗺️ <b>Штаты:</b> {states_display}
            📮 <b>Почтовые индексы:</b> {zip_codes_display}
            🔢 <b>ASN сети:</b> {asns_display}
            🕶️ <b>Анонимный фильтр:</b> {anonymous_filter_display}
            ⏱️ <b>Интервал ротации:</b> {rotation_interval_display}
            
            ⚠️ Настройки используются для белого списка{advanced_settings_note}
            
            Используйте кнопки ниже для изменения параметров:
        "#, &ln),
        countries_display,
        cities_display,
        states_display,
        zip_codes_display,
        asns_display,
        anonymous_filter_display,
        rotation_interval_display,
        advanced_settings_note
    )?;

    match settings.behavior {
        ForceHandlerBehavior::NewMessage => {
            bot.send_message(msg.chat.id, message)
                .reply_markup(keyboard)
                .parse_mode(ParseMode::Html)
                .await?;
        }
        _ => {
            bot.edit_message_text(msg.chat.id, msg.id, message)
                .reply_markup(keyboard)
                .parse_mode(ParseMode::Html)
                .await?;
        }
    }

    Ok(())
}

pub async fn advanced_location_settings_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    let buttons: Vec<InlineButton<DefaultProxySettingsCallback>> = vec![
        (t8x!(Ru, "🏙️ Города 🏙️", &ln), DefaultProxySettingsCallback::EditCities { pool }).into(),
        (t8x!(Ru, "🗺️ Штаты 🗺️", &ln), DefaultProxySettingsCallback::EditStates { pool }).into(),
        (t8x!(Ru, "📮 Почтовые индексы 📮", &ln), DefaultProxySettingsCallback::EditZipCodes { pool }).into(),
        (t8x!(Ru, "🔢 ASN сети 🔢", &ln), DefaultProxySettingsCallback::EditASNs { pool }).into(),
        (t8x!(Ru, "🔙 Назад к настройкам 🔙", &ln), DefaultProxySettingsCallback::ManageDefaultSettings { pool }).into(),
    ];

    let keyboard = make_inline_keyboard(buttons, 2);

    let message = t8x!(Ru, r#"
            🗺️ <b>Расширенные настройки локации</b> 🗺️
            
            ⚠️ Внимание! ⚠️
            ⚠️ При использовании расширенных настроек локации трафик может списываться в повышенном объеме в зависимости от выбранных параметров.

            Выберите параметр для настройки:
        "#, &ln);

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

    Ok(())
}

pub async fn edit_countries_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    
    let current_settings = match get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    let countries = match get_or_fetch_countries(&dialogue, pool).await {
        Ok(countries) => countries.into_iter().map(|c| Location { code: c.code, name: c.name, count: c.count }).collect(),
        Err(e) => {
            log::error!("Failed to get countries: {}", e);
            let message = t8x!(Ru, "❌ Ошибка загрузки стран", &ln);
            bot.edit_message_text(msg.chat.id, msg.id, message).await?;
            return Ok(());
        }
    };
    
    let mut config = countries_selection_config(settings.language);
    config.back_callback = DefaultProxySettingsCallback::ManageDefaultSettings { pool };
    show_default_location_selection(bot, msg, 0, pool, countries, &current_settings.countries, settings, config).await
}

pub async fn edit_cities_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    
    let current_settings = match get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    let selected_countries: Vec<Country> = current_settings.countries.iter()
        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
        .collect();
    
    let cities = match get_or_fetch_cities(&dialogue, pool, selected_countries, vec![]).await {
        Ok(cities) => cities.into_iter().map(|c| Location { code: c.code, name: c.name, count: c.count }).collect(),
        Err(e) => {
            log::error!("Failed to get cities: {}", e);
            let message = t8x!(Ru, "❌ Ошибка загрузки городов", &ln);
            bot.edit_message_text(msg.chat.id, msg.id, message).await?;
            return Ok(());
        }
    };
    
    let mut config = cities_selection_config(settings.language);
    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
    show_default_location_selection(bot, msg, 0, pool, cities, &current_settings.cities, settings, config).await
}

pub async fn edit_states_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    
    let current_settings = match get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    let selected_countries: Vec<Country> = current_settings.countries.iter()
        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
        .collect();
    
    let states = match get_or_fetch_states(&dialogue, pool, selected_countries).await {
        Ok(states) => states.into_iter().map(|s| Location { code: s.code, name: s.name, count: s.count }).collect(),
        Err(e) => {
            log::error!("Failed to get states: {}", e);
            let message = t8x!(Ru, "❌ Ошибка загрузки штатов", &ln);
            bot.edit_message_text(msg.chat.id, msg.id, message).await?;
            return Ok(());
        }
    };
    
    let mut config = states_selection_config(settings.language);
    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
    show_default_location_selection(bot, msg, 0, pool, states, &current_settings.states, settings, config).await
}

pub async fn edit_zip_codes_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    
    let current_settings = match get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    let selected_countries: Vec<Country> = current_settings.countries.iter()
        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
        .collect();
    
    let zip_codes = match get_or_fetch_zip_codes(&dialogue, pool, selected_countries, vec![], vec![]).await {
        Ok(zip_codes) => zip_codes.into_iter().map(|z| Location { code: z.code, name: z.name, count: z.count }).collect(),
        Err(e) => {
            log::error!("Failed to get zip codes: {}", e);
            let message = t8x!(Ru, "❌ Ошибка загрузки почтовых индексов", &ln);
            bot.edit_message_text(msg.chat.id, msg.id, message).await?;
            return Ok(());
        }
    };
    
    let mut config = zip_codes_selection_config(settings.language);
    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
    show_default_location_selection(bot, msg, 0, pool, zip_codes, &current_settings.zipcodes, settings, config).await
}

pub async fn edit_asns_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    
    let current_settings = match get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    let selected_countries: Vec<Country> = current_settings.countries.iter()
        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
        .collect();
    
    let asns = match get_or_fetch_asns(&dialogue, pool, selected_countries, vec![], vec![]).await {
        Ok(asns) => asns.into_iter().map(|a| Location { code: a.code, name: a.name, count: a.count }).collect(),
        Err(e) => {
            log::error!("Failed to get ASNs: {}", e);
            let message = t8x!(Ru, "❌ Ошибка загрузки ASN", &ln);
            bot.edit_message_text(msg.chat.id, msg.id, message).await?;
            return Ok(());
        }
    };
    
    let mut config = asns_selection_config(settings.language);
    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
    show_default_location_selection(bot, msg, 0, pool, asns, &current_settings.asns, settings, config).await
}

pub async fn toggle_anonymous_filter_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let mut current_settings = match get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    current_settings.anonymous_filter = !current_settings.anonymous_filter;
    
    match api::save_default_proxy_settings(msg.chat.id.0, pool, current_settings).await {
        Ok(fresh_settings) => {
            if let Ok(Some(mut state)) = dialogue.get().await {
                state.update_default_settings(fresh_settings);
                dialogue.update(state).await?;
            }
        }
        Err(e) => {
            log::error!("Failed to save anonymous filter setting: {}", e);
        }
    }
    
    manage_default_proxy_settings_handler(bot, msg, pool, dialogue, settings).await
}

pub async fn edit_rotation_interval_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    let pool_name = pool.display_name(&ln);
    
    let message = format!(
        "⏱️ Настройка интервала ротации для пула: {}\n\n📝 Введите интервал ротации в минутах (например: 10):",
        pool_name
    );
    
    let back_button = InlineKeyboardButton::callback(
        t8x!(Ru, "🔙Назад🔙", &ln),
        DefaultProxySettingsCallback::ManageDefaultSettings { pool }.to_string()
    );
    let keyboard = InlineKeyboardMarkup::new(vec![vec![back_button]]);
    
    match settings.behavior {
        ForceHandlerBehavior::NewMessage => {
            bot.send_message(msg.chat.id, message)
                .reply_markup(keyboard)
                .parse_mode(ParseMode::Html)
                .await?;
        }
        _ => {
            bot.edit_message_text(msg.chat.id, msg.id, message)
                .reply_markup(keyboard)
                .parse_mode(ParseMode::Html)
                .await?;
        }
    }
    
    super::update_state_preserving_cache(&dialogue, UserStateKind::ReceiveRotationInterval { selected_pool: pool }).await?;
    
    Ok(())
}

pub async fn reset_to_defaults_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    let pool_name = pool.display_name(&ln);
    
    let message = strfmt!(t8x!(Ru, r#"
        🔄 <b>Сброс к умолчанию для пула {pool}</b>
        
        ⚠️ <b>Эта операция сбросит все настройки к значениям по умолчанию.</b>
        
        ⚠️ <i>Логика сброса будет добавлена позже</i>
    "#, &ln), pool => pool_name)?;

    let buttons = vec![
        (t8x!(Ru, "✅ Подтвердить сброс ✅", &ln), DefaultProxySettingsCallback::SaveSettings { pool }).into(),
        (t8x!(Ru, "🔙Назад к настройкам🔙", &ln), DefaultProxySettingsCallback::ManageDefaultSettings { pool }).into(),
    ];
    let keyboard = make_inline_keyboard(buttons, 1);
    
    bot.edit_message_text(msg.chat.id, msg.id, message)
        .parse_mode(teloxide::types::ParseMode::Html)
        .reply_markup(keyboard)
        .await?;
    
    Ok(())
}

pub async fn save_settings_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    let pool_name = pool.display_name(&ln);
    
    let default_settings = DefaultProxySettings::default();
    
    let message = match api::save_default_proxy_settings(msg.chat.id.0, pool, default_settings).await {
        Ok(_) => {
            strfmt!(t8x!(Ru, r#"
                💾<b>Сохранить настройки для пула {pool}</b>
                
                ✅ <b>Настройки успешно сохранены!</b>
                
                Все параметры сброшены к значениям по умолчанию.
            "#, &ln), pool => pool_name)?
        }
        Err(e) => {
            log::error!("Failed to save default settings: {}", e);
            strfmt!(t8x!(Ru, r#"
                💾 <b>Сохранение настроек для пула {pool}</b>
                
                ❌ <b>Ошибка при сохранении настроек</b>
                
                Попробуйте позже или обратитесь к администратору.
            "#, &ln), pool => pool_name)?
        }
    };

    let buttons = vec![
        (t8x!(Ru, "🔙Назад к настройкам🔙", &ln), DefaultProxySettingsCallback::ManageDefaultSettings { pool }).into()
    ];
    let keyboard = make_inline_keyboard(buttons, 1);
    
    bot.edit_message_text(msg.chat.id, msg.id, message)
        .parse_mode(teloxide::types::ParseMode::Html)
        .reply_markup(keyboard)
        .await?;
    
    Ok(())
}

pub async fn default_proxy_settings_callback_handler(
    bot: Bot,
    q: CallbackQuery,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
    profile: Profile,
) -> HandlerResult {
    let ln = settings.language;

    if let Some(data) = q.data.clone() {
        if let Some(message) = get_callback_message(q.clone()) {
            let callback: DefaultProxySettingsCallback = serde_json::from_str(&data)?;
            
            match callback {
                DefaultProxySettingsCallback::ManageDefaultSettings { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    manage_default_proxy_settings_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::AdvancedLocationSettings { pool } => {
                    bot.answer_callback_query(q.id.clone()).text(t8x!(Ru, r#"
                            ⚠️ Внимание! ⚠️
                            При использовании расширенных настроек локации трафик может списываться в повышенном объеме в зависимости от выбранных параметров.
                        "#, &ln))
                        .show_alert(true)
                        .send()
                        .await?;
                    advanced_location_settings_handler(bot, message, pool, settings).await?;
                }
                DefaultProxySettingsCallback::EditCountries { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_countries_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::EditCities { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_cities_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::EditStates { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_states_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::EditZipCodes { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_zip_codes_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::EditASNs { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_asns_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::BackToAdvancedLocation { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    advanced_location_settings_handler(bot, message, pool, settings).await?;
                }
                DefaultProxySettingsCallback::EditExcludeCountries { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_exclude_countries_handler(bot, message, pool, settings).await?;
                }
                DefaultProxySettingsCallback::EditExcludeASNs { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_exclude_asns_handler(bot, message, pool, settings).await?;
                }
                DefaultProxySettingsCallback::ToggleAnonymousFilter { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    toggle_anonymous_filter_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::EditRotationInterval { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    edit_rotation_interval_handler(bot, message, pool, dialogue, settings).await?;
                }
                DefaultProxySettingsCallback::ResetToDefaults { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    reset_to_defaults_handler(bot, message, pool, settings).await?;
                }
                DefaultProxySettingsCallback::SaveSettings { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    save_settings_handler(bot, message, pool, settings).await?;
                }
                DefaultProxySettingsCallback::Back { pool } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    super::proxy_management_menu_handler(bot, message, dialogue, pool, settings, profile).await?;
                }
                DefaultProxySettingsCallback::CountryPage { pool, page } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let countries = match super::get_or_fetch_countries(&dialogue, pool).await {
                        Ok(countries) => countries.into_iter().map(|c| Location { code: c.code, name: c.name, count: c.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = countries_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::ManageDefaultSettings { pool };
                    show_default_location_selection(bot, message, page, pool, countries, &current_settings.countries, settings, config).await?;
                }
                DefaultProxySettingsCallback::CountrySelect { pool, index } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let countries = match super::get_or_fetch_countries(&dialogue, pool).await {
                        Ok(countries) => countries.into_iter().map(|c| Location { code: c.code, name: c.name, count: c.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = countries_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::ManageDefaultSettings { pool };
                    handle_default_location_select(bot, message, pool, index, dialogue, settings, countries, config).await?;
                }
                DefaultProxySettingsCallback::CityPage { pool, page } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let cities = match super::get_or_fetch_cities(&dialogue, pool, selected_countries, vec![]).await {
                        Ok(cities) => cities.into_iter().map(|c| Location { code: c.code, name: c.name, count: c.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = cities_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    show_default_location_selection(bot, message, page, pool, cities, &current_settings.cities, settings, config).await?;
                }
                DefaultProxySettingsCallback::CitySelect { pool, index } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let cities = match super::get_or_fetch_cities(&dialogue, pool, selected_countries, vec![]).await {
                        Ok(cities) => cities.into_iter().map(|c| Location { code: c.code, name: c.name, count: c.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = cities_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    handle_default_location_select(bot, message, pool, index, dialogue, settings, cities, config).await?;
                }
                DefaultProxySettingsCallback::StatePage { pool, page } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let states = match super::get_or_fetch_states(&dialogue, pool, selected_countries).await {
                        Ok(states) => states.into_iter().map(|s| Location { code: s.code, name: s.name, count: s.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = states_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    show_default_location_selection(bot, message, page, pool, states, &current_settings.states, settings, config).await?;
                }
                DefaultProxySettingsCallback::StateSelect { pool, index } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let states = match super::get_or_fetch_states(&dialogue, pool, selected_countries).await {
                        Ok(states) => states.into_iter().map(|s| Location { code: s.code, name: s.name, count: s.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = states_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    handle_default_location_select(bot, message, pool, index, dialogue, settings, states, config).await?;
                }
                DefaultProxySettingsCallback::ZipCodePage { pool, page } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let zip_codes = match super::get_or_fetch_zip_codes(&dialogue, pool, selected_countries, vec![], vec![]).await {
                        Ok(zip_codes) => zip_codes.into_iter().map(|z| Location { code: z.code, name: z.name, count: z.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = zip_codes_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    show_default_location_selection(bot, message, page, pool, zip_codes, &current_settings.zipcodes, settings, config).await?;
                }
                DefaultProxySettingsCallback::ZipCodeSelect { pool, index } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let zip_codes = match super::get_or_fetch_zip_codes(&dialogue, pool, selected_countries, vec![], vec![]).await {
                        Ok(zip_codes) => zip_codes.into_iter().map(|z| Location { code: z.code, name: z.name, count: z.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = zip_codes_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    handle_default_location_select(bot, message, pool, index, dialogue, settings, zip_codes, config).await?;
                }
                DefaultProxySettingsCallback::ASNPage { pool, page } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let asns = match super::get_or_fetch_asns(&dialogue, pool, selected_countries, vec![], vec![]).await {
                        Ok(asns) => asns.into_iter().map(|a| Location { code: a.code, name: a.name, count: a.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = asns_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    show_default_location_selection(bot, message, page, pool, asns, &current_settings.asns, settings, config).await?;
                }
                DefaultProxySettingsCallback::ASNSelect { pool, index } => {
                    bot.answer_callback_query(q.id.clone()).await?;
                    
                    let current_settings = super::get_or_fetch_default_settings(&dialogue, message.chat.id.0, pool).await.unwrap_or_default();
                    let selected_countries: Vec<Country> = current_settings.countries.iter()
                        .map(|code| Country { code: code.clone(), name: code.clone(), count: 0 })
                        .collect();
                    let asns = match super::get_or_fetch_asns(&dialogue, pool, selected_countries, vec![], vec![]).await {
                        Ok(asns) => asns.into_iter().map(|a| Location { code: a.code, name: a.name, count: a.count }).collect(),
                        Err(_) => vec![],
                    };
                    
                    let mut config = asns_selection_config(settings.language);
                    config.back_callback = DefaultProxySettingsCallback::BackToAdvancedLocation { pool };
                    handle_default_location_select(bot, message, pool, index, dialogue, settings, asns, config).await?;
                }
            }
        }
    }
    
    Ok(())
}

async fn show_default_location_selection(
    bot: Bot,
    msg: Message,
    page: usize,
    pool: PoolType,
    locations: Vec<Location>,
    selected_items: &[String],
    settings: HandlerSettings,
    config: DefaultLocationSelectionConfig,
) -> HandlerResult {
    let ln = settings.language;
    
    let start_idx = page * ITEMS_PER_PAGE;
    let end_idx = std::cmp::min(start_idx + ITEMS_PER_PAGE, locations.len());
    let total_pages = locations.len().div_ceil(ITEMS_PER_PAGE);
    
    let mut keyboard = InlineKeyboardMarkup::default();
    
    let selected_count = selected_items.len();
    
    let header = strfmt!(&config.header, 
        icon => config.icon,
        location_type => config.location_type_name,
        location_type_singular => config.location_type_name_singular,
        pool => pool.display_name(&ln),
        total => locations.len(),
        selected => selected_count,
        current_page => page + 1,
        total_pages => total_pages
    )?;
    
    let mut current_row = Vec::new();
    for (i, location) in locations[start_idx..end_idx].iter().enumerate() {
        let is_selected = selected_items.contains(&location.code);
        let checkmark = if is_selected { "✅ " } else { "" };
        let button_text = format!("{}{} ({})", checkmark, location.name, location.count);
        let button = InlineKeyboardButton::callback(
            button_text,
            (config.select_callback)(pool, start_idx + i).to_string()
        );
        current_row.push(button);
        
        if current_row.len() == ITEMS_PER_ROW || i == locations[start_idx..end_idx].len() - 1 {
            keyboard = keyboard.append_row(current_row.clone());
            current_row.clear();
        }
    }
    
    if total_pages > 1 {
        let mut pagination_row = Vec::new();
        
        if page > 0 {
            pagination_row.push(InlineKeyboardButton::callback(
                "⬅️",
                (config.page_callback)(pool, page - 1).to_string()
            ));
        }
        
        pagination_row.push(InlineKeyboardButton::callback(
            format!("{}/{}", page + 1, total_pages),
            Callback::Noop.to_string()
        ));
        
        if page < total_pages - 1 {
            pagination_row.push(InlineKeyboardButton::callback(
                "➡️",
                (config.page_callback)(pool, page + 1).to_string()
            ));
        }
        
        keyboard = keyboard.append_row(pagination_row);
    }
    
    keyboard = keyboard.append_row(vec![
        InlineKeyboardButton::callback(
            t8x!(Ru, "✅ Подтвердить выбор", &ln),
            config.back_callback.to_string()
        )
    ]);
    
    bot.edit_message_text(msg.chat.id, msg.id, header)
        .reply_markup(keyboard)
        .parse_mode(ParseMode::Html)
        .await?;
    
    Ok(())
}

async fn handle_default_location_select(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    index: usize,
    dialogue: MasterDialogue,
    settings: HandlerSettings,
    locations: Vec<Location>,
    config: DefaultLocationSelectionConfig,
) -> HandlerResult {
    let ln = settings.language;
    
    let current_page = index / ITEMS_PER_PAGE;
    
    let mut current_settings = match super::get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    if let Some(location) = locations.get(index) {
        let location_code = &location.code;
        
        let mut selected_items = match config.location_type {
            LocationType::Countries => current_settings.countries.clone(),
            LocationType::Cities => current_settings.cities.clone(),
            LocationType::States => current_settings.states.clone(),
            LocationType::ZipCodes => current_settings.zipcodes.clone(),
            LocationType::ASNs => current_settings.asns.clone(),
        };
        
        if let Some(pos) = selected_items.iter().position(|c| c == location_code) {
            selected_items.remove(pos);
            log::info!("{}", format!("Removed {} {} from default settings", config.location_type_name_singular, location.name).bright_black());
        } else {
            selected_items.push(location_code.clone());
            log::info!("{}", format!("Added {} {} to default settings", config.location_type_name_singular, location.name).bright_black());
        }
        
        match config.location_type {
            LocationType::Countries => current_settings.countries = selected_items,
            LocationType::Cities => current_settings.cities = selected_items,
            LocationType::States => current_settings.states = selected_items,
            LocationType::ZipCodes => current_settings.zipcodes = selected_items,
            LocationType::ASNs => current_settings.asns = selected_items,
        };
        
        match api::save_default_proxy_settings(msg.chat.id.0, pool, current_settings).await {
            Ok(fresh_settings) => {
                if let Ok(Some(mut state)) = dialogue.get().await {
                    state.update_default_settings(fresh_settings);
                    dialogue.update(state).await?;
                }
            }
            Err(e) => {
                log::error!("Failed to save default settings: {}", e);
                let message = t8x!(Ru, "❌ Ошибка сохранения настроек", &ln);
                bot.edit_message_text(msg.chat.id, msg.id, message).await?;
                return Ok(());
            }
        }
    }
    
    let updated_settings = super::get_or_fetch_default_settings(&dialogue, msg.chat.id.0, pool).await.unwrap_or_default();
    let selected_items = match config.location_type {
        LocationType::Countries => &updated_settings.countries,
        LocationType::Cities => &updated_settings.cities,
        LocationType::States => &updated_settings.states,
        LocationType::ZipCodes => &updated_settings.zipcodes,
        LocationType::ASNs => &updated_settings.asns,
    };
    
    show_default_location_selection(bot, msg, current_page, pool, locations, selected_items, settings, config).await
}

fn countries_selection_config(ln: Language) -> DefaultLocationSelectionConfig {
    DefaultLocationSelectionConfig {
        header: t8x!(Ru, r#"
            {icon} <b>Редактирование {location_type} для пула {pool}</b>
            
            📊 Всего {location_type}: {total} | Выбрано: {selected}
            📄 Страница: {current_page}/{total_pages}
            
            Выберите {location_type_singular} из списка:
        "#, &ln).to_string(),
        icon: "🌍".to_string(),
        location_type_name: t8x!(Ru, "стран", &ln).to_string(),
        location_type_name_singular: t8x!(Ru, "страны", &ln).to_string(),
        location_type: LocationType::Countries,
        select_callback: Arc::new(|pool, index| DefaultProxySettingsCallback::CountrySelect { pool, index }),
        page_callback: Arc::new(|pool, page| DefaultProxySettingsCallback::CountryPage { pool, page }),
        back_callback: DefaultProxySettingsCallback::ManageDefaultSettings { pool: PoolType::Residential }, // Will be overridden
    }
}

fn cities_selection_config(ln: Language) -> DefaultLocationSelectionConfig {
    DefaultLocationSelectionConfig {
        header: t8x!(Ru, r#"
            {icon} <b>Редактирование {location_type} для пула {pool}</b>
            
            📊 Всего {location_type}: {total} | Выбрано: {selected}
            📄 Страница: {current_page}/{total_pages}
            
            Выберите {location_type_singular} из списка:
        "#, &ln).to_string(),
        icon: "🏙️".to_string(),
        location_type_name: t8x!(Ru, "городов", &ln).to_string(),
        location_type_name_singular: t8x!(Ru, "города", &ln).to_string(),
        location_type: LocationType::Cities,
        select_callback: Arc::new(|pool, index| DefaultProxySettingsCallback::CitySelect { pool, index }),
        page_callback: Arc::new(|pool, page| DefaultProxySettingsCallback::CityPage { pool, page }),
        back_callback: DefaultProxySettingsCallback::BackToAdvancedLocation { pool: PoolType::Residential }, // Will be overridden
    }
}

fn states_selection_config(ln: Language) -> DefaultLocationSelectionConfig {
    DefaultLocationSelectionConfig {
        header: t8x!(Ru, r#"
            {icon} <b>Редактирование {location_type} для пула {pool}</b>
            
            📊 Всего {location_type}: {total} | Выбрано: {selected}
            📄 Страница: {current_page}/{total_pages}
            
            Выберите {location_type_singular} из списка:
        "#, &ln).to_string(),
        icon: "🗺️".to_string(),
        location_type_name: t8x!(Ru, "штатов", &ln).to_string(),
        location_type_name_singular: t8x!(Ru, "штаты", &ln).to_string(),
        location_type: LocationType::States,
        select_callback: Arc::new(|pool, index| DefaultProxySettingsCallback::StateSelect { pool, index }),
        page_callback: Arc::new(|pool, page| DefaultProxySettingsCallback::StatePage { pool, page }),
        back_callback: DefaultProxySettingsCallback::BackToAdvancedLocation { pool: PoolType::Residential }, // Will be overridden
    }
}

fn zip_codes_selection_config(ln: Language) -> DefaultLocationSelectionConfig {
    DefaultLocationSelectionConfig {
        header: t8x!(Ru, r#"
            {icon} <b>Редактирование {location_type} для пула {pool}</b>
            
            📊 Всего {location_type}: {total} | Выбрано: {selected}
            📄 Страница: {current_page}/{total_pages}
            
            Выберите {location_type_singular} из списка:
        "#, &ln).to_string(),
        icon: "📮".to_string(),
        location_type_name: t8x!(Ru, "почтовых индексов", &ln).to_string(),
        location_type_name_singular: t8x!(Ru, "почтовые индексы", &ln).to_string(),
        location_type: LocationType::ZipCodes,
        select_callback: Arc::new(|pool, index| DefaultProxySettingsCallback::ZipCodeSelect { pool, index }),
        page_callback: Arc::new(|pool, page| DefaultProxySettingsCallback::ZipCodePage { pool, page }),
        back_callback: DefaultProxySettingsCallback::BackToAdvancedLocation { pool: PoolType::Residential }, // Will be overridden
    }
}

fn asns_selection_config(ln: Language) -> DefaultLocationSelectionConfig {
    DefaultLocationSelectionConfig {
        header: t8x!(Ru, r#"
            {icon} <b>Редактирование {location_type} для пула {pool}</b>
            
            📊 Всего {location_type}: {total} | Выбрано: {selected}
            📄 Страница: {current_page}/{total_pages}
            
            Выберите {location_type_singular} из списка:
        "#, &ln).to_string(),
        icon: "🔢".to_string(),
        location_type_name: t8x!(Ru, "ASN", &ln).to_string(),
        location_type_name_singular: t8x!(Ru, "ASN", &ln).to_string(),
        location_type: LocationType::ASNs,
        select_callback: Arc::new(|pool, index| DefaultProxySettingsCallback::ASNSelect { pool, index }),
        page_callback: Arc::new(|pool, page| DefaultProxySettingsCallback::ASNPage { pool, page }),
        back_callback: DefaultProxySettingsCallback::BackToAdvancedLocation { pool: PoolType::Residential }, // Will be overridden
    }
}

pub async fn edit_exclude_countries_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    let pool_name = pool.display_name(&ln);
    
    let message = strfmt!(t8x!(Ru, r#"
        🚫 <b>Редактирование исключаемых стран для пула {pool}</b>
        
        📝 <b>Текущие исключенные страны:</b>
        • (пусто - логика будет добавлена позже)
        
        ⚠️ <i>Функция в разработке</i>
    "#, &ln), pool => pool_name)?;

    let buttons = vec![
        (t8x!(Ru, "🔙Назад к настройкам🔙", &ln), DefaultProxySettingsCallback::ManageDefaultSettings { pool }).into()
    ];
    let keyboard = make_inline_keyboard(buttons, 1);
    
    bot.edit_message_text(msg.chat.id, msg.id, message)
        .parse_mode(teloxide::types::ParseMode::Html)
        .reply_markup(keyboard)
        .await?;
    
    Ok(())
}

pub async fn edit_exclude_asns_handler(
    bot: Bot,
    msg: Message,
    pool: PoolType,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    let pool_name = pool.display_name(&ln);
    
    let message = strfmt!(t8x!(Ru, r#"
        🚫 <b>Редактирование исключаемых ASN для пула {pool}</b>
        
        📝 <b>Текущие исключенные ASN:</b>
        • (пусто - логика будет добавлена позже)
        
        ⚠️ <i>Функция в разработке</i>
    "#, &ln), pool => pool_name)?;

    let buttons = vec![
        (t8x!(Ru, "🔙Назад к настройкам🔙", &ln), DefaultProxySettingsCallback::ManageDefaultSettings { pool }).into()
    ];
    let keyboard = make_inline_keyboard(buttons, 1);
    
    bot.edit_message_text(msg.chat.id, msg.id, message)
        .parse_mode(teloxide::types::ParseMode::Html)
        .reply_markup(keyboard)
        .await?;
    
    Ok(())
}

pub async fn receive_rotation_interval(
    bot: Bot,
    msg: Message,
    dialogue: MasterDialogue,
    selected_pool: PoolType,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;
    let input = msg.text().unwrap_or("").trim();
    
    let mut current_settings = match super::get_or_fetch_default_settings(&dialogue, msg.chat.id.0, selected_pool).await {
        Ok(settings) => settings,
        Err(e) => {
            log::warn!("Failed to fetch default settings: {}", e);
            DefaultProxySettings::default()
        }
    };
    
    let new_interval = if input.is_empty() {
        None // Remove rotation interval
    } else {
        match input.parse::<u32>() {
            Ok(minutes) if minutes > 0 => Some(minutes),
            _ => {
                let message = t8x!(Ru, "❌ Неверный формат. Введите число больше 0 или оставьте пустым для отключения ротации.", &ln);
                bot.send_message(msg.chat.id, message).await?;
                return Ok(());
            }
        }
    };
    
    current_settings.rotation_interval = new_interval;
    
    match api::save_default_proxy_settings(msg.chat.id.0, selected_pool, current_settings).await {
        Ok(fresh_settings) => {
            if let Ok(Some(mut state)) = dialogue.get().await {
                state.update_default_settings(fresh_settings);
                dialogue.update(state).await?;
            }
            
            let success_message = if let Some(interval) = new_interval {
                format!("✅ Интервал ротации установлен: {} минут", interval)
            } else {
                "✅ Интервал ротации отключен".to_string()
            };
            
            let keyboard = make_inline_keyboard(
                vec![(t8x!(Ru, "🔙Назад к настройкам🔙", &ln), DefaultProxySettingsCallback::ManageDefaultSettings { pool: selected_pool }).into()],
                1,
            );
            
            bot.send_message(msg.chat.id, success_message)
                .reply_markup(keyboard)
                .await?;
        }
        Err(e) => {
            log::error!("Failed to save rotation interval setting: {}", e);
            let error_message = t8x!(Ru, "❌ Не удалось сохранить интервал ротации. Попробуйте позже.", &ln);
            let keyboard = make_inline_keyboard(
                vec![(t8x!(Ru, "🔙Назад к настройкам🔙", &ln), DefaultProxySettingsCallback::ManageDefaultSettings { pool: selected_pool }).into()],
                1,
            );
            
            bot.send_message(msg.chat.id, error_message)
                .reply_markup(keyboard)
                .await?;
        }
    }
    
    super::update_state_preserving_cache(&dialogue, UserStateKind::UserMenu).await?;
    Ok(())
} 
