from aiogram import Router, F, Bot
from aiogram.types import Message, CallbackQuery
from aiogram.fsm.context import FSMContext
from states import PaymentStates
from keyboards import get_subscription_plans_keyboard, get_payment_keyboard
from config import SUBSCRIPTION_PLANS, PAYMENT_CARD_NUMBER, PAYMENT_CARD_OWNER
from database import create_payment_request, get_user, activate_subscription, add_wallet_balance, get_discount_code, use_discount_code
from utils.subscription_utils import is_premium_user, get_subscription_info

router = Router()

@router.message(F.text.contains("اشتراک"))
async def show_sub_msg(message: Message):
    premium = await is_premium_user(message.from_user.id)
    if premium:
        sub_info = await get_subscription_info(message.from_user.id)
        text = f"⭐ <b>اشتراک VIP شما فعال است</b>\n\n⏳ روزهای باقی‌مانده: <b>{sub_info['remaining_days']} روز</b>\n📅 تاریخ پایان: {sub_info['end_date_jalali']}"
    else:
        text = "⭐ <b>خرید اشتراک مربیگری</b>\n\nبا تهیه اشتراک، ربات تبدیل به مربی شخصی شما می‌شود!\n👇 یکی از پلن‌های اقتصادی زیر را انتخاب کنید:"
    await message.answer(text, parse_mode="HTML", reply_markup=get_subscription_plans_keyboard())

@router.callback_query(F.data == "subscription")
async def sub_callback(callback: CallbackQuery):
    await show_sub_msg(callback.message)
    await callback.message.delete()

@router.callback_query(F.data.startswith("buy_plan_"))
async def buy_plan(callback: CallbackQuery, state: FSMContext):
    plan_key = callback.data.replace("buy_plan_", "")
    plan = SUBSCRIPTION_PLANS.get(plan_key)
    if not plan: return
    await state.update_data(selected_plan=plan_key, current_price=plan['price'])
    
    user = await get_user(callback.from_user.id)
    bal = user.get('wallet_balance', 0) if user else 0
    can_pay_wallet = bal >= plan['price']

    text = f"💳 <b>درخواست خرید {plan['name']}</b>\n\n💰 مبلغ قابل پرداخت: <b>{plan['price_display']}</b>\n\n💳 شماره کارت:\n<code>{PAYMENT_CARD_NUMBER}</code>\n👤 به نام: {PAYMENT_CARD_OWNER}\n\n👇 پس از کارت‌به‌کارت، دکمه ارسال رسید را بزنید."
    if can_pay_wallet:
        text += f"\n\n🎁 <b>موجودی کیف پول شما کافیست ({bal:,} تومان). می‌توانید مستقیماً از کیف پول پرداخت کنید!</b>"

    await callback.message.edit_text(text, parse_mode="HTML", reply_markup=get_payment_keyboard(plan_key, can_pay_wallet, has_discount=False))

# زدن دکمه اعمال کد تخفیف
@router.callback_query(F.data.startswith("apply_discount_"))
async def prompt_discount(callback: CallbackQuery, state: FSMContext):
    await callback.message.edit_text("🎟 <b>کد تخفیف خود را وارد کنید:</b>", parse_mode="HTML")
    await state.set_state(PaymentStates.waiting_for_discount)

@router.message(PaymentStates.waiting_for_discount)
async def process_discount(message: Message, state: FSMContext):
    code_text = message.text.strip().upper()
    discount = await get_discount_code(code_text)
    
    if not discount or discount['used_count'] >= discount['max_uses']:
        await message.answer("❌ کد تخفیف نامعتبر است یا ظرفیت آن به پایان رسیده.")
        return
        
    data = await state.get_data()
    plan_key = data.get("selected_plan", "1month")
    plan = SUBSCRIPTION_PLANS.get(plan_key)
    
    orig_price = plan['price']
    percent = discount['percent']
    new_price = int(orig_price * (100 - percent) / 100)
    
    await state.update_data(current_price=new_price, applied_code=code_text)
    
    user = await get_user(message.from_user.id)
    bal = user.get('wallet_balance', 0) if user else 0
    can_pay_wallet = bal >= new_price

    text = f"🎉 <b>کد تخفیف {percent}% با موفقیت اعمال شد!</b>\n\n<s>مبلغ قبلی: {orig_price:,} تومان</s>\n💰 <b>مبلغ نهایی با تخفیف: {new_price:,} تومان</b>\n\n💳 شماره کارت:\n<code>{PAYMENT_CARD_NUMBER}</code>\n👤 به نام: {PAYMENT_CARD_OWNER}\n\n👇 دکمه ارسال رسید را بزنید."
    if can_pay_wallet:
        text += f"\n\n🎁 <b>موجودی کیف پول شما برای این مبلغ کافیست!</b>"
        
    await message.answer(text, parse_mode="HTML", reply_markup=get_payment_keyboard(plan_key, can_pay_wallet, has_discount=True))

@router.callback_query(F.data.startswith("wallet_pay_"))
async def wallet_pay(callback: CallbackQuery, state: FSMContext):
    plan_key = callback.data.replace("wallet_pay_", "")
    plan = SUBSCRIPTION_PLANS.get(plan_key)
    data = await state.get_data()
    price = data.get("current_price", plan['price'])
    
    user = await get_user(callback.from_user.id)
    if user.get('wallet_balance', 0) < price:
        await callback.answer("موجودی کافی نیست!", show_alert=True)
        return
        
    applied_code = data.get("applied_code")
    if applied_code:
        await use_discount_code(applied_code)
        
    await add_wallet_balance(callback.from_user.id, -price)
    await activate_subscription(callback.from_user.id, plan_key, plan['duration_days'], price, callback.from_user.id, "Wallet Pay")
    await callback.message.edit_text("🎉 <b>پرداخت موفق! اشتراک شما فعال شد.</b>", parse_mode="HTML")
    await callback.answer()
    await state.clear()

@router.callback_query(F.data.startswith("send_receipt_"))
async def req_receipt(callback: CallbackQuery, state: FSMContext):
    await callback.message.edit_text("📸 لطفاً عکس فیش واریزی را بفرستید:")
    await state.set_state(PaymentStates.waiting_for_receipt)

@router.message(PaymentStates.waiting_for_receipt)
async def process_receipt(message: Message, state: FSMContext, bot: Bot):
    file_id = message.photo[-1].file_id if message.photo else (message.document.file_id if message.document else None)
    if not file_id: return
    data = await state.get_data()
    plan_key = data.get("selected_plan", "1month")
    plan = SUBSCRIPTION_PLANS.get(plan_key, SUBSCRIPTION_PLANS["1month"])
    price = data.get("current_price", plan['price'])
    applied_code = data.get("applied_code")
    
    if applied_code:
        await use_discount_code(applied_code)
        
    req_id = await create_payment_request(message.from_user.id, plan_key, price, file_id)
    
    from keyboards import get_payment_review_keyboard
    from utils.admin_utils import notify_all_admins
    admin_msg = f"🔔 <b>رسید جدید #{req_id}</b>\n👤 @{message.from_user.username}\n📋 {plan['name']} (مبلغ: {price:,} تومان)"
    await notify_all_admins(bot, admin_msg, reply_markup=get_payment_review_keyboard(req_id), photo=file_id if message.photo else None, document=file_id if message.document else None)
    
    await message.answer("✅ رسید شما ارسال شد.")
    await state.clear()
