"""Expired license dialog — shown when user has no active subscription and free period ended."""

from __future__ import annotations

import logging
import sys
import webbrowser

log = logging.getLogger(__name__)

_BUY_URL = "https://whop.com/checkout/plan_YFqvqKJproMsR"


def show_expired_dialog(
    status: str = "expired",
    free_cutoff: str = "",
    referral_code: str = "",
    pricing: dict | None = None,
) -> bool:
    """Show expired dialog. Returns True if user wants to buy, False to exit.

    Works on Windows (PyQt6) with console fallback.
    """
    if pricing is None:
        pricing = {"base_price": 150, "discount": 0, "final_price": 150, "tier": "early"}

    price = pricing.get("final_price", 150)
    discount = pricing.get("discount", 0)
    base = pricing.get("base_price", 150)

    # Try PyQt6 dialog
    if sys.platform == "win32":
        try:
            return _show_qt_dialog(price, discount, base, free_cutoff, referral_code)
        except Exception as exc:
            log.debug("Qt dialog failed: %s — using console", exc)

    # Console fallback
    return _show_console(price, discount, base, free_cutoff, referral_code)


def _show_qt_dialog(price, discount, base, cutoff, ref_code) -> bool:
    from PyQt6.QtWidgets import QApplication, QDialog, QVBoxLayout, QLabel, QPushButton, QHBoxLayout
    from PyQt6.QtCore import Qt
    from PyQt6.QtGui import QFont

    app = QApplication.instance() or QApplication(sys.argv)

    dialog = QDialog()
    dialog.setWindowTitle("MuraveyChina — Subscription Required")
    dialog.setFixedSize(420, 340)
    dialog.setStyleSheet("background-color: #111; color: #e0e0e0;")
    dialog.setWindowFlags(Qt.WindowType.WindowStaysOnTopHint | Qt.WindowType.Dialog)

    layout = QVBoxLayout(dialog)
    layout.setContentsMargins(30, 25, 30, 25)
    layout.setSpacing(12)

    # Title
    title = QLabel("Your free access has ended")
    title.setFont(QFont("Arial", 16, QFont.Weight.Bold))
    title.setStyleSheet("color: #ffffff;")
    title.setAlignment(Qt.AlignmentFlag.AlignCenter)
    layout.addWidget(title)

    title_ru = QLabel("Бесплатный период закончился")
    title_ru.setFont(QFont("Arial", 12))
    title_ru.setStyleSheet("color: #888;")
    title_ru.setAlignment(Qt.AlignmentFlag.AlignCenter)
    layout.addWidget(title_ru)

    # Price
    if discount > 0:
        price_text = f"<s>${base}</s> → <b>${price}</b> (referral discount -${discount})"
    else:
        price_text = f"<b>${price}</b> for 30 days"
    price_label = QLabel(price_text)
    price_label.setFont(QFont("Arial", 14))
    price_label.setStyleSheet("color: #3a8bff; padding: 10px;")
    price_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
    price_label.setTextFormat(Qt.TextFormat.RichText)
    layout.addWidget(price_label)

    # Info
    info = QLabel("Purchase a subscription to continue using MuraveyChina.\n"
                  "Купите подписку чтобы продолжить.")
    info.setStyleSheet("color: #aaa; font-size: 12px;")
    info.setAlignment(Qt.AlignmentFlag.AlignCenter)
    info.setWordWrap(True)
    layout.addWidget(info)

    # Referral code
    if ref_code:
        ref_label = QLabel(f"Your referral code: <b>{ref_code}</b>\n"
                          f"Share it — both you and your friend get $10!")
        ref_label.setStyleSheet("color: #7ac3ff; font-size: 11px; padding: 8px; "
                               "background: #1a1a2e; border-radius: 6px;")
        ref_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        ref_label.setTextFormat(Qt.TextFormat.RichText)
        ref_label.setWordWrap(True)
        layout.addWidget(ref_label)

    # Buttons
    btn_layout = QHBoxLayout()

    buy_btn = QPushButton(f"Buy ${price} →")
    buy_btn.setStyleSheet(
        "QPushButton { background: #3a8bff; color: white; font-size: 14px; "
        "font-weight: bold; padding: 12px; border-radius: 8px; border: none; }"
        "QPushButton:hover { background: #2a7bef; }"
    )
    buy_btn.setFixedHeight(44)

    exit_btn = QPushButton("Exit / Выход")
    exit_btn.setStyleSheet(
        "QPushButton { background: #222; color: #888; font-size: 12px; "
        "padding: 10px; border-radius: 8px; border: 1px solid #333; }"
        "QPushButton:hover { background: #333; }"
    )
    exit_btn.setFixedHeight(44)

    result = [False]

    def on_buy():
        webbrowser.open(_BUY_URL)
        result[0] = False  # exit app after opening browser
        dialog.accept()

    def on_exit():
        result[0] = False
        dialog.reject()

    buy_btn.clicked.connect(on_buy)
    exit_btn.clicked.connect(on_exit)

    btn_layout.addWidget(buy_btn, stretch=2)
    btn_layout.addWidget(exit_btn, stretch=1)
    layout.addLayout(btn_layout)

    dialog.exec()
    return result[0]


def _show_console(price, discount, base, cutoff, ref_code) -> bool:
    print()
    print("  ╔══════════════════════════════════════════════╗")
    print("  ║  Your free access has ended                  ║")
    print("  ║  Бесплатный период закончился                ║")
    print("  ╠══════════════════════════════════════════════╣")
    if discount > 0:
        print(f"  ║  Price: ${base} → ${price} (-${discount} referral)     ║")
    else:
        print(f"  ║  Price: ${price} for 30 days                   ║")
    print(f"  ║                                              ║")
    if ref_code:
        print(f"  ║  Your referral code: {ref_code:<24}║")
        print(f"  ║  Share it for $10 discount!                  ║")
    print(f"  ║                                              ║")
    print(f"  ║  Buy: {_BUY_URL:<40}║")
    print("  ╚══════════════════════════════════════════════╝")
    print()
    choice = input("  Open buy page? (y/n): ").strip().lower()
    if choice in ("y", "yes", "д", "да"):
        webbrowser.open(_BUY_URL)
    return False
