import json
import os
import logging
from aiogram.types import Message, CallbackQuery, FSInputFile
from aiogram.filters import Command, CommandObject
from aiogram import Router, F
from aiogram.fsm.context import FSMContext
from models.admin import Admin
from models.user import User
from states.state import GetHyperLinkState, EditPriceState, AdminMailingState, AdminCreatePromoDiscountState, \
            AdminCreatePromoTrafficState
from keyboards import inline_admin, inline
from utils import helpers
from config import ADMIN_IDS, LightningProxiesAPI_KEY
from LightningProxiesAPI import LightningProxiesAPI

router = Router()

# Set up logger for traffic checking
logger = logging.getLogger(__name__)

async def get_user_traffic_left(user_id: int, admin_model: Admin) -> str:
    """Get total traffic left for a user across all active subscriptions"""
    #logger.info(f"🔍 Starting traffic check for user_id: {user_id}")
    
    try:
        proxy_api = LightningProxiesAPI(LightningProxiesAPI_KEY)
        #logger.info("✅ Lightning Proxies API initialized successfully")
        
        subscriptions = await admin_model.get_subscriptions_user(user_id)
        #logger.info(f"📊 Found {len(subscriptions)} active subscriptions for user {user_id}")
        
        if not subscriptions:
            logger.info("❌ No active subscriptions found")
            return "0.00 GB"
            
        total_traffic_left = 0.0
        successful_calls = 0
        
        for i, subscription in enumerate(subscriptions):
            plan_type = subscription["plan"]
            plan_id = subscription["planID"]
            #logger.info(f"🔄 Processing subscription {i+1}/{len(subscriptions)}: {plan_type} (Plan ID: {plan_id})")
            
            try:
                if plan_type == "Mobile":
                    #logger.info(f"📱 Calling Mobile API for plan {plan_id}")
                    info = proxy_api.get_mobile_proxy_info(plan_id)
                    bandwidth_left = float(info.get('bandwidthLeft', 0))
                    #logger.info(f"✅ Mobile API response: bandwidthLeft = {bandwidth_left} GB")
                    total_traffic_left += bandwidth_left
                    successful_calls += 1
                    
                elif plan_type == "Residential": 
                    #logger.info(f"🏠 Calling Residential API for plan {plan_id}")
                    info = proxy_api.get_residential_proxy_info(plan_id)
                    bandwidth_left = float(info.get('bandwidthLeft', 0))
                    #logger.info(f"✅ Residential API response: bandwidthLeft = {bandwidth_left} GB")
                    total_traffic_left += bandwidth_left
                    successful_calls += 1
                    
                elif plan_type in ["IPV6 Bandwidth", "IPV6 Unlimited"]:
                    #logger.info(f"🌐 Calling IPv6 API for plan {plan_id} (type: {plan_type})")
                    info = proxy_api.get_ipv6_proxy_info(plan_id)
                    #logger.info(f"📋 IPv6 API response keys: {list(info.keys())}")
                    
                    if 'bandwidthLeft' in info:
                        bandwidth_left = float(info.get('bandwidthLeft', 0))
                        #logger.info(f"✅ IPv6 API response: bandwidthLeft = {bandwidth_left} GB")
                        total_traffic_left += bandwidth_left
                        successful_calls += 1
                    else:
                        logger.info(f"⚠️ IPv6 plan {plan_id} doesn't have bandwidthLeft field (unlimited plan)")
                        
                else:
                    logger.info(f"⚠️ Unknown plan type: {plan_type} - skipping")
                    
            except Exception as e:
                logger.error(f"❌ API call failed for {plan_type} plan {plan_id}: {str(e)}")
                continue
                
        #logger.info(f"📊 Final result: {total_traffic_left:.2f} GB total from {successful_calls}/{len(subscriptions)} successful API calls")
        return f"{total_traffic_left:.2f} GB"
        
    except Exception as e:
        logger.error(f"❌ Critical error in get_user_traffic_left: {str(e)}")
        return "N/A"

@router.message(Command("admin"))
async def admin_panel(message: Message) -> Message:
    if message.from_user.id not in ADMIN_IDS:
        return await message.answer('❌У вас нет прав для использования этой команды')

    return await message.answer('<b>🎭ADMIN PANEL | PROXY SELLER🎭</b>\n\n'
                                '<b>⚙️Список команд:</b>\n'
                                '⚙️/profile {username} - получить профиль пользователя\n'
                                '⚙️/profile_id {id} - получить профиль пользователя\n',
                                reply_markup = inline_admin.admin_menu())

@router.message(Command("profile"))
async def profile_process(message: Message, command: CommandObject, admin_model: Admin) -> Message:
    if message.from_user.id not in ADMIN_IDS:
        return await message.answer('❌У вас нет прав для использования этой команды')

    if command.args is None:
        return await message.answer(
            "❌Ошибка: не переданы аргументы. /profile {username}"
        )

    username: str = command.args.split(" ", maxsplit=1)[0]
    user_profile: dict = await admin_model.get_user_by_name(username)

    if user_profile is None:
        return await message.answer(
            "❌Ошибка: username не найден!"
        )

    counts_orders: int = len(await admin_model.get_orders_by_user_id(user_profile["user_id"]))
    counts_active_plans: int  = len(await admin_model.get_subscriptions_user(user_profile['user_id']))
    traffic_left = await get_user_traffic_left(user_profile["user_id"], admin_model)

    return await message.answer(f"<b>👤Профиль пользователя @{user_profile['username']}</b>\n\n"
                                f"🆔: <code>{user_profile['user_id']}</code>\n"
                                f"🉐Язык: <code>{user_profile['language']}</code>\n"
                                f"📅Дата создания профиля: <code>{user_profile['created_at']}</code>\n"
                                f"💰Реферальный баланс: <code>{user_profile['referral_balance']}$</code>\n"
                                f"👥Количество рефералов: <code>{user_profile['referral_counts']}</code>\n"
                                f"🛒Количество заказов: <code>{counts_orders}</code>\n"
                                f"🎭Количество активных планов: <code>{counts_active_plans}</code>\n"
                                f"📊Трафик осталось: <code>{traffic_left}</code>")

@router.message(Command("profile_id"))
async def profile_process(message: Message, command: CommandObject, user_model: User, admin_model: Admin) -> Message:
    if message.from_user.id not in ADMIN_IDS:
        return await message.answer('❌У вас нет прав для использования этой команды')

    if command.args is None:
        return await message.answer(
            "❌Ошибка: не переданы аргументы. /profile_id {id}"
        )

    user_id: str = command.args.split(" ", maxsplit=1)[0]
    if not user_id.isdigit():
        return await message.answer(
            "❌Ошибка: ID - число. /profile_id {id}"
        )


    user_profile: dict = await user_model.get_by_user_id(int(user_id))

    if user_profile is None:
        return await message.answer(
            "❌Ошибка: username не найден!"
        )

    counts_orders: int = len(await admin_model.get_orders_by_user_id(user_profile["user_id"]))
    counts_active_plans: int  = len(await admin_model.get_subscriptions_user(user_profile['user_id']))
    traffic_left = await get_user_traffic_left(user_profile["user_id"], admin_model)

    return await message.answer(f"<b>👤Профиль пользователя @{user_profile['username']}</b>\n\n"
                                f"🆔: <code>{user_profile['user_id']}</code>\n"
                                f"🉐Язык: <code>{user_profile['language']}</code>\n"
                                f"📅Дата создания профиля: <code>{user_profile['created_at']}</code>\n"
                                f"💰Реферальный баланс: <code>{user_profile['referral_balance']}$</code>\n"
                                f"👥Количество рефералов: <code>{user_profile['referral_counts']}</code>\n"
                                f"🛒Количество заказов: <code>{counts_orders}</code>\n"
                                f"🎭Количество активных планов: <code>{counts_active_plans}</code>\n"
                                f"📊Трафик осталось: <code>{traffic_left}</code>")


@router.callback_query(F.data == 'payments_systems')
async def edit_payments_system(callback_query: CallbackQuery, admin_model: Admin):
    payments_systems = await admin_model.get_payments_systems()
    return await callback_query.message.edit_text('<b>↘️Выберите платежную систему</b>',
                                                  reply_markup= inline_admin.admin_payments_menu(payments_systems))


@router.callback_query(F.data.startswith('edit_payment_'))
async def process_edit_payment_status(callback_query: CallbackQuery, admin_model: Admin):
    payment_system_id: int = int(callback_query.data.split('_')[2])
    payment_system_info = await admin_model.get_payment_system_by_id(payment_system_id)
    return await callback_query.message.edit_text(f'<b>⚙️Настройки платежной системы '
                                                  f'{payment_system_info["system"]}</b>\n\n'
                                                  f'<b>💡Статус:</b>'
                                                  f' {"🟢" if payment_system_info["is_active"] else "🔴"}',
                                                  reply_markup= inline_admin.payments_status_menu(payment_system_id,
                                                                payment_system_info["is_active"]))

@router.callback_query(F.data.startswith('status_'))
async def change_status(callback_query: CallbackQuery, admin_model: Admin):
    payment_system_id: int = int(callback_query.data.split('_')[1])
    payment_status: str = callback_query.data.split('_')[2]

    if payment_status == 'off':
        await admin_model.update_payment_system(payment_system_id, 'is_active', False)

    if payment_status == 'on':
        await admin_model.update_payment_system(payment_system_id, 'is_active', True)

    payment_system_info = await admin_model.get_payment_system_by_id(payment_system_id)
    return await callback_query.message.edit_text(f'<b>⚙️Настройки платежной системы'
                                                  f' {payment_system_info["system"]}</b>\n\n'
                                                  f'<b>💡Статус:</b> '
                                                  f'{"🟢" if payment_system_info["is_active"] else "🔴"}',
                                                  reply_markup= inline_admin.payments_status_menu(payment_system_id,
                                                                payment_system_info["is_active"]))

@router.callback_query(F.data == 'admin_back')
async def admin_back_callback(callback_query: CallbackQuery, state: FSMContext  ):
    await state.clear()
    await callback_query.message.delete()

    if callback_query.from_user.id not in ADMIN_IDS:
        return await callback_query.message.answer('❌У вас нет прав для использования этой команды')

    return await callback_query.message.answer('<b>🎭ADMIN PANEL | PROXY SELLER🎭</b>\n\n'
                                '<b>⚙️Список команд:</b>\n'
                                '⚙️/profile {username} - получить профиль пользователя\n'
                                '⚙️/profile_id {id} - получить профиль пользователя\n',
                                reply_markup = inline_admin.admin_menu())

@router.callback_query(F.data == 'hyperlink')
async def hyperlink_callback(callback_query: CallbackQuery):
    return await callback_query.message.edit_text('<b>⚙️Выберите действие</b>',
                                                  reply_markup=inline_admin.hyperlink_menu())

@router.callback_query(F.data == 'create_hyperlink')
async def hyperlink_callback(callback_query: CallbackQuery, state: FSMContext ):
    await callback_query.message.edit_text('<b>⚙️Напишите ссылку (ваш текст после start={your_text)</b>',
                                                  reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(GetHyperLinkState.hyperlink)

@router.message(GetHyperLinkState.hyperlink)
async def get_hyperlink(message: Message, state: FSMContext, admin_model: Admin) -> Message:
    await state.clear()
    hyperlink: int = await admin_model.create_hyperlink(message.text)
    return await message.answer(f'✅Ваша ссылка #{hyperlink}: <code>{message.text}</code> успешно создана!',
                                reply_markup = inline_admin.admin_back_menu())


@router.callback_query(F.data == 'active_hyperlink')
async def hyperlink_callback(callback_query: CallbackQuery, admin_model: Admin):
    hyperlink_data: dict = await admin_model.get_all_hyperlinks()
    return await callback_query.message.edit_text('<b>⚙️Выберите ссылку</b>',
                                                  reply_markup=inline_admin.active_hyperlink_menu(hyperlink_data))

@router.callback_query(F.data.startswith('edit_hyperlink_'))
async def edit_hyperlink_callback(callback_query: CallbackQuery, admin_model: Admin):
    hyperlink_id: str = callback_query.data.split('edit_hyperlink_')[1]
    hyperlink_info = await admin_model.get_hyperlink_by_id(int(hyperlink_id))
    return await callback_query.message.edit_text(f'🆔: <code>{hyperlink_id}</code>\n'
                           f'🔗<code>https://t.me/{(await callback_query.bot.get_me()).username}?'
                                                  f'start={hyperlink_info["link"]}\n</code>\n'
                                                  f'👁Переходов: <code>{hyperlink_info["counts"]}</code>\n',
                           reply_markup=inline_admin.edit_hyperlink_menu(hyperlink_id))

@router.callback_query(F.data.startswith('delete_hyperlink_'))
async def delete_hyperlink_callback(callback_query: CallbackQuery, admin_model: Admin):
    hyperlink_id: str = callback_query.data.split('delete_hyperlink_')[1]
    await admin_model.delete_hyperlink_by_id(int(hyperlink_id))
    return await callback_query.message.edit_text(f'✅Ссылка #{hyperlink_id} удалена!',
                                                  reply_markup=inline_admin.admin_back_menu())

@router.callback_query(F.data.startswith('users_hyperlink_'))
async def delete_hyperlink_callback(callback_query: CallbackQuery, admin_model: Admin):
    hyperlink_id: str = callback_query.data.split('users_hyperlink_')[1]
    users = await admin_model.get_users_by_hyperlink_id(int(hyperlink_id))

    if len(users) == 0:
        return await callback_query.message.edit_text('❌Нет пользователей для выгрузки!',
                                                      reply_markup=inline_admin.admin_back_menu())

    file = await helpers.generate_file_with_users_hyperlink(users, './tempfiles/')
    document = FSInputFile(file)

    await callback_query.message.delete()
    await callback_query.message.answer_document(document, caption = '👤Список пользователей перешедших по ссылке',
                                                  reply_markup=inline_admin.admin_back_menu())
    return os.remove(file)


@router.callback_query(F.data == 'edit_price')
async def edit_price_callback(callback_query: CallbackQuery, admin_model: Admin):
    products: dict = await admin_model.get_products()
    return await callback_query.message.edit_text('<b>⚙️Выберите продукт</b>',
                                           reply_markup=inline_admin.edit_price_products_menu(products))

@router.callback_query(F.data.startswith('edit_product_'))
async def edit_price_product_callback(callback_query: CallbackQuery, admin_model: Admin):
    product_id: int = int(callback_query.data.split('edit_product_')[1])
    variants: dict = await admin_model.get_variants(product_id)
    return await callback_query.message.edit_text('<b>⚙️Выберите товар</b>',
                                           reply_markup=inline_admin.edit_price_variants_menu(variants))

@router.callback_query(F.data.startswith('back_variants_'))
async def admin_back_callback(callback_query: CallbackQuery, state: FSMContext, admin_model: Admin):
    await state.clear()
    await callback_query.message.delete()

    product_id: int = int(callback_query.data.split('back_variants_')[1])
    variants: dict = await admin_model.get_variants(product_id)

    return await callback_query.message.answer('<b>⚙️Выберите товар</b>',
                                           reply_markup=inline_admin.edit_price_variants_menu(variants))

@router.callback_query(F.data.startswith('edit_variant_'))
async def edit_price_product_callback(callback_query: CallbackQuery, admin_model: Admin):
    variant_id: int = int(callback_query.data.split('edit_variant_')[1])
    variant_info: dict = await admin_model.get_variant_by_id(variant_id)
    product_info: dict = await admin_model.get_product_by_id(variant_info['product_id'])

    return await callback_query.message.edit_text('<b>⚙️Информация по товару</b>\n\n'
                                           f'💡Название: <code>{product_info["name"]} {variant_info["name"]}</code>\n'
                                           f'🛒Категория: <code>{product_info["name"]}</code>\n'
                                           f'💵Цена: <code>{variant_info["price"]}$</code>\n',
                                           reply_markup=inline_admin.edit_variant_menu(variant_id,
                                                                                       variant_info['product_id']))

@router.callback_query(F.data.startswith('change_price_'))
async def variant_edit_price_callback(callback_query: CallbackQuery, state: FSMContext):
    variant_id: int = int(callback_query.data.split('change_price_')[1])
    await callback_query.message.edit_text('<b>✏️Напишите новую цену в $</b>\n'
                                           'ℹ️Пример чисел: <code>13.5 или 13</code>',
                                           reply_markup=inline_admin.admin_back_menu())
    await state.update_data(variant_id=variant_id)
    return await state.set_state(EditPriceState.price)

@router.message(EditPriceState.price)
async def process_edit_price(message: Message, state: FSMContext, admin_model: Admin):
    data = await state.get_data()
    variant_id: int = data['variant_id']

    if not helpers.is_number(message.text):
        return await message.answer('❌Принимаются только числа, попробуйте еще раз!')

    await state.clear()
    await admin_model.update_variant(variant_id, 'price', message.text)
    return await message.answer(f'<b>✅Вы успешно изменили цену на</b> <code>{message.text}$</code>',
                                reply_markup=inline_admin.admin_back_menu())


@router.callback_query(F.data == 'mailing')
async def mailing_users(callback_query: CallbackQuery,  state: FSMContext):
    await callback_query.message.edit_text('⚙️Ваше следующее сообщение будет рассылкой!',
                                           reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(AdminMailingState.message)
    
@router.message(AdminMailingState.message)
async def check_mailing_message(message: Message, state: FSMContext):
    await message.copy_to(message.chat.id,
                           reply_markup=inline_admin.edit_mailing_menu())
    return await state.set_state(AdminMailingState.check)
    

@router.callback_query(AdminMailingState.check)
async def process_mailing_message(callback_query: CallbackQuery, state: FSMContext, admin_model: Admin):
    await state.clear()

    if callback_query.data == 'send_mailing':
        counts: int = 0
        users: dict = await admin_model.get_all_users()
        for user in users:
            try:
                await callback_query.message.copy_to(user["user_id"], parse_mode="HTML")
                counts += 1
            except Exception as e:
                print(e)
                pass

        return await callback_query.message.edit_text(f'🟢Рассылка завершена!\n📩Доставлено сообщений: {counts} из {len(users)}')

    if callback_query.data == 'edit_mailing':
        await callback_query.message.edit_text('⚙️Пришлите ваше новое сообщение!', 
                                               reply_markup=inline_admin.admin_back_menu())
        return await state.set_state(AdminMailingState.message)

@router.callback_query(F.data == 'stats')
async def stats_callback(callback_query: CallbackQuery, admin_model: Admin):
    stats: dict = await admin_model.get_order_counts_and_totals()
    await callback_query.message.edit_text('<b>📊Статистика</b>\n\n'
                                           '<b>👥Пользователи</b>\n\n'
                                           f'За 1 день: <code>{stats["users"]["1_day"]}</code>\n'
                                           f'За 7 дней: <code>{stats["users"]["7_days"]}</code>\n'
                                           f'За 30 дней: <code>{stats["users"]["30_days"]}</code>\n'
                                           f'За все время: <code>{stats["users"]["all_time"]}</code>\n\n'
                                           f'<b>🎭Подписки</b>\n\n'
                                           f'За 1 день: <code>{stats["subscriptions"]["1_day"]}</code>\n'
                                           f'За 7 дней: <code>{stats["subscriptions"]["7_days"]}</code>\n'
                                           f'За 30 дней: <code>{stats["subscriptions"]["30_days"]}</code>\n'
                                           f'За все время: <code>{stats["subscriptions"]["all_time"]}</code>\n\n'
                                           f'<b>🛒Заказы</b>\n\n'
                                           f'За 1 день: <code>{stats["orders"]["1_day"]}$</code>\n'
                                           f'За 7 дней: <code>{stats["orders"]["7_days"]}$</code>\n'
                                           f'За 30 дней: <code>{stats["orders"]["30_days"]}$</code>\n'
                                           f'За все время: <code>{stats["orders"]["all_time"]}$</code>\n\n',
                                           reply_markup=inline_admin.admin_back_menu())

@router.callback_query(F.data == 'promo_list')
async def promo_list_callback(callback_query: CallbackQuery):
    return await callback_query.message.edit_text('⚙️Выберите действие',
                                                  reply_markup=inline_admin.promo_actions_menu())

@router.callback_query(F.data == 'create_promo')
async def create_promo_callback(callback_query: CallbackQuery):
    return await callback_query.message.edit_text('⚙️Выберите какой промокод создать',
                                                  reply_markup=inline_admin.create_promo_menu())

@router.callback_query(F.data == 'create_discount')
async def create_promo_discount_callback(callback_query: CallbackQuery, state: FSMContext):
    await callback_query.message.edit_text('✏️️Напишите промокод', reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(AdminCreatePromoDiscountState.promo)

@router.message(AdminCreatePromoDiscountState.promo)
async def get_promo_discount(message: Message, state: FSMContext, admin_model: Admin):
    is_promo_exits = await admin_model.get_promo_discount_by_promo(message.text)
    if is_promo_exits is not None:
        return await message.answer('❌Такой промокод уже существует, придумайте другой!')

    await state.update_data(promo=message.text)
    await message.answer('✏️Напишите количество активаций', reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(AdminCreatePromoDiscountState.total)

@router.message(AdminCreatePromoDiscountState.total)
async def get_promo_discount_total_callback(message: Message, state: FSMContext, admin_model: Admin):
    if not message.text.isdigit():
        return await message.answer('❌Только числовое значение', reply_markup=inline_admin.admin_back_menu())

    if int(message.text) < 1:
        return await message.answer('❌Число активаций должно быть больше 1',
                                    reply_markup=inline_admin.admin_back_menu())

    await state.update_data(total=int(message.text))
    await message.answer('✏️Напишите процент скидки', reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(AdminCreatePromoDiscountState.discount)


@router.message(AdminCreatePromoDiscountState.discount)
async def process_create_discount_promo(message: Message, state: FSMContext, admin_model: Admin):
    if not message.text.isdigit():
        return await message.answer('❌Только числовое значение', reply_markup=inline_admin.admin_back_menu())

    if int(message.text) < 1 or int(message.text) > 100:
        return await message.answer('❌Процент скидки должен быть выше 1 и не больше 99',
                                    reply_markup=inline_admin.admin_back_menu())

    data: dict = await state.get_data()
    await state.clear()

    await admin_model.create_promo_discount(data['promo'], data['total'], int(message.text))
    return await message.answer(f'✅Промокод: <code>{data["promo"]}</code> <b>успешно создан!</b>\n'
                                f'ℹ️Число активаций: <code>{data["total"]}</code>\n'
                                f'🛍Процент скидки: <code>{message.text}</code>\n',
                                reply_markup=inline_admin.admin_back_menu())

@router.callback_query(F.data == 'create_traffic')
async def create_traffic_callback(callback_query: CallbackQuery, admin_model: Admin):
    data_products: dict = await admin_model.get_products()
    return await callback_query.message.edit_text('⚙️Выберите продукт для промокода',
                                        reply_markup=inline_admin.create_promo_traffic_products_menu(data_products))

@router.callback_query(F.data.startswith('traffic_promo_'))
async def select_product_traffic_callback(callback_query: CallbackQuery, state: FSMContext, admin_model: Admin):
    product_id: int = int(callback_query.data.split('traffic_promo_')[1])
    product_info: dict = await admin_model.get_product_by_id(product_id)

    await state.update_data(product_id=product_id)
    if product_info['name'] in ['Mobile', 'Residential', 'IPV6 Bandwidth']:
        await callback_query.message.edit_text('✏️Напишите количество GB '
                                               '(только целое число или формата float - 0.15)\n\n'
                                               'ℹ️Для IPV6 Bandwidth: '
                                               '5, 100, 250, 500, 1000',
                                               reply_markup=inline_admin.admin_back_menu())
        return await state.set_state(AdminCreatePromoTrafficState.bandwidth)

    if product_info['name'] == 'ISP Proxies':
        await callback_query.message.edit_text('️✏️Напишите количество прокси',
                                               reply_markup=inline_admin.admin_back_menu())
        return await state.set_state(AdminCreatePromoTrafficState.count)

    if product_info['name'] == 'IPV6 Unlimited':
        variants: dict = await admin_model.get_variants(product_id)
        await callback_query.message.edit_text("⚙️Выберите вариант",
                                               reply_markup=inline.variants_ipv_category_menu(variants))
        return await state.set_state(AdminCreatePromoTrafficState.variant_id)

@router.callback_query(AdminCreatePromoTrafficState.variant_id)
async def process_get_speed_callback(callback_query: CallbackQuery, state: FSMContext):
    if callback_query.data.startswith('back'):
        await state.clear()
        return await callback_query.message.edit_text('<b>🎭ADMIN PANEL | PROXY SELLER🎭</b>\n\n'
                                    '<b>⚙️Список команд:</b>\n'
                                    '⚙️/profile {username} - получить профиль пользователя\n'
                                    '⚙️/profile_id {id} - получить профиль пользователя\n',
                                    reply_markup=inline_admin.admin_menu())

    variant_id = int(callback_query.data.split('_')[1])
    await state.update_data(variant_id=variant_id)
    await callback_query.message.edit_text('✏️Напишите ваш промокод', reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(AdminCreatePromoTrafficState.promo)


@router.message(AdminCreatePromoTrafficState.count)
async def process_get_count_promo(message: Message, state: FSMContext):
    if not message.text.isdigit():
        return await message.answer('❌Принимаются только числа, попробуйте еще раз!')

    await state.update_data(count=message.text)
    await message.answer('🏳️Выберите страну из списка', reply_markup=inline.isp_proxies_menu())
    return await state.set_state(AdminCreatePromoTrafficState.country)

@router.callback_query(AdminCreatePromoTrafficState.country)
async def process_get_country_promo(callback_query: CallbackQuery, state: FSMContext):
    region_code: str = callback_query.data.split('_')[1]
    await state.update_data(country=region_code)
    await callback_query.message.edit_text('✏️Напишите ваш промокод', reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(AdminCreatePromoTrafficState.promo)


@router.message(AdminCreatePromoTrafficState.bandwidth)
async def process_get_bandwidth_promo(message: Message, state: FSMContext):
    if not helpers.is_number(message.text):
        return await message.answer('❌Принимаются только числа, попробуйте еще раз!')

    await state.update_data(bandwidth=message.text)
    await message.answer('✏️Напишите ваш промокод', reply_markup=inline_admin.admin_back_menu())
    return await state.set_state(AdminCreatePromoTrafficState.promo)

@router.message(AdminCreatePromoTrafficState.promo)
async def process_create_promo_traffic(message: Message, state: FSMContext, admin_model: Admin):
    data = await state.get_data()
    product_info: dict = await admin_model.get_product_by_id(data['product_id'])

    await state.clear()

    if product_info['name'] in ['Mobile', 'Residential', 'IPV6 Bandwidth']:
        promo_attributes = json.dumps({
            "product_id": data['product_id'],
            "bandwidth": data['bandwidth']
        })
        await admin_model.create_promo_traffic(message.text, promo_attributes)

    if product_info['name'] == 'ISP Proxies':
        promo_attributes = json.dumps({
            "product_id": data['product_id'],
            "region": data['country'],
            "ip": data['count']
        })
        await admin_model.create_promo_traffic(message.text, promo_attributes)

    if product_info['name'] == 'IPV6 Unlimited':
        variant_info: dict = await admin_model.get_variant_by_id(data['variant_id'])

        promo_attributes = {
            "product_id": data['product_id']
        }
        all_attributes = {**promo_attributes, **json.loads(variant_info['attributes'])}

        await admin_model.create_promo_traffic(message.text, json.dumps(all_attributes))

    return await message.answer(f'✅Ваш промокод <code>{message.text}</code> '
                                    f'на товар: <code>{product_info["name"]}</code> успешно создан',
                                reply_markup=inline_admin.admin_back_menu())