import asyncio
import os
from dotenv import load_dotenv

from aiogram import Bot, Dispatcher, F
from aiogram.filters import CommandStart
from aiogram.types import (
    Message, CallbackQuery,
    InlineKeyboardMarkup, InlineKeyboardButton,WebAppInfo
)

from bot.database import (
    init_db, upsert_user, set_user_language, get_user_language,
    create_chat, get_active_chat, update_chat_status,
    save_message, get_chat_with_messages,
)
from bot.texts import t

load_dotenv()

BOT_TOKEN = os.getenv("BOT_TOKEN")
STAFF_IDS = [int(i) for i in os.getenv("STAFF_IDS", "").split(",") if i.strip()]

bot = Bot(token=BOT_TOKEN)
dp = Dispatcher()


# ── Helpers ────────────────────────────────────────────
def lang_keyboard():
    return InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text="🇺🇿 O'zbekcha", callback_data="lang_uz"),
            InlineKeyboardButton(text="🇷🇺 Русский",   callback_data="lang_ru"),
            InlineKeyboardButton(text="🇬🇧 English",   callback_data="lang_en"),
        ]
    ])


# ── /start ─────────────────────────────────────────────
@dp.message(CommandStart())
async def cmd_start(msg: Message):
    user = msg.from_user
    await upsert_user(user.id, user.username or "", user.full_name or "")

    # Staff: send them to the web panel info
    if user.id in STAFF_IDS:
        admin_url = os.getenv("ADMIN_URL", "")
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(
            text="📋 Admin panelni ochish",
            web_app=WebAppInfo(url=admin_url)
        )
    ]])
    await msg.answer("👋 Xodim sifatida kirdingiz.", reply_markup=keyboard)
    return
    await msg.answer(t("uz", "choose_lang"), reply_markup=lang_keyboard())


# ── Language selection ─────────────────────────────────
@dp.callback_query(F.data.startswith("lang_"))
async def choose_language(cb: CallbackQuery):
    lang = cb.data.split("_")[1]
    user = cb.from_user
    await upsert_user(user.id, user.username or "", user.full_name or "", lang)
    await set_user_language(user.id, lang)

    # Close any old open chat
    old_chat = await get_active_chat(user.id)
    if old_chat:
        await update_chat_status(old_chat["id"], "closed")

    # Create new chat
    await create_chat(user.id)

    await cb.message.edit_text(t(lang, "welcome"))
    await cb.answer()


# ── User sends a message ───────────────────────────────
@dp.message(F.text & ~F.text.startswith("/"))
async def user_message(msg: Message):
    user = msg.from_user
    if user.id in STAFF_IDS:
        return  # staff uses web panel

    lang = await get_user_language(user.id)
    chat = await get_active_chat(user.id)

    if not chat:
        # Auto-create chat if user writes without /start
        await upsert_user(user.id, user.username or "", user.full_name or "", lang)
        chat_id = await create_chat(user.id)
        chat = {"id": chat_id, "status": "new"}

    # If status was 'new', move to 'active'
    if chat["status"] == "new":
        await update_chat_status(chat["id"], "active")

    await save_message(chat["id"], "user", msg.text)
    await msg.answer(t(lang, "question_received"))

    # Notify all staff
    for staff_id in STAFF_IDS:
        try:
            await bot.send_message(
                staff_id,
                f"📩 Yangi xabar!\n"
                f"👤 {user.full_name} (@{user.username or '-'})\n"
                f"💬 {msg.text}\n\n"
                f"Admin panelda javob bering: http://localhost:{os.getenv('ADMIN_PORT', 8000)}/chat/{chat['id']}"
            )
        except Exception:
            pass


# ── Send reply from staff to user (called from web panel via HTTP) ──
async def send_reply_to_user(chat_id: int, text: str):
    chat_data, _ = await get_chat_with_messages(chat_id)
    if not chat_data:
        return False
    user_id = chat_data["uid"]
    lang = await get_user_language(user_id)
    await save_message(chat_id, "staff", text)
    try:
        await bot.send_message(user_id, f"{t(lang, 'staff_replied')}\n\n{text}")
        return True
    except Exception:
        return False


async def close_chat_notify(chat_id: int):
    chat_data, _ = await get_chat_with_messages(chat_id)
    if not chat_data:
        return
    user_id = chat_data["uid"]
    lang = await get_user_language(user_id)
    await update_chat_status(chat_id, "closed")
    try:
        await bot.send_message(user_id, t(lang, "chat_closed_user"))
    except Exception:
        pass


# ── Main ───────────────────────────────────────────────
async def main():
    await init_db()
    print("Bot started...")
    await dp.start_polling(bot)


if __name__ == "__main__":
    asyncio.run(main())
