from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ContextTypes
from asgiref.sync import sync_to_async
from users.models import User, NotificationSettings

async def settings_menu(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Меню настроек уведомлений."""
    query = update.callback_query
    await query.answer()

    user_id = query.from_user.id
    user = await sync_to_async(User.objects.filter(chat_id=user_id).first)()
    if not user:
        await query.edit_message_text("Вы не зарегистрированы.")
        return

    settings, _ = await sync_to_async(NotificationSettings.objects.get_or_create)(user=user)

    telegram_status = "✅" if settings.telegram_enabled else "❌"
    email_status = "✅" if settings.email_enabled else "❌"

    keyboard = [
        [InlineKeyboardButton(f"{telegram_status} Уведомления в Telegram", callback_data="toggle_telegram")],
        [InlineKeyboardButton(f"{email_status} Уведомления по Email", callback_data="toggle_email")],
        [InlineKeyboardButton("🕒 Настроить время уведомлений", callback_data="set_notification_time")],
        [InlineKeyboardButton("📋 Показать текущие настройки", callback_data="current_settings")],
        [InlineKeyboardButton("🏠 Главная", callback_data="main_menu")],
        [InlineKeyboardButton("🔙 Назад", callback_data="back")],
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await query.edit_message_text("Настройки уведомлений:", reply_markup=reply_markup)

async def toggle_telegram(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Переключение состояния Telegram-уведомлений."""
    query = update.callback_query
    await query.answer()

    user_id = query.from_user.id
    user = await sync_to_async(User.objects.filter(chat_id=user_id).first)()
    if not user:
        await query.edit_message_text("Вы не зарегистрированы.")
        return

    settings, _ = await sync_to_async(NotificationSettings.objects.get_or_create)(user=user)
    settings.telegram_enabled = not settings.telegram_enabled
    await sync_to_async(settings.save)()

    print(f"Пользователь {user_id} переключил Telegram-уведомления: {settings.telegram_enabled}")
    await settings_menu(update, context)


async def toggle_email(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Переключение состояния Email-уведомлений."""
    query = update.callback_query
    await query.answer()

    user_id = query.from_user.id
    user = await sync_to_async(User.objects.filter(chat_id=user_id).first)()
    if not user:
        await query.edit_message_text("Вы не зарегистрированы.")
        return

    settings, _ = await sync_to_async(NotificationSettings.objects.get_or_create)(user=user)
    settings.email_enabled = not settings.email_enabled
    await sync_to_async(settings.save)()

    print(f"Пользователь {user_id} переключил Email-уведомления: {settings.email_enabled}")
    await settings_menu(update, context)


async def show_current_settings(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Отображение текущих настроек уведомлений."""
    query = update.callback_query
    await query.answer()

    user_id = query.from_user.id
    user = await sync_to_async(User.objects.filter(chat_id=user_id).first)()
    if not user:
        await query.edit_message_text("Вы не зарегистрированы.")
        return

    settings, _ = await sync_to_async(NotificationSettings.objects.get_or_create)(user=user)
    telegram_status = "✅ Включены" if settings.telegram_enabled else "❌ Выключены"
    email_status = "✅ Включены" if settings.email_enabled else "❌ Выключены"
    notification_time = settings.notification_time or "Не установлено"

    message = (
        f"📋 Ваши настройки уведомлений:\n"
        f"🔔 Telegram: {telegram_status}\n"
        f"📧 Email: {email_status}\n"
        f"🕒 Время: {notification_time}"
    )
    await query.edit_message_text(message)

async def set_notification_time(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Настройка времени уведомлений."""
    query = update.callback_query
    await query.answer()

    user_id = query.from_user.id
    user = await sync_to_async(User.objects.filter(chat_id=user_id).first)()
    if not user:
        await query.edit_message_text("Вы не зарегистрированы.")
        return

    await query.edit_message_text("Введите новое время для уведомлений в формате HH:MM (например, 08:30):")
    context.user_data["set_time"] = True
    print(f"Пользователь {user_id} настраивает время уведомлений.")