"""Reminders — schedule personal reminders with /remind."""
from __future__ import annotations

import logging
import re
from datetime import datetime, timedelta

from telegram import Update
from telegram.constants import ParseMode
from telegram.ext import ContextTypes

from bot import db
from bot.helpers import parse_time, format_time
from bot.persian_router import register_mixed

logger = logging.getLogger(__name__)


async def remind_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Set a reminder: /remind 2h رونمایی از پروژه"""
    args = (update.message.text or "").split(maxsplit=2)
    if len(args) < 3:
        await update.message.reply_text(
            "⏰ استفاده: <code>یادآوری 2h متن یادآوری</code>\n"
            "زمان‌ها: 30m (دقیقه), 2h (ساعت), 1d (روز), 1w (هفته)",
            parse_mode=ParseMode.HTML,
        )
        return

    duration = parse_time(args[1])
    if not duration or duration > 2592000:  # max 30 days
        await update.message.reply_text("❌ زمان نامعتبر (حداکثر ۳۰ روز)")
        return

    text = args[2]
    user = update.effective_user
    chat = update.effective_chat

    # Store reminder
    remind_at = int((datetime.utcnow() + timedelta(seconds=duration)).timestamp())
    await db.add_reminder(chat.id, user.id, remind_at, text)

    # Schedule job
    context.job_queue.run_once(
        _send_reminder,
        when=duration,
        data={"chat_id": chat.id, "user_id": user.id, "text": text},
        name=f"remind_{chat.id}_{user.id}",
    )

    await update.message.reply_text(
        f"⏰ یادآوری تنظیم شد!\n"
        f"📅 زمان: {format_time(duration)} دیگه\n"
        f"📝 متن: {text}",
        parse_mode=ParseMode.HTML,
    )


async def _send_reminder(context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send the reminder message."""
    data = context.job.data
    chat_id = data["chat_id"]
    user_id = data["user_id"]
    text = data["text"]

    try:
        await context.bot.send_message(
            chat_id=chat_id,
            text=f"⏰ <b>یادآوری برای</b> <a href='tg://user?id={user_id}'>کاربر</a>:\n\n{text}",
            parse_mode=ParseMode.HTML,
        )
        await db.remove_reminder(chat_id, user_id, text)
    except Exception as e:
        logger.warning(f"Failed to send reminder: {e}")


async def reminders_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """List active reminders for this user."""
    user_id = update.effective_user.id
    chat_id = update.effective_chat.id
    reminders = await db.get_user_reminders(chat_id, user_id)

    if not reminders:
        await update.message.reply_text("⏰ یادآوری فعالی ندارید.")
        return

    text = f"⏰ <b>یادآوری‌های شما ({len(reminders)}):</b>\n\n"
    for i, r in enumerate(reminders, 1):
        remind_at = datetime.fromtimestamp(r['remind_at'])
        remaining = remind_at - datetime.utcnow()
        if remaining.total_seconds() > 0:
            text += f"{i}. ⏳ {format_time(int(remaining.total_seconds()))} دیگه: {r['text']}\n"
        else:
            text += f"{i}. ⚠️ {r['text']}\n"

    await update.message.reply_text(text, parse_mode=ParseMode.HTML)


async def cancel_remind_cmd(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Cancel all reminders."""
    user_id = update.effective_user.id
    chat_id = update.effective_chat.id
    count = await db.clear_user_reminders(chat_id, user_id)

    # Cancel scheduled jobs
    for job in context.job_queue.get_jobs_by_name(f"remind_{chat_id}_{user_id}"):
        job.schedule_removal()

    await update.message.reply_text(f"⏰ {count} یادآوری لغو شد.")


def register(app) -> None:
    register_mixed(
        app,
        {
            "remind": remind_cmd,
            "reminders": reminders_cmd,
            "cancelremind": cancel_remind_cmd,
        },
        {
            "یادآوری": remind_cmd,
            "یادآور": remind_cmd,
            "یادم بنداز": remind_cmd,
            "لیست یادآوری": reminders_cmd,
            "یادآوری‌ها": reminders_cmd,
            "لغو یادآوری": cancel_remind_cmd,
        },
    )
