"""
Advanced Add Account Handler

Features:
- cancel command
- live countdown (edit every 1 sec)
- cooldown enforcement
- human-like delayed login
- fully compatible with SessionCreator
"""

import asyncio
import time

from remottxrea.client.create_client import SessionCreator
from remottxrea.core.logger import get_action_logger


COOLDOWN_SECONDS = 8


class AddAccountHandler:

    def __init__(self):
        self.creator = SessionCreator()
        self.states = {}

    # ==================================================
    async def handle(self, message):

        user_id = message.from_user.id
        text = message.text.strip()

        # =============================================
        # CANCEL
        # =============================================
        if text.lower() == "cancel":

            state = self.states.get(user_id)

            if state:
                phone = state.get("phone")

                if phone in self.creator.pending:
                    try:
                        app = self.creator.pending[phone]["app"]
                        await app.disconnect()
                    except:
                        pass

                    del self.creator.pending[phone]

                del self.states[user_id]

                return await message.reply_text(
                    "❌ Add account cancelled"
                )

            return

        # =============================================
        # START
        # =============================================
        if text == "addAccount":

            self.states[user_id] = {
                "step": "phone",
                "unlock_time": 0
            }

            return await message.reply_text(
                "Send phone number with country code\n"
                "Example:\n+491234567890"
            )

        if user_id not in self.states:
            return

        state = self.states[user_id]
        now = time.time()

        # =============================================
        # BLOCK IF UNDER COOLDOWN
        # =============================================
        if now < state.get("unlock_time", 0):
            remaining = int(state["unlock_time"] - now)
            return await message.reply_text(
                f"⏳ Please wait {remaining}s..."
            )

        # =============================================
        # STEP 1 → PHONE
        # =============================================
        if state["step"] == "phone":

            phone = text
            logger = get_action_logger(
                action="add_account",
                session=phone
            )

            try:

                await self.creator.send_code(phone)

                state.update({
                    "step": "code",
                    "phone": phone
                })

                await self._countdown(
                    message,
                    f"📩 Code sent to {phone}\n"
                    f"Wait {COOLDOWN_SECONDS}s before sending code",
                    COOLDOWN_SECONDS
                )

                state["unlock_time"] = time.time()

                return await message.reply_text(
                    "✅ Now send the code"
                )

            except Exception as e:
                logger.exception(f"Send code failed → {e}")
                return await message.reply_text(
                    "Failed to send code"
                )

        # =============================================
        # STEP 2 → CODE
        # =============================================
        if state["step"] == "code":

            phone = state["phone"]
            code = text

            logger = get_action_logger(
                action="add_account",
                session=phone
            )

            await self._countdown(
                message,
                "⏳ Processing login in",
                COOLDOWN_SECONDS
            )

            result = await self.creator.login_with_code(
                phone,
                code
            )

            if result is True:
                logger.info("Login success")
                del self.states[user_id]
                return await message.reply_text(
                    "Account added successfully ✅"
                )

            if result == "2FA":

                state["step"] = "password"

                await self._countdown(
                    message,
                    "🔐 2FA detected\n"
                    "Wait before sending password",
                    COOLDOWN_SECONDS
                )

                state["unlock_time"] = time.time()

                return await message.reply_text(
                    "Now send your password"
                )

            logger.warning("Invalid code")
            return await message.reply_text(
                "Invalid or expired code"
            )

        # =============================================
        # STEP 3 → PASSWORD
        # =============================================
        if state["step"] == "password":

            phone = state["phone"]
            password = text

            logger = get_action_logger(
                action="add_account",
                session=phone
            )

            await self._countdown(
                message,
                "⏳ Verifying password in",
                COOLDOWN_SECONDS
            )

            success = await self.creator.login_with_password(
                phone,
                password
            )

            if success:
                logger.info("Login success with 2FA")
                del self.states[user_id]
                return await message.reply_text(
                    "Account added successfully ✅"
                )

            logger.warning("Wrong password")
            return await message.reply_text(
                "Wrong password"
            )

    # ==================================================
    # LIVE COUNTDOWN
    # ==================================================
    async def _countdown(
        self,
        message,
        base_text,
        seconds
    ):

        countdown_msg = await message.reply_text(
            f"{base_text} {seconds}s"
        )

        for remaining in range(seconds - 1, -1, -1):

            await asyncio.sleep(1)

            try:
                await countdown_msg.edit_text(
                    f"{base_text} {remaining}s"
                )
            except:
                pass