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

fn get_language_display_name(language: &Language) -> &'static str {
    match language {
        Language::En => "🇺🇸English",
        Language::Ru => "🇷🇺Русский",
    }
}

pub fn make_profile_inline_keyboard(ln: Language, _profile: Profile) -> InlineKeyboardMarkup {
    use Callback::*;

    let mut buttons: Vec<InlineButton<Callback>> = vec![
        (t8x!(Ru, "🛒 Купить трафик🛒",         &ln), BuyTraffic { pool: None }).into(),
        (t8x!(Ru, "🎁 Активировать промокод🎁", &ln), ActivatePromo).into(),
        (t8x!(Ru, "⚙️ Управление прокси ⚙️",    &ln), ManageProxy).into(),
        (t8x!(Ru, "👥 Реферальная система👥",   &ln), Referral).into(),
        (t8x!(Ru, "⚙️ API⚙️",                   &ln), Api).into(),
        (t8x!(Ru, "🔧 Расширенные функции🔧",   &ln), AdvancedFeatures).into(),
    ];

    buttons.push((t8x!(Ru, "🌎Set English language🌎",   &ln), ChangeLanguage).into());

    make_inline_keyboard(buttons, 1)
}

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

    match dialogue.get_or_fetch_profile(msg.chat.id.0).await {
        Ok(profile_data) => {
            let _username = profile_data.username.clone().unwrap_or_else(|| msg.chat.id.0.to_string());
            
            let mut balance_info = String::new();
            for pool_type in PoolType::all() {
                let pool_info = profile_data.get_pool_or_default(&pool_type);
                let pool_name = pool_type.display_name(&ln);
                balance_info.push_str(&format!("  · {}: <code>{}</code>\n", pool_name, pool_info.balance_format));
            }
            
            let language_display = get_language_display_name(&profile_data.language);
            
            // <b>🆔Ваш айди</b>: {user_id}
            let message = strfmt!(t8x!(Ru, r#"
                    👤 <b>Профиль</b>
                    🔹<b>ID</b>: <code>{user_id}</code>
                    🔹<b>Количество покупок</b>: <code>{purchase_count}</code>
                    🔹<b>Количество ГБ куплено</b>: <code>{purchase_sum_gb}</code>
                    🔹<b>Язык</b>: {language}
            
                    📊<b>Осталось трафика</b>:
                      {balance_info}
                "#, &ln),
                user_id => profile_data.id,
                //username => username,
                purchase_count => profile_data.purchase_count,
                purchase_sum_gb => profile_data.purchase_sum_gb,
                language => language_display,
                balance_info => balance_info.trim().to_string()
            )?;

            let keyboard = make_profile_inline_keyboard(ln, profile);

            if settings.behavior == ForceHandlerBehavior::DeleteMessage {
                bot.delete_message(msg.chat.id, msg.id).await?;
                bot.send_message(msg.chat.id, message)
                    .parse_mode(teloxide::types::ParseMode::Html)
                    .reply_markup(keyboard)
                    .await?;
            } else {
                bot.edit_message_text(msg.chat.id, msg.id, message)
                    .parse_mode(teloxide::types::ParseMode::Html)
                    .reply_markup(keyboard)
                    .await?;
            }
            crate::ui::user::update_state_preserving_cache(&dialogue, UserStateKind::Profile).await?;
        }
        Err(e) => {
            log::error!("{}", e);
            return error_handler(bot, dialogue, msg, settings).await;
        }
    }
    Ok(())
}

pub async fn refresh_profile_handler(
    bot: Bot,
    dialogue: MasterDialogue,
    msg: Message,
    settings: HandlerSettings,
    profile: Profile,
) -> HandlerResult {
    profile_handler(bot, dialogue, msg, profile, settings).await
}

pub fn make_advanced_features_keyboard(ln: Language, profile: Profile) -> InlineKeyboardMarkup {
    use Callback::*;

    let mut buttons: Vec<InlineButton<Callback>> = vec![
        (t8x!(Ru, "🌐 Логин на сайте🌐", &ln), WebsiteLogin).into(),
        (t8x!(Ru, "🏢 Реселлерский профиль🏢", &ln), ResellerProfile).into(),
        (t8x!(Ru, "🔗 Объединить аккаунт🔗", &ln), MergeAccount).into(),
    ];

    if profile.email.is_none() {
        buttons.push((t8x!(Ru, "📧 Привязать почту📧", &ln), BindEmail).into());
    }

    buttons.push((t8x!(Ru, "🔙Назад к профилю🔙", &ln), BackToProfile).into());

    make_inline_keyboard(buttons, 1)
}

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

    let message = t8x!(Ru, r#"
        🔧 <b>Расширенные функции</b>
        
        Здесь находятся дополнительные настройки и функции для вашего аккаунта.
    "#, &ln);

    let keyboard = make_advanced_features_keyboard(ln, profile);

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

    Ok(())
}

pub async fn reseller_profile_handler(
    bot: Bot,
    dialogue: MasterDialogue,
    msg: Message,
    settings: HandlerSettings,
) -> HandlerResult {
    let ln = settings.language;

    match api::get_reseller_profile(msg.chat.id.0).await {
        Ok(reseller_profile) => {
            let message = strfmt!(t8x!(Ru, r#"
                🏢 <b>Реселлерский профиль</b>
                
                🆔 <b>ID реселлера</b>: <code>{id}</code>
                🔑 <b>API ключ</b>: <code>{api_key}</code>
                
                📊 <b>Статистика</b>:
                • Трафик: <code>{traffic_formatted}</code>
                • Субпользователи: <code>{subusers_count}</code>
            "#, &ln),
                id => reseller_profile.id,
                api_key => reseller_profile.api_key,
                traffic_formatted => reseller_profile.traffic_formatted,
                subusers_count => reseller_profile.subusers_count
            )?;

            let keyboard = make_inline_keyboard(
                vec![(t8x!(Ru, "🔙Назад к расширенным функциям🔙", &ln), Callback::AdvancedFeatures).into()],
                1,
            );

            bot.edit_message_text(msg.chat.id, msg.id, message)
                .parse_mode(teloxide::types::ParseMode::Html)
                .reply_markup(keyboard)
                .await?;
        }
        Err(e) => {
            log::error!("Failed to get reseller profile: {}", e);
            let error_message = t8x!(Ru, "❌ Не удалось получить реселлерский профиль. Возможно, у вас нет прав реселлера.", &ln);
            let keyboard = make_inline_keyboard(
                vec![(t8x!(Ru, "🔙Назад к расширенным функциям🔙", &ln), Callback::AdvancedFeatures).into()],
                1,
            );
            
            bot.edit_message_text(msg.chat.id, msg.id, error_message)
                .reply_markup(keyboard)
                .await?;
        }
    }

    Ok(())
}
