//
//  TSPurchaseVC.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2025/1/14.
//

import Combine
import SwiftUI
import SwiftUIX
class PurchaseViewModel : ObservableObject{
    
    @Published var selectedType: PremiumPeriod = .month
    
    /// 订阅publisher
    let buyPublisher  = PassthroughSubject<Bool,Never>()
    /// 隐私
    let privacyPublisher = PassthroughSubject<Bool, Never>()
    /// term
    let termPublisher = PassthroughSubject<Bool, Never>()
    /// restore
    let restorePublisher = PassthroughSubject<Bool, Never>()
}


class TSPurchaseVC: TSBaseVC {
    
    var closePageBlock:(()->Void)?
    
    var viewModel: PurchaseViewModel = .init()
    var cancellabel: [AnyCancellable] = []
    var buyPeriod:PremiumPeriod = .year
    lazy var purchaseManager: PurchaseManager = {
        let purchaseManager = kPurchaseDefault
        return purchaseManager
    }()
    
    lazy var hostVc: UIHostingController<PurchaseView> = {
        let vc = UIHostingController(rootView: PurchaseView(viewModel: viewModel))
        vc.view.backgroundColor = .clear
        return vc
    }()
    
    override func createView() {
        addNormalNavBarView()
        _ = setNavigationItem("", imageName: "close_gray", direction: .left, action: #selector(closePage))
        setViewBgImageNamed(named: "purchase_bj")

        contentView.addSubview(hostVc.view)
        hostVc.view.snp.makeConstraints { make in
            make.leading.trailing.bottom.top.equalToSuperview()
        }
    }
    
    override func dealThings() {
        addNotifaction()
        onPurchaseStateChanged()
    }
    
    
    func addNotifaction() {

        viewModel.buyPublisher.receive(on: DispatchQueue.main).sink { [weak self] _ in
            guard let self = self else {
                return
            }
            kPurchaseDefault.pay(for: self.viewModel.selectedType)
        }.store(in: &cancellabel)

        viewModel.privacyPublisher.receive(on: DispatchQueue.main).sink { [weak self] _ in
            guard let self = self else {
                return
            }
            
            let vc = TSBusinessWebVC(urlType: .privacy)
            vc.hidesBottomBarWhenPushed = true
            kPresentModalVC(target: self, modelVC: vc)
            
        }.store(in: &cancellabel)

        viewModel.termPublisher.receive(on: DispatchQueue.main).sink { [weak self] _ in
            guard let self = self else {
                return
            }
            
            let vc = TSBusinessWebVC(urlType: .terms)
            vc.hidesBottomBarWhenPushed = true
            kPresentModalVC(target: self, modelVC: vc)

        }.store(in: &cancellabel)

        viewModel.restorePublisher.receive(on: DispatchQueue.main).sink { _ in
            kPurchaseDefault.restorePremium()
        }.store(in: &cancellabel)
    }
    
    
    func onPurchaseStateChanged(){
        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,containerView: self.view)
                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) {
                        kPurchaseDefault.requestProducts()
                    }
                case .paying:
                    TSToastShared.showLoading(text: "Purchasing now".localized,containerView: self.view)
                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,containerView: self.view)
                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,containerView: self.view)
                    #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)
    }
    
    override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)
         // 禁用右滑返回手势
         navigationController?.interactivePopGestureRecognizer?.isEnabled = false
     }

     override func viewWillDisappear(_ animated: Bool) {
         super.viewWillDisappear(animated)
         // 恢复右滑返回手势
         navigationController?.interactivePopGestureRecognizer?.isEnabled = true
     }
    
    deinit {
        cancellabel.removeAll()
    }
}


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

}


struct PurchaseView :View {
    
    @ObservedObject var viewModel: PurchaseViewModel
    
    var body: some View {
        ScrollView {
//            Spacer().frame(height: 44)
            
            VStack {
                Image("vip_big_icon").resizable().frame(width: 163, height: 163)
      
                Text(" AI Ringtone Pro")
                    .font(.font(name: .PoppinsBlackItalic,size: 30))
                    .gradientForeground(
                        colors: [Color.white, "#F7B7FF".uiColor.color],
                        startPoint: UnitPoint.top,
                        endPoint: UnitPoint.bottom
                    )
                    .frame(height: 30)
   
                Spacer().frame(height: 36)
                
                ZStack {
                    VStack(alignment: .leading,spacing: 20) {
                        
                        HStack(spacing: 16) {
                            Image("vip_ringtone").resizable().frame(width: 32, height: 32)
                            Text("Unlimited ringtones generation")
                        }
                        
                        HStack(spacing: 16) {
                            Image("vip_pic").resizable().frame(width: 32, height: 32)
                            Text("Generate unlimited contact poster&photo")
                        }
                        
                        HStack(spacing: 16) {
                            Image("vip_photo").resizable().frame(width: 32, height: 32)
                            Text("Unlock all premium calling theme")
                        }
                        
                        HStack(spacing: 16) {
                            Image("vip_ads").resizable().frame(width: 32, height: 32)
                            Text("100% No Ads").multilineTextAlignment(.leading)
                        }
                        
                    }.font(.font(size: 14)).foregroundColor(UIColor.white.color)
                }
         
            }
            
            Spacer().frame(height: 48)
            
            
            VStack(spacing: 12) {
                
                ZStack(alignment: .topTrailing) {
                    PurchaseItemView(title: "One Month", type: .month, selectedType: $viewModel.selectedType).onTapGesture {
                        viewModel.selectedType = .month
                    }
//                    TSVipRecView()
//                        .offset(y:-14)
                }
          
//                HStack {
//                    PurchaseItemView(title: "One Year", type: .year, selectedType: $viewModel.selectedType).onTapGesture {
//                        viewModel.selectedType = .year
//                    }
//                    
//                    PurchaseItemView(title: "One Week", type: .week, selectedType: $viewModel.selectedType).onTapGesture {
//                        viewModel.selectedType = .week
//                    }
//                }
                
                Spacer().frame(height: 2)
                Button {
                    viewModel.buyPublisher.send(true)
                } label: {
                    ZStack {
                        Color.hex("#E661F6").frame(height: 48)
//                        "#E661F6".uiColor.color
//                        Image("submit_btn_bg").resizable().aspectRatio(contentMode: .fill)
                        Text("Continue")
                            .font(.system(size: 16))
                            .foregroundColor(.white)
                            
                    }.frame(maxWidth: .infinity ,maxHeight: 48.0)
                        .cornerRadius(24.0)
                }
                
                HStack {
                    Text("Recurring billing, cancel anytime")
                        .foregroundColor(Color.hex("#E661F6")) +
                        Text(", 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.")
                        .foregroundColor(UIColor.lesserText.color)
                }
                .multilineTextAlignment(.center).font(.font(size: 8))
                .onTapGesture {
                    viewModel.privacyPublisher.send(true)
                }

                HStack(spacing: 8) {
                    Text("Term of us")
                        .onTapGesture {
                            viewModel.termPublisher.send(true)
                        }
                    Text("|")
                    Text("Privacy Policy")
                        .onTapGesture {
                            viewModel.privacyPublisher.send(true)
                        }
                    Text("|")
                    Text("Restore")
                        .onTapGesture {
                            viewModel.restorePublisher.send(true)
                        }
                }.font(.system(size: 12)).foregroundColor(.hex("#999999"))
            }.padding(.horizontal)
        }
    }
}


struct PurchaseItemView: View {
    var title: String
    var type: PremiumPeriod
    @Binding var selectedType: PremiumPeriod

    var body: some View {
        ZStack {
            Color.clear
            HStack {
                VStack(alignment: .leading, spacing: 8) {
                    Text(title).font(.font(size: 14)).foregroundColor(UIColor.textAssist.color)
                    Text(kPurchaseDefault.price(for: type) ?? "--").font(.font(size: 18,weight: .medium)).foregroundColor(UIColor.mainText.color)
                }
                Spacer()
                if type == selectedType {
                    Image(.radioboxSelected)
                }
            }.padding(.horizontal)
        }
        .frame(height: 74) // 设置高度
        .cornerRadius(16.0) // 圆角
       
        .overlay(
            RoundedRectangle(cornerRadius: 16)
                .stroke(Color.hex("#E661F6"), lineWidth: type == selectedType ? 1 : 0) // 边框
        )
        .shadow(color: Color.hex("#E661F6"), radius: 4, x: 0, y: 1)
    }
}

//推荐选择view
struct TSVipRecView: View {
    var body: some View {
        
        HStack(spacing: 4) {
            Image("upvote_black").resizable().frame(width: 16, height: 16)
            Text("80% Choose").font(.font(size: 12,weight: .medium)).foregroundColor(.hex("#111111"))
        }
        .padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6))
        .background(Color.hex("#FECB34"))
        .frame(height: 28) // 设置高度
        .cornerRadius([.topLeading, .topTrailing, .bottomLeading], 16.0)
    }
}
