from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import ContextTypes
from bot.operations.hotels import manage_hotels, hotel_actions, delete_hotel, check_pms, setup_rooms
from bot.operations.statistics import statistics, stats_select_period, generate_statistics
from bot.operations.settings import settings_menu, toggle_telegram, toggle_email, set_notification_time, show_current_settings
from bot.operations.users import show_users
from django.core.exceptions import ObjectDoesNotExist
from pms_integration.api_client import APIClient

from users.models import User, NotificationSettings
from hotels.models import Hotel

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Обработчик команды /start."""
    user_id = (
        update.message.from_user.id
        if update.message
        else update.callback_query.from_user.id
    )
    print(f"Пользователь {user_id} вызвал команду /start")

    keyboard = [
        [InlineKeyboardButton("📊 Статистика", callback_data="stats")],
        [InlineKeyboardButton("🏨 Управление отелями", callback_data="manage_hotels")],
        [InlineKeyboardButton("👤 Пользователи", callback_data="manage_users")],
        [InlineKeyboardButton("⚙️ Настройки", callback_data="settings")],
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    if update.message:
        await update.message.reply_text("Выберите действие:", reply_markup=reply_markup)
    elif update.callback_query:
        await update.callback_query.edit_message_text("Выберите действие:", reply_markup=reply_markup)



async def handle_button_click(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Обработчик всех нажатий кнопок."""
    query = update.callback_query
    await query.answer()

    callback_data = query.data

    # Сохраняем предыдущее меню для кнопки "Назад"
    context.user_data["previous_menu"] = context.user_data.get("current_menu", "main_menu")
    context.user_data["current_menu"] = callback_data

    if callback_data == "stats":
        await statistics(update, context)
    elif callback_data.startswith("stats_hotel_"):
        await stats_select_period(update, context)
    elif callback_data.startswith("stats_period_"):
        await generate_statistics(update, context)
    elif callback_data == "manage_hotels":
        await manage_hotels(update, context)
    elif callback_data == "manage_users":
        await show_users(update, context)
    elif callback_data.startswith("hotel_"):
        await hotel_actions(update, context)
    elif callback_data.startswith("delete_hotel_"):
        await delete_hotel(update, context)
    elif callback_data.startswith("check_pms_"):
        await check_pms(update, context)
    elif callback_data.startswith("setup_rooms_"):
        await setup_rooms(update, context)
    elif callback_data == "settings":
        await settings_menu(update, context)
    elif callback_data == "toggle_telegram":
        await toggle_telegram(update, context)
    elif callback_data == "toggle_email":
        await toggle_email(update, context)
    elif callback_data == "set_notification_time":
        await set_notification_time(update, context)
    elif callback_data == "current_settings":
        await show_current_settings(update, context)
    elif callback_data == "main_menu":
        await start(update, context)
    elif callback_data == "back":
        await navigate_back(update, context)
    else:
        await query.edit_message_text("Команда не распознана.")


async def navigate_back(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Обработчик кнопки 'Назад'."""
    previous_menu = context.user_data.get("previous_menu", "main_menu")
    context.user_data["current_menu"] = previous_menu

    if previous_menu == "main_menu":
        await start(update, context)
    elif previous_menu == "stats":
        await statistics(update, context)
    elif previous_menu == "manage_hotels":
        await manage_hotels(update, context)
    elif previous_menu == "manage_users":
        await show_users(update, context)
    elif previous_menu.startswith("hotel_"):
        await hotel_actions(update, context)
    else:
        await update.callback_query.edit_message_text("Команда не распознана.")


async def sync_hotel_data(update: Update, context: ContextTypes.DEFAULT_TYPE):
    """Синхронизация данных отеля через API."""
    user_id = update.effective_user.id

    try:
        user = User.objects.get(chat_id=user_id)
        hotels = Hotel.objects.filter(hotel_users__user=user)
    except ObjectDoesNotExist:
        await update.message.reply_text("Вы не зарегистрированы.")
        return

    if not hotels:
        await update.message.reply_text("У вас нет доступных отелей для синхронизации.")
        return

    for hotel in hotels:
        try:
            client = APIClient(hotel.pms)
            client.run(hotel)
            await update.message.reply_text(f"Данные отеля {hotel.name} успешно синхронизированы.")
        except Exception as e:
            await update.message.reply_text(f"Ошибка синхронизации для {hotel.name}: {str(e)}")