from aiogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton
from keyboards.user_buttons import buy_vpn, my_subscriptions, profile_button, support
from aiogram.types import User
from utils.db import get_plans, get_user_subscriptions_paginated
from vpns.marz import marzban_service
from typing import Dict, List
from marzban import ProxyInbound
from utils.emoji_flags import get_country_flag
from utils.pay_providers import providers

def get_main_menu_keyboard() -> ReplyKeyboardMarkup:
    keyboard = [
        [
            KeyboardButton(text=buy_vpn),
            KeyboardButton(text=my_subscriptions)
        ],
        [
            KeyboardButton(text=profile_button),
            KeyboardButton(text=support)
        ]
    ]
    
    return ReplyKeyboardMarkup(keyboard=keyboard, resize_keyboard=True)

async def get_buy_vpn_keyboard() -> InlineKeyboardMarkup:
    # Get all plans from database
    plans = await get_plans()
    keyboard = [
        [InlineKeyboardButton(text=plan.name + f" ({plan.price}₽)", callback_data=f"buy_{plan.id}")]
        for plan in plans
    ]
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

def get_providers_keyboard() -> InlineKeyboardMarkup:
    global providers
    keyboard = [
        [
            InlineKeyboardButton(text=provider.name, callback_data=f"pay:{provider.callback_data_prefix}")
            for provider in providers.values()
        ],
        [
            InlineKeyboardButton(text="🔙 Назад", callback_data="back")
        ]
    ]   
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

def get_payment_keyboard(pay_link: str, payment_id: int, provider: str) -> InlineKeyboardMarkup:
    keyboard = [
        [
            InlineKeyboardButton(text="💰 Оплатить", url=pay_link),
            InlineKeyboardButton(text="✅ Проверить оплату", callback_data=f"check_payment:{provider}:{payment_id}")
        ],
        [
            InlineKeyboardButton(text="❌ Отменить", callback_data="cancel")
        ]
    ]
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

async def get_my_subscriptions_keyboard(user_id: int, page: int = 1, items_per_page: int = 5) -> InlineKeyboardMarkup:
    # Get paginated subscriptions and total count
    subscriptions, total = await get_user_subscriptions_paginated(user_id, page, items_per_page)
    
    # Calculate total pages
    total_pages = (total + items_per_page - 1) // items_per_page
    
    # Create subscription buttons for current page
    keyboard = [
        [InlineKeyboardButton(text=f"🔑 №{subscription.id} • {subscription.end_date.strftime('%d.%m.%Y')}", 
                             callback_data=f"subscription_{subscription.id}")]
        for subscription in subscriptions
    ]
    
    # Add navigation buttons if needed
    nav_buttons = []
    if total_pages > 1:
        if page > 1:
            nav_buttons.append(InlineKeyboardButton(text="◀️", callback_data=f"subs_page_{page-1}"))
        nav_buttons.append(InlineKeyboardButton(text=f"📄 {page}/{total_pages}", callback_data="ignore"))
        if page < total_pages:
            nav_buttons.append(InlineKeyboardButton(text="▶️", callback_data=f"subs_page_{page+1}"))
    
    if nav_buttons:
        keyboard.append(nav_buttons)
    
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

def get_profile_keyboard() -> InlineKeyboardMarkup:
    keyboard = [
        [InlineKeyboardButton(text="💰 Пополнить баланс", callback_data=f"add_balance")],
        [InlineKeyboardButton(text="🔗 Реферальная система", callback_data="referal_system")]
    ]
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

def get_countries_keyboard(page: int = 1, items_per_page: int = 8) -> InlineKeyboardMarkup:
    """
    Create paginated keyboard for countries selection
 
    :param page: Current page number (1-based)
    :param items_per_page: Number of items per page
    :return: InlineKeyboardMarkup
    """
    keyboard = []
    
    # Get list of countries
    countries = marzban_service.countries
    country_list = list(countries.keys())
    
    # Calculate pagination
    start_idx = (page - 1) * items_per_page
    end_idx = start_idx + items_per_page
    total_pages = (len(country_list) + items_per_page - 1) // items_per_page
    
    # Add country buttons
    for country in country_list[start_idx:end_idx]:
        # Get flag emoji for country
        flag = get_country_flag(country)
        # Add button with country name and flag
        keyboard.append([
            InlineKeyboardButton(
                text=f"{flag} {country}",
                callback_data=f"select_country:{country}"
            )
        ])
    
    # Add navigation buttons if needed
    nav_buttons = []
    if page > 1:
        nav_buttons.append(
            InlineKeyboardButton(
                text="◀️ Назад",
                callback_data=f"countries_page:{page-1}"
            )
        )
    if page < total_pages:
        nav_buttons.append(
            InlineKeyboardButton(
                text="Вперед ▶️",
                callback_data=f"countries_page:{page+1}"
            )
        )
    
    # Add page counter if there are multiple pages
    if total_pages > 1:
        keyboard.append([
            InlineKeyboardButton(
                text=f"📄 {page}/{total_pages}",
                callback_data="ignore"
            )
        ])
    
    # Add navigation buttons if any
    if nav_buttons:
        keyboard.append(nav_buttons)
    
    # Add back button
    keyboard.append([
        InlineKeyboardButton(
            text="🔙 Назад",
            callback_data="back"
        )
    ])
    
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

def get_subscription_keyboard(subscription_id: int) -> InlineKeyboardMarkup:
    keyboard = [
        [
            InlineKeyboardButton(text="🔑 Продлить подписку", callback_data=f"extend_subscription_{subscription_id}")
        ],
        [
            InlineKeyboardButton(text="🔙 Назад", callback_data="back")
        ]
    ]
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

def get_confirm_buy_keyboard(amount: float) -> InlineKeyboardMarkup:
    keyboard = [
        [
            InlineKeyboardButton(text="💰 Оплатить", callback_data=f"confirm_buy:{amount}")
        ],
        [
            InlineKeyboardButton(text="🔙 Назад", callback_data="back")
        ]
    ]
    return InlineKeyboardMarkup(inline_keyboard=keyboard)

def back_keyboard() -> InlineKeyboardMarkup:
    keyboard = [
        [
            InlineKeyboardButton(text="🔙 Назад", callback_data="back")
        ]
    ]
    return InlineKeyboardMarkup(inline_keyboard=keyboard)