import logging

from aiogram import F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery, Message

from bot.services.api import ApiError, api
from bot.services.checkout import show_result, show_timeout, start_payment
from bot.services.texts import crypto, texts
from bot.states.purchase import PurchaseStates

logger = logging.getLogger("bot.payment")
router = Router(name="payment")


@router.callback_query(F.data.startswith("pay:"))
async def choose_method(callback: CallbackQuery, state: FSMContext) -> None:
    _, method, order_id = callback.data.split(":", 2)
    await callback.answer()
    await start_payment(callback, state, callback.from_user.id, order_id, method)
    if method == "bank":
        await state.set_state(PurchaseStates.receipt)


@router.callback_query(F.data.startswith("chk:"))
async def check_payment(callback: CallbackQuery, state: FSMContext) -> None:
    payment_id = callback.data.split(":", 1)[1]
    try:
        result = await api.check_payment(callback.from_user.id, payment_id)
    except ApiError as exc:
        await callback.answer(await texts.error(exc.code), show_alert=True)
        return

    if result.get("expired"):
        await show_timeout(callback, result["order"]["id"])
        await callback.answer()
        return

    if not result.get("paid"):
        await callback.answer(await texts.text("tron_not_found"), show_alert=True)
        return

    await callback.answer()
    await show_result(callback, result["order"])
    await state.clear()


@router.callback_query(F.data.startswith("cpy:"))
async def copy_amount(callback: CallbackQuery) -> None:
    payment_id = callback.data.split(":", 1)[1]
    try:
        data = await api.get(f"/payments/{payment_id}", telegram_id=callback.from_user.id)
    except ApiError as exc:
        await callback.answer(await texts.error(exc.code), show_alert=True)
        return

    amount = crypto(data["payment"].get("payable_amount"))
    await callback.answer(await texts.text("amount_copied", amount=amount), show_alert=True)
    if callback.message:
        await callback.message.answer(f"<code>{amount}</code>")


@router.message(PurchaseStates.receipt, F.photo)
async def upload_receipt(message: Message, state: FSMContext) -> None:
    data = await state.get_data()
    payment_id = data.get("payment_id")
    if not payment_id or not message.photo:
        return

    photo = message.photo[-1]
    file = await message.bot.get_file(photo.file_id)
    buffer = await message.bot.download_file(file.file_path)
    content = buffer.read() if buffer else b""

    try:
        await api.upload_receipt(message.from_user.id, payment_id, content, f"{photo.file_id}.jpg")
    except ApiError as exc:
        await message.answer(await texts.error(exc.code))
        return

    from bot.keyboards.common import main_menu_keyboard

    await state.clear()
    await message.answer(await texts.text("waiting_approval"), reply_markup=await main_menu_keyboard())


@router.message(PurchaseStates.receipt)
async def receipt_required(message: Message) -> None:
    await message.answer(await texts.error("photo_required"))
