//
//  TSPurchaseMembershipVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2025/1/13.
//

class TSPurchaseMembership111VC: TSBaseVC {
    
    var closePageBlock:(()->Void)?
    var buyPeriod:PremiumPeriod = .year
    lazy var purchaseManager: PurchaseManager = {
        let purchaseManager = PurchaseManager.default
        return purchaseManager
    }()
    
    lazy var yearCell: TSPurchaseMembershipCell = {
        let yearCell = TSPurchaseMembershipCell()
        yearCell.titleLabel.text = "Year".localized
        yearCell.priceLabel.text = purchaseManager.price(for: .year)
        yearCell.selectedImageView.isHidden = false
        yearCell.onTapd = { [weak self]  in
            guard let self = self else { return }
            monthCell.selectedImageView.isHidden = true
            buyPeriod = .year
        }
        return yearCell
    }()
    
    lazy var monthCell: TSPurchaseMembershipCell = {
        let monthCell = TSPurchaseMembershipCell()
        monthCell.titleLabel.text = "Month".localized
        monthCell.priceLabel.text = purchaseManager.price(for: .month)
        monthCell.onTapd = { [weak self]  in
            guard let self = self else { return }
            yearCell.selectedImageView.isHidden = true
            buyPeriod = .month
        }
        return monthCell
    }()
    
    lazy var submitBtn: UIButton = {
        let submitBtn = TSViewTool.createNormalSubmitBtn(title: "Continue") { [weak self]  in
            guard let self = self else { return }
            
            purchaseManager.pay(for: buyPeriod)
            
        }
        submitBtn.cornerRadius = 24.0
        return submitBtn
    }()

    lazy var textLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .center
        label.font = .font(size: 8)
        label.textColor = UIColor.fromHex("#FFFFFF",alpha: 0.4)
        let fullText = "Recurring billing, cancel anytime. Payment will be charged to your iTunes account at confirmation of purchase. Subscriptions automatically renew for the same applicable term and price, unless auto-renew is turned off at least 24 hours before the end of the current period."
        let highlightedText = "Recurring billing, cancel anytime."
        let attributedString = NSMutableAttributedString(string: fullText)
        if let range = fullText.range(of: highlightedText) {
            let nsRange = NSRange(range, in: fullText)
            attributedString.addAttributes([
                .foregroundColor: UIColor.fromHex("#12FFF7"), // 高亮颜色
            ], range: nsRange)
        }
        label.attributedText = attributedString
        return label
    }()
    
    override func createView() {
        addNormalNavBarView()
        _ = setNavigationItem("", imageName: "close_gray", direction: .left, action: #selector(closePage))
    
    
        
        let topView = creatTopView()
        contentView.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.leading.equalTo(0)
            make.trailing.equalTo(0)
            make.top.equalTo(20)
        }
        
        
        contentView.addSubview(yearCell)
        contentView.addSubview(monthCell)
        contentView.addSubview(submitBtn)
        
        yearCell.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(74)
            make.top.equalTo(topView.snp.bottom).offset(72)
        }
        
        monthCell.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(74)
            make.top.equalTo(yearCell.snp.bottom).offset(12)
        }
        
        submitBtn.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(48)
            make.top.equalTo(monthCell.snp.bottom).offset(28)
        }
        
        contentView.addSubview(textLabel)
        textLabel.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(48)
            make.top.equalTo(submitBtn.snp.bottom).offset(12)
        }
        
        let bottomView = creatBottomLabel()
        contentView.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.height.equalTo(17)
            make.centerX.equalToSuperview()
            make.top.equalTo(textLabel.snp.bottom).offset(8)
        }
  
    }
    
    override func dealThings() {
        purchaseManager.onPurchaseStateChanged = { [weak self] manager,state,object in
            guard let self = self else { return }
        
            DispatchQueue.main.async {
                switch state {
                case .none:
                    break
                case .loading:
                    TSToastShared.showLoading(text: "Getting price".localized)
                case .loadSuccess:
                    TSToastShared.hideLoading()
                case .loadFail:
                    TSToastShared.hideLoading()
                    let message = "Get price failure, Will automatically retry in 5 seconds".localized
                    TSToastShared.showToast(text: message)
                    DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                        PurchaseManager.default.requestProducts()
                    }
                case .paying:
                    TSToastShared.showLoading(text: "Purchasing now".localized)
                case .paySuccess:
                    TSToastShared.hideLoading()
                    let loadingText = manager.isVip ? "Congratulation you have become VIP".localized : "Finish".localized
                    TSToastShared.showToast(text:loadingText)
                    if manager.isVip {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            self.closePage()
                        }
                    }

                case .payFail:
                    TSToastShared.hideLoading()
                    if let str = object as? String {
                        TSToastShared.showToast(text: str)
                    }
                    
                case .restoreing:
                    TSToastShared.showLoading(text: "Restoring now".localized)
                case .restoreSuccess:
                    TSToastShared.hideLoading()
                    let loadingText = manager.isVip ? "Congratulation you have become VIP".localized : "Couldn't Restore Subscription".localized
                    debugPrint(loadingText)
                    TSToastShared.showToast(text:loadingText)
                    if manager.isVip {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                            self.closePage()
                        }
                    }

                case .restoreFail:
                    TSToastShared.hideLoading()
                    let loadingText = (object as? String) ?? "Failed to restore subscribe, please try again".localized
                    debugPrint(loadingText)
                    TSToastShared.showToast(text: loadingText)
                case .verifying:
                    #if DEBUG
                    TSToastShared.showLoading(text: "Verifying receipt...".localized)
                    #endif
                case .verifySuccess:
                    break
                case .verifyFail:
                #if DEBUG
                    TSToastShared.hideLoading()
                    let message = (object as? String) ?? "Verify receipt failed"
                    TSToastShared.showToast(text:message)

                #endif
                }
            }
            debugPrint("PurchaseManager onPurchaseStateChanged=\(String(describing: state))")
        }
        

    }
    
    @objc func closePage(){
        closePageBlock?()
        TSToastShared.hideLoading()
        self.dismiss(animated: true)
    }
}


extension TSPurchaseMembership111VC {
    

    func creatTopView() -> UIView {
        
        let topView = UIView()
        
        let vipImageView = UIImageView.createImageView(imageName: "vip_big_icon")
        topView.addSubview(vipImageView)
        
        let liveImageView = UIImageView.createImageView(imageName: "livelive")
        topView.addSubview(liveImageView)
        
        let cell0 = creatCell(text: "All Premium Wallpapers")
        topView.addSubview(cell0)
        
        let cell1 = creatCell(text: "Unlimited Video To Live")
        topView.addSubview(cell1)
        
        let cell2 = creatCell(text: "100% No Ads")
        topView.addSubview(cell2)
        
        
        
        vipImageView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.centerX.equalToSuperview()
            make.width.equalTo(124)
            make.height.equalTo(102)
        }
        
        liveImageView.snp.makeConstraints { make in
            make.top.equalTo(vipImageView.snp.bottom).offset(12)
            make.centerX.equalToSuperview()
        }
        
        cell0.snp.makeConstraints { make in
            make.top.equalTo(liveImageView.snp.bottom).offset(40)
            make.leading.equalTo(76)
            make.trailing.equalTo(-10)
            make.height.equalTo(24)
        }
        
        cell1.snp.makeConstraints { make in
            make.top.equalTo(cell0.snp.bottom).offset(18)
            make.leading.equalTo(76)
            make.trailing.equalTo(-10)
            make.height.equalTo(24)
        }
        
        cell2.snp.makeConstraints { make in
            make.top.equalTo(cell1.snp.bottom).offset(18)
            make.leading.equalTo(76)
            make.trailing.equalTo(-10)
            make.height.equalTo(24)
            make.bottom.equalToSuperview()
        }
        
        return topView
    }
    
 
    func creatCell(text:String) -> UIView {
        let cellView = UIView()
        
        let vipImageView = UIImageView.createImageView(imageName: "check")
        cellView.addSubview(vipImageView)
        
        
        let label = UILabel.createLabel(text: text,font: .font(size: 16),textColor: .lesserText)
        cellView.addSubview(label)
        
        vipImageView.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.leading.top.bottom.equalTo(0)
        }
        
        label.snp.makeConstraints { make in
            make.trailing.top.bottom.equalTo(0)
            make.leading.equalTo(vipImageView.snp.trailing).offset(8)
        }
        
        return cellView
    }
    
    
    func creatBottomLabel() -> UIView {
        let bgView = UIView()
        
        let termsLable = UILabel.createLabel(text: " Terms of us  ".localized,font: .font(size: 12),textColor: .textAssist)
        termsLable.isUserInteractionEnabled = true
        termsLable.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickTermsLabel)))
        let privacyLable = UILabel.createLabel(text: "|  Privacy Policy  ".localized,font: .font(size: 12),textColor: .textAssist)
        privacyLable.isUserInteractionEnabled = true
        privacyLable.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickPrivacyLable)))
        let restoreLable = UILabel.createLabel(text: "|  Restore   ".localized,font: .font(size: 12),textColor: .textAssist)
        restoreLable.isUserInteractionEnabled = true
        restoreLable.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickRestoreLable)))
        
        bgView.addSubview(termsLable)
        termsLable.snp.makeConstraints { make in
            make.leading.top.bottom.equalTo(0)
        }
        
        bgView.addSubview(privacyLable)
        privacyLable.snp.makeConstraints { make in
            make.leading.equalTo(termsLable.snp.trailing)
            make.top.bottom.equalTo(0)
        }
        
        bgView.addSubview(restoreLable)
        restoreLable.snp.makeConstraints { make in
            make.leading.equalTo(privacyLable.snp.trailing)
            make.top.bottom.trailing.equalTo(0)
        }
        
        return bgView
    }
    
    
    @objc func clickTermsLabel() {
        
        let vc = TSBusinessWebVC(urlType: .terms)
        vc.hidesBottomBarWhenPushed = true
        kPresentModalVC(target: self, modelVC: vc)
    }
    
    @objc func clickPrivacyLable() {
        let vc = TSBusinessWebVC(urlType: .privacy)
        vc.hidesBottomBarWhenPushed = true
        kPresentModalVC(target: self, modelVC: vc)
    }
    
    @objc func clickRestoreLable() {
        purchaseManager.restorePremium()
    }
    
}





class TSPurchaseMembershipCell: TSBaseView {
    
    
    var onTapd:(()->Void)?
    
    
    lazy var titleLabel: UILabel = {
        let titleLabel = UILabel.createLabel(font: .font(size: 14),textColor: .textAssist)
        return titleLabel
    }()
    
    lazy var priceLabel: UILabel = {
        let titleLabel = UILabel.createLabel(font: .font(size: 18,weight: .medium),textColor: .mainText)
        return titleLabel
    }()
    
    
    lazy var selectedImageView: UIImageView = {
        let selectedImageView = UIImageView.createImageView(imageName: "radiobox_selected")
        selectedImageView.isHidden = true
        return selectedImageView
    }()
    
    override func creatUI() {
        contentView.backgroundColor = .fromHex("FFFFFF", alpha: 0.1)
        contentView.layer.cornerRadius = 16.0
        contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickBg)))
        contentView.addSubview(titleLabel)
        contentView.addSubview(priceLabel)
        contentView.addSubview(selectedImageView)
        
        titleLabel.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.top.equalTo(15)
            make.height.equalTo(14)
        }
        
        priceLabel.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.bottom.equalTo(-15)
            make.height.equalTo(18)
        }
        
        selectedImageView.snp.makeConstraints { make in
            make.trailing.equalTo(-16)
            make.centerY.equalToSuperview()
            make.width.height.equalTo(24)
        }
    }
    
    @objc func clickBg(){
        selectedImageView.isHidden = false
        onTapd?()
    }
    
}

extension TSPurchaseMembership111VC{
    
    static func show(target:UIViewController,closePageBlock:(()->Void)?){
//        let vc = TSPurchaseMembershipVC()
//        vc.closePageBlock = closePageBlock
//        let navi = TSBaseNavigationC(rootViewController: vc)
//        navi.modalPresentationStyle = .overFullScreen
//        target.present(navi, animated: true)
    }

}


