//
//  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 = .month
    lazy var purchaseManager: PurchaseManager = {
        let purchaseManager = PurchaseManager.default
        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_bg_shade")
       
        contentView.addSubview(hostVc.view)
        hostVc.view.snp.makeConstraints { make in
            make.leading.trailing.bottom.top.equalToSuperview()
        }
    }
    
    override func dealThings() {
        PurchaseManager.default.requestProducts()
        addNotifaction()
        onPurchaseStateChanged()
    }
    
    
    func addNotifaction() {

        viewModel.buyPublisher.receive(on: DispatchQueue.main).sink { [weak self] _ in
            guard let self = self else {
                return
            }
            PurchaseManager.default.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
            PurchaseManager.default.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) {
                        PurchaseManager.default.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".localized
                    TSToastShared.showToast(text:message)

                #endif
                }
            }
            debugPrint("PurchaseManager onPurchaseStateChanged=\(String(describing: state))")
        }
    }
    
    @objc func closePage(){
        closePageBlock?()
        TSToastShared.hideLoading()
        self.dismiss(animated: true)
    }
    
    
    deinit {
        cancellabel.removeAll()
    }
}

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

}

struct PurchaseView :View {
    
    @ObservedObject var viewModel: PurchaseViewModel
    
    var body: some View {
        let vipType = PurchaseManager.default.vipType
        VStack {
            Spacer()
            
            VStack(alignment: .leading) {
                Text("Update to \nPRO")
                    .foregroundColor(UIColor.mainText.color)
                    .multilineTextAlignment(.leading)
                    .font(.font(name: .CherryBombOneRegular,size: 36))
                
                Spacer().frame(height: 47)
                
                VStack(alignment: .leading, spacing: 12, content: {
                    TSFeatureItemView(image: .purchaseIconUnLock, text: "Unlock All Templates".localized)
                    TSFeatureItemView(image: .purchaseIconUnlimited, text: "Unlimited Define Travel".localized)
                    TSFeatureItemView(image: .purchaseIconAd, text: "100% No Ad".localized)
                }).multilineTextAlignment(.center).font(.font(size: 16,weight:.medium)).foregroundColor(UIColor.mainText.color)
            }.frame(width: k_ScreenWidth - 48, alignment: .leading).padding(.leading,8)
            
            Spacer().frame(height: 56)
            
            
            VStack(spacing: 16) {
                ZStack(alignment: .topTrailing) {
                    PurchaseItemView(title: "One Month".localized, type: .month, selectedType: $viewModel.selectedType).onTapGesture {
                        viewModel.selectedType = .month
                        viewModel.buyPublisher.send(true)
                    }
                    TSVipRecView(save: vipType.saveString)
                        .offset(x:-30,y:-14)
                }
                
                PurchaseItemView(title: "One Week".localized, type: .week, selectedType: $viewModel.selectedType).onTapGesture {
                    viewModel.selectedType = .week
                    viewModel.buyPublisher.send(true)
                }
            }
            
            Spacer().frame(height: 20)
            
            Button {
                viewModel.buyPublisher.send(true)
            } label: {
                ZStack {
                    UIColor.mainText.color
                    Text("Continue".localized)
                        .font(.font(name: .PoppinsBoldItalic,size: 14))
                        .foregroundColor(.white)
                    
                }.frame(maxWidth: .infinity ,maxHeight: 52)
                .cornerRadius(26.0)
            }
            
            Spacer().frame(height: 26)
            
            
            VStack(spacing: 12) {
                
                HStack(spacing: 8) {
                    Text("Terms of us".localized)
                        .onTapGesture {
                            viewModel.termPublisher.send(true)
                        }
                    Text("|")
                    Text("Privacy Policy".localized)
                        .onTapGesture {
                            viewModel.privacyPublisher.send(true)
                        }
                    Text("|")
                    Text("Restore".localized)
                        .onTapGesture {
                            viewModel.restorePublisher.send(true)
                        }
                }.font(.system(size: 12)).foregroundColor(UIColor.lesserText.color)
                
                HStack {
                    Text("Recurring billing,cancel anytime.".localized)
                        .foregroundColor("#FF86EF".uiColor.color) +
                    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.".localized)
                        .foregroundColor(UIColor.lesserText.color)
                }
                .multilineTextAlignment(.center)
                .font(.font(size: 8))
                .onTapGesture {
                    viewModel.privacyPublisher.send(true)
                }
                
            }
            
            Spacer().frame(height:6+k_Height_safeAreaInsetsBottom())
        }.padding(.horizontal).environment(\.layoutDirection, kIsRTL ? .rightToLeft : .leftToRight)
    }
}



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

    var body: some View {
        let textColor = UIColor.secondaryText.color
        ZStack {
            type == selectedType ? UIColor.themeColor.color : .white
            HStack {
                //左边加个
                VStack(alignment: .leading, spacing: 12) {
                    Text(title).font(.font(size: 16)).foregroundColor(type == selectedType ? UIColor.mainText.color : textColor)
                    HStack{
                        Text(PurchaseManager.default.price(for: type) ?? "--").font(.font(size: 18,weight: .medium)).foregroundColor(type == selectedType ? UIColor.mainText.color : textColor)
                        Text(PurchaseManager.default.averageWeekly(for:type) ?? "--").font(.font(size: 12)).foregroundColor(textColor)
                    }
                }

                Spacer()

                Image(type == selectedType ? .purchaseSelected : .purchaseUnSelected)

            }.padding(.horizontal)
        }
        .foregroundColor(textColor)
        .frame(height: 74) // 设置高度
        .cornerRadius(16.0)
//        .overlay(
//            RoundedRectangle(cornerRadius: 0)
//                .stroke(UIColor.themeColor.color, lineWidth: type == selectedType ? 1 : 0) // 边框
//        )
    }

    func perString()->String{
        switch type {
        case .year:
            return "Per Year".localized
        case .week:
            return "Per Week".localized
        default:
            return ""
        }
    }
}

//推荐选择view
struct TSVipRecView: View {
    var save:String
    var body: some View {
        HStack(spacing: 4) {
            Image("upvote_black").resizable().frame(width: 16, height: 16)
            Text("Save".localized  + " " + save ).font(.font(size: 12,weight: .medium)).foregroundColor(.hex("#111111"))
        }
        .padding(EdgeInsets(top: 6, leading: 6, bottom: 6, trailing: 6))
        .background(Color.hex("#01E2FF"))
//        .linearGradientBackground(colors: ["#F1D3AB".uiColor.color,"#E4A858".uiColor.color])
        .frame(height: 28) // 设置高度
        .cornerRadius(14.0)
//        .cornerRadius([.topLeading, .topTrailing, .bottomLeading, .bottomTrailing], 16.0)
    }
}


//推荐选择view
struct TSFeatureItemView: View {
    var image:ImageResource
    var text:String
    var body: some View {
        let backgroundColor = Color.clear
        ZStack {
            HStack(alignment: .center, spacing: 12) {
                Image(image).resizable().frame(width: 24, height: 24)
                Text(text)
            }
        }
    }
}

extension View {
    /// 添加线性渐变背景
    /// - Parameters:
    ///   - colors: 渐变颜色数组
    ///   - startPoint: 渐变起点 (默认 .top)
    ///   - endPoint: 渐变终点 (默认 .bottom)
    ///   - cornerRadius: 圆角半径 (默认 0)
    func linearGradientBackground(colors: [Color],
                                  startPoint: UnitPoint = .leading,
                                  endPoint: UnitPoint = .trailing,
                                  cornerRadius: CGFloat = 0) -> some View {
        self.background(
            LinearGradient(
                gradient: Gradient(colors: colors),
                startPoint: startPoint,
                endPoint: endPoint
            )
            .cornerRadius(cornerRadius)
        )
    }
    
}
