"""
Poe2VisualTool Commercial License Activation Dialog
Hộp thoại đồ họa kích hoạt bản quyền sang trọng, thân thiện cho người dùng cuối (CustomTkinter).
Bản quyền 2026 Poe2VisualTool.
"""

from __future__ import annotations

from typing import Callable, Optional
import customtkinter as ctk

from src.commercial.license_manager import LicenseManager, LicenseInfo, LicenseTier


class LicenseDialog(ctk.CTkToplevel):
    """
    Hộp thoại kích hoạt bản quyền dành cho khách hàng cuối.
    """

    def __init__(
        self,
        parent=None,
        license_manager: Optional[LicenseManager] = None,
        on_success: Optional[Callable[[LicenseInfo], None]] = None,
    ):
        super().__init__(parent)
        self.lm = license_manager or LicenseManager()
        self.on_success = on_success

        self.title("Kích Hoạt Bản Quyền — Poe2VisualTool")
        self.geometry("540x480")
        self.resizable(False, False)

        # Đưa lên trên cùng và focus
        self.attributes("-topmost", True)
        self.after(100, self.lift)

        self._build_ui()
        self._refresh_status()

    def _build_ui(self):
        container = ctk.CTkFrame(self, fg_color="#0f172a")
        container.pack(fill="both", expand=True, padx=16, pady=16)

        # Header
        lbl_title = ctk.CTkLabel(
            container,
            text="🛡️ KÍCH HOẠT BẢN QUYỀN",
            font=ctk.CTkFont(size=18, weight="bold"),
            text_color="#38bdf8",
        )
        lbl_title.pack(pady=(16, 4))

        lbl_subtitle = ctk.CTkLabel(
            container,
            text="Poe2VisualTool Commercial Grade · Path of Exile 2 (2026)",
            font=ctk.CTkFont(size=11),
            text_color="#94a3b8",
        )
        lbl_subtitle.pack(pady=(0, 16))

        # Status Card
        self.card_status = ctk.CTkFrame(container, fg_color="#1e293b", corner_radius=8)
        self.card_status.pack(fill="x", padx=16, pady=(0, 14))

        self.lbl_status_badge = ctk.CTkLabel(
            self.card_status,
            text="TRẠNG THÁI: ĐANG KIỂM TRA",
            font=ctk.CTkFont(size=12, weight="bold"),
            text_color="#f59e0b",
        )
        self.lbl_status_badge.pack(anchor="w", padx=14, pady=(10, 2))

        self.lbl_status_desc = ctk.CTkLabel(
            self.card_status,
            text="Vui lòng nhập mã bản quyền hợp lệ để mở khóa toàn bộ tính năng.",
            font=ctk.CTkFont(size=11),
            text_color="#cbd5e1",
            justify="left",
            wraplength=460,
        )
        self.lbl_status_desc.pack(anchor="w", padx=14, pady=(0, 10))

        # HWID Section
        lbl_hwid_title = ctk.CTkLabel(
            container,
            text="MÃ PHẦN CỨNG CỦA MÁY TÍNH NÀY (HWID):",
            font=ctk.CTkFont(size=11, weight="bold"),
            text_color="#e2e8f0",
        )
        lbl_hwid_title.pack(anchor="w", padx=16, pady=(0, 4))

        hwid_row = ctk.CTkFrame(container, fg_color="transparent")
        hwid_row.pack(fill="x", padx=16, pady=(0, 14))

        self.entry_hwid = ctk.CTkEntry(
            hwid_row,
            font=ctk.CTkFont(family="Consolas", size=13, weight="bold"),
            text_color="#38bdf8",
        )
        self.entry_hwid.insert(0, self.lm.hwid)
        self.entry_hwid.configure(state="readonly")
        self.entry_hwid.pack(side="left", fill="x", expand=True, padx=(0, 8))

        btn_copy_hwid = ctk.CTkButton(
            hwid_row,
            text="📋 Sao Chép",
            width=90,
            command=self._on_copy_hwid,
        )
        btn_copy_hwid.pack(side="left")

        # Key Input Section
        lbl_key_title = ctk.CTkLabel(
            container,
            text="NHẬP PRODUCT KEY BẢN QUYỀN:",
            font=ctk.CTkFont(size=11, weight="bold"),
            text_color="#e2e8f0",
        )
        lbl_key_title.pack(anchor="w", padx=16, pady=(0, 4))

        self.entry_key = ctk.CTkEntry(
            container,
            placeholder_text="PVTK-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX",
            font=ctk.CTkFont(family="Consolas", size=12),
        )
        self.entry_key.pack(fill="x", padx=16, pady=(0, 16))

        # Action Buttons
        btn_row = ctk.CTkFrame(container, fg_color="transparent")
        btn_row.pack(fill="x", padx=16, pady=(0, 8))

        self.btn_activate = ctk.CTkButton(
            btn_row,
            text="⚡ Kích Hoạt Ngay",
            font=ctk.CTkFont(size=13, weight="bold"),
            fg_color="#059669",
            hover_color="#047857",
            height=36,
            command=self._on_activate,
        )
        self.btn_activate.pack(side="left", fill="x", expand=True, padx=(0, 8))

        self.btn_trial = ctk.CTkButton(
            btn_row,
            text="🎁 Dùng Thử 24 Giờ",
            font=ctk.CTkFont(size=12),
            fg_color="#334155",
            hover_color="#475569",
            height=36,
            command=self._on_trial,
        )
        self.btn_trial.pack(side="left", fill="x", expand=True)

    def _on_copy_hwid(self):
        self.clipboard_clear()
        self.clipboard_append(self.lm.hwid)
        self.lbl_status_desc.configure(text="[✓] Đã sao chép mã HWID! Hãy gửi mã này cho Admin để nhận Product Key.")

    def _refresh_status(self):
        info = self.lm.load_license()
        if info.is_valid:
            if info.tier == LicenseTier.LIFETIME:
                self.lbl_status_badge.configure(text="TRẠNG THÁI: BẢN QUYỀN VĨNH VIỄN (LIFETIME)", text_color="#10b981")
                self.lbl_status_desc.configure(text="Phần mềm đã được kích hoạt vĩnh viễn không giới hạn thời gian.")
            elif info.tier == LicenseTier.SUBSCRIPTION:
                self.lbl_status_badge.configure(text=f"TRẠNG THÁI: THUÊ BAO CÒN {info.days_left} NGÀY", text_color="#38bdf8")
                exp_str = info.expires_at.strftime("%d/%m/%Y %H:%M") if info.expires_at else "Chưa rõ"
                self.lbl_status_desc.configure(text=f"Hạn sử dụng đến: {exp_str} UTC.")
            elif info.tier == LicenseTier.TRIAL:
                self.lbl_status_badge.configure(text="TRẠNG THÁI: ĐANG DÙNG THỬ (TRIAL)", text_color="#f59e0b")
                self.lbl_status_desc.configure(text=f"Thời gian dùng thử còn lại: {info.days_left} ngày.")
            
            if info.raw_key:
                self.entry_key.delete(0, "end")
                self.entry_key.insert(0, info.raw_key)
        else:
            self.lbl_status_badge.configure(text="TRẠNG THÁI: CHƯA KÍCH HOẠT", text_color="#ef4444")
            self.lbl_status_desc.configure(text=info.message or "Vui lòng nhập mã bản quyền để sử dụng.")

    def _on_activate(self):
        key = self.entry_key.get().strip()
        if not key:
            self.lbl_status_desc.configure(text="[!] Lỗi: Vui lòng nhập Product Key trước khi bấm Kích hoạt!")
            return

        success = self.lm.save_license(key)
        if success:
            info = self.lm.load_license()
            self._refresh_status()
            if self.on_success:
                self.on_success(info)
            self.after(1500, self.destroy)
        else:
            valid, tier, exp, msg = self.lm.verify_product_key(key)
            self.lbl_status_badge.configure(text="TRẠNG THÁI: KÍCH HOẠT THẤT BẠI", text_color="#ef4444")
            self.lbl_status_desc.configure(text=f"[!] {msg}")

    def _on_trial(self):
        if self.lm.activate_trial(hours=24):
            info = self.lm.load_license()
            self._refresh_status()
            if self.on_success:
                self.on_success(info)
            self.after(1500, self.destroy)
        else:
            self.lbl_status_desc.configure(text="[!] Không thể kích hoạt dùng thử. Có thể máy này đã từng dùng thử trước đó.")
