from flask import Flask
from telebot import TeleBot, logger
from telebot.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from app.bot.keyboards.settings_menu import get_settings_menu
from app.bot.utils.helpers import get_user_subscribed_regions
from app import Subscriptions
from app.bot.utils.tg_audit import log_user_event
from app.extensions.db import db
from app.bot.states import UserStateManager
from app.bot.constants import UserStates

def process_unsubscribe_button(message: Message, app: Flask, bot: TeleBot, chat_id: int, state_manager: UserStateManager):
    unsubbed_regions = []
    invalid_regions = []
    username = f"{message.from_user.username}" if message.from_user.username else "N/A"

    parts = [part.strip() for part in message.text.split(',')]
    if not parts or not all(part.isdigit() for part in parts):
        markup = InlineKeyboardMarkup()
        markup.add(InlineKeyboardButton('Отмена', callback_data='cancel_input'))

        bot.send_message(chat_id,
                         "Неверный ввод, введите число(а) через запятую, либо нажмите отмена.",
                         reply_markup=markup)

        def delayed_handler(msg):
            process_unsubscribe_button(msg, app, bot, chat_id, state_manager)

        bot.register_next_step_handler(message, delayed_handler)
        return

    region_ids = [int(part) for part in parts]

    try:
        with app.app_context():
            valid_region_ids = [int(region[0]) for region in get_user_subscribed_regions(chat_id)]

            for region_id in region_ids:
                if region_id not in valid_region_ids:
                    invalid_regions.append(str(region_id))
                    continue

                subscription = Subscriptions.query.filter_by(chat_id=chat_id, region_id=region_id).first()
                if subscription:
                    subscription.active = False
                    db.session.add(subscription)
                    unsubbed_regions.append(str(region_id))

            db.session.commit()


    except Exception as e:
        bot.send_message(chat_id, "⚠ Произошла ошибка при обработке запроса. Попробуйте позже.")
        logger.error(f"Unexpected Error: {e}")
        return

    if unsubbed_regions:
        bot.send_message(chat_id, f"✅ Вы успешно отписались от регионов: {', '.join(unsubbed_regions)}")
        log_user_event(chat_id, app, username, f"Отписался от регионов: {', '.join(unsubbed_regions)}")
    if invalid_regions:
        bot.send_message(chat_id,
                         f"⚠ Регионы с ID {', '.join(invalid_regions)} не найдены среди ваших подписок и не были изменены.")

    state_manager.set_state(chat_id, UserStates.SETTINGS_MENU)
    bot.send_message(chat_id, "⚙ Вернулись в меню настроек.", reply_markup=get_settings_menu())