//
//  SpeakEleIAPViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/11.
//

import UIKit
import StoreKit

class SpeakEleIAPViewCtr: SpeakEleBaseViewCtr {

    enum iapstate {
        case guide
        case plan
        case other
    }
    
    // MARK: - ib
    @IBOutlet weak var SpeakEasyV: UIView!
    
    @IBOutlet weak var SpeakPayDescritionL: UILabel!
    @IBOutlet weak var SpeakPayContentV: UIView!
    @IBOutlet weak var SpeakPayTitleL: UILabel!
    @IBOutlet weak var SpeakSwitch: UISwitch!
    
    
    @IBOutlet weak var SpeakTL1: UILabel!
    @IBOutlet weak var SpeakFreeTL1: UILabel!
    @IBOutlet weak var SpeakRTL1: UILabel!
    
    @IBOutlet weak var SpeakTL2: UILabel!
    @IBOutlet weak var SpeakRTL2: UILabel!
    @IBOutlet weak var SpeakSave: UILabel!
    
    @IBOutlet weak var SpeakPayBut: SpeakEleButton!
    @IBOutlet weak var SpeakBotDescription: UILabel!
    
    @IBOutlet weak var SpeakContentBg: UIView!
    
    var Products:[SKProduct?] = []
    
    private let viewModel = IAPViewModel.share
    
    var state:iapstate = .other
    
    var isFree:Bool = true {
        didSet {
            SpeakSwitch.isOn = isFree
            configsUI()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        SpeakSwitch.addTarget(self, action: #selector(valueChange(_:)), for: .touchUpInside)
        isFree = true
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        viewModel.fetchProducts {[weak self] products in
            if let prod = products {
                self?.Products = prod
                self?.configsUI()
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.AnimationState = .none
        titleView.isHidden = true
    }

    private func setconfigs() -> Void {
        SpeakTL1.textColor = UIColor(with: SpeakIAPConfigs.share.configs.SpeakPayTL?.color ?? "")
        SpeakFreeTL1.textColor = UIColor(with: SpeakIAPConfigs.share.configs.SpeakPayTHint?.color ?? "")
        SpeakRTL1.textColor = UIColor(with: SpeakIAPConfigs.share.configs.SpeakPayTR?.color ?? "")
        
        SpeakTL2.textColor = UIColor(with: SpeakIAPConfigs.share.configs.SpeakPayBL?.color ?? "")
        SpeakRTL2.textColor = UIColor(with: SpeakIAPConfigs.share.configs.SpeakPayBR?.color ?? "")
        SpeakSave.textColor = UIColor(with: SpeakIAPConfigs.share.configs.SpeakPayBHint?.color ?? "")
        
        SpeakTL1.font = UIFont.IAPFont(SpeakIAPConfigs.share.configs.SpeakPayTL?.font ?? "")
        SpeakFreeTL1.font = UIFont.IAPFont(SpeakIAPConfigs.share.configs.SpeakPayTHint?.font ?? "")
        SpeakRTL1.font = UIFont.IAPFont(SpeakIAPConfigs.share.configs.SpeakPayTR?.font ?? "")
        
        SpeakTL2.font = UIFont.IAPFont(SpeakIAPConfigs.share.configs.SpeakPayBL?.font ?? "")
        SpeakRTL2.font = UIFont.IAPFont(SpeakIAPConfigs.share.configs.SpeakPayBR?.font ?? "")
        SpeakSave.font = UIFont.IAPFont(SpeakIAPConfigs.share.configs.SpeakPayBHint?.font ?? "")
    }
    
    override func setup() {
        let privacy = "Privacy".attributed().underline(.single).paragraphStyle(.center,lineSpacing: 4).build()
        let terms = "Terms".attributed().underline(.single).paragraphStyle(.center,lineSpacing: 4).build()
        let att = "Cancel Anytime & ".combined(with: [privacy,"｜",terms])
        self.SpeakBotDescription.attributedText = att
        self.SpeakBotDescription.AddTextTap(["Privacy","Terms"])
        self.SpeakBotDescription.callblack = { [weak self] text in
            guard let text:String = text as? String else { return }
            if text == privacy.string {
                let web = SpeakEleWebViewCtr()
                web.LoadWithUrl(url: SpeakPrivacy)
                self?.navigationController?.pushViewController(web, animated: true)
            } else {
                let web = SpeakEleWebViewCtr()
                web.LoadWithUrl(url: SpeakTerms)
                self?.navigationController?.pushViewController(web, animated: true)
            }
        }
        setconfigs()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.layoutIfNeeded()
        SpeakEasyV.shadow(cornerRadius: 16,shadowColor: .init(hex: 0x000000,alpha: 1),opacity: 0.06,radius: 2)
        SpeakPayContentV.shadow(cornerRadius: 8,shadowColor: .init(hex: 0x000000,alpha: 1),opacity: 0.06,radius: 2)
        SpeakContentBg.gradient(colors: [.init(hex: 0xFFFFFF,alpha: 0),.init(hex: 0xFFFFFF,alpha: 0.76) ,.white],direction: .topToBottom)
    }
    
    @IBAction func SpeakCloseTaps(_ sender: Any) {
        if state == .guide {
            let QAndA = SpeakEleQAViewCtr()
            self.navigationController?.pushViewController(QAndA, animated: true)
        }else if state == .plan {
            if SpeakElePublicManager.share.userInfo.isLogin() {
                let nav = SpeakEleBaseNavigationCtr(rootViewController: SpeakEleTabbarViewCtr())
                SpWindow.switchToController(nav)
            }else{
                let login = SpeakEleFLoginViewCtr()
                self.navigationController?.pushViewController(login, animated: true)
            }
        }else{
            self.navigationController?.AnimationState = .present
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc private func valueChange(_ switch:UISwitch) -> Void {
        isFree = SpeakSwitch.isOn
    }
    
    func toNextPage() -> Void {
        DispatchQueue.main.async {
            if self.state == .guide {
                let QAndA = SpeakEleQAViewCtr()
                self.navigationController?.pushViewController(QAndA, animated: true)
            }else if self.state == .plan {
                if SpeakElePublicManager.share.userInfo.isLogin() {
                    let nav = SpeakEleBaseNavigationCtr(rootViewController: SpeakEleTabbarViewCtr())
                    SpWindow.switchToController(nav)
                }else{
                    let login = SpeakEleFLoginViewCtr()
                    self.navigationController?.pushViewController(login, animated: true)
                }
            }else{
                self.navigationController?.AnimationState = .present
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    @IBAction func SpeakPayTaps(_ sender: Any) {
        viewModel.purchase(isFree ? .week : .year ) {[weak self] respose in
            
            let idx = self?.isFree ?? false ? 0 : 1;
            let skproduct:SKProduct? = IAPViewModel.share.IAPProducts?[safe:idx] ?? SKProduct()
            switch respose {
            case .success(let su):
                if let success:Bool = su as? Bool ,success == true{
                    APIReportManager.shared.startReport(type: .apple_billing_success, ext: ["productId":skproduct?.productIdentifier ?? "","from":"SpeckPurchase"])
                    self?.toNextPage()
                }
                break
            case .failure(let error):
                APIReportManager.shared.startReport(type: .apple_billing_error, ext: ["productId":skproduct?.productIdentifier ?? "","info":error.localizedDescription,"from":"SpeckPurchase"])
                break
            }
        }
    }
    
    @IBAction func SpeakRestoreTaps(_ sender: Any) {
        viewModel.restore(isFree ? .week : .year, completion: {[weak self] respose in
            
            let idx = self?.isFree ?? false ? 0 : 1;
            let skproduct:SKProduct? = IAPViewModel.share.IAPProducts?[safe:idx] ?? SKProduct()
            
            switch respose {
            case .success(let su):
                if let success:Bool = su as? Bool , success == true{
                    APIReportManager.shared.startReport(type: .apple_billing_success, ext: ["productId":skproduct?.productIdentifier ?? "","from":"SpeckPurchase"])
                    self?.toNextPage()
                }
                break
            case .failure(let error):
                APIReportManager.shared.startReport(type: .apple_billing_error, ext: ["productId":skproduct?.productIdentifier ?? "","info":error.localizedDescription,"from":"SpeckPurchase"])
                break
            }
        })
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
    }
}


extension SpeakEleIAPViewCtr {
    
    private func configsUI() -> Void {
        if self.Products.count > 1 {
            if isFree {
                if let p = self.Products[safe: 0] {
                    
                    let att = "Unlimited dialogue learning, unlimited answer correction, real-time Al feedback, unlimited word parsing\n".attributed().font(UIFont.montserrat(.regular,size: 16)).color(.init(hex: 0x000000,alpha: 0.54)).build().combined(with: [ "Free for 3 days, then \(p?.localizedPrice ?? "--") per week".attributed().font(UIFont.montserrat(.regular,size: 18)).color(.init(hex: 0x000000,alpha: 1)).build()  ])
                    
//                    SpeakPayDescritionL.text = "Unlimited dialogue learning, unlimited answer correction, real-time Al feedback, unlimited word parsing\nFree for 3 days, then \(p?.localizedPrice ?? "--") per week"
                    
                    SpeakPayDescritionL.attributedText = att
                    let payDay = Date().Common(day: 3).toStr("MMM dd, yyyy") ?? "--"
                    SpeakTL1.text = "Today Start"
                    SpeakTL2.text = "become due \(payDay)"
                    SpeakRTL1.text = "\(p?.symbol ?? "-")0.00"
                    SpeakRTL2.text = "\(p?.localizedPrice ?? "--")"
                    SpeakPayTitleL.text = "Free Trial Enabled"
                    SpeakFreeTL1.isHidden = false
                    SpeakSave.isHidden = true
                    SpeakPayBut.setTitle("Try Free", for: .normal)
                }
            }else{
                if let p = self.Products[safe: 1] {
                    
                    let att = "Unlimited dialogue learning, unlimited answer correction, real-time Al feedback, unlimited word\n".attributed().font(UIFont.montserrat(.regular,size: 16)).color(.init(hex: 0x000000,alpha: 0.54)).build().combined(with: [ "parsing \(p?.localizedPrice ?? "--")/year".attributed().font(UIFont.montserrat(.regular,size: 18)).color(.init(hex: 0x000000,alpha: 1)).build() ])
                    SpeakPayDescritionL.attributedText = att
//                    SpeakPayDescritionL.text = "Unlimited dialogue learning, unlimited answer correction, real-time Al feedback, unlimited word parsing\n\(p?.localizedPrice ?? "--")/year"
                    
                    
                    let week = String(format: "%.2lf", (p?.price.doubleValue ?? 0) / (12*4.0))
                    SpeakTL1.text = "Per week"
                    SpeakTL2.text = "One year validity period"
                    SpeakRTL1.text = "\(p?.symbol ?? "-")\(week)/week"
                    SpeakRTL2.text = "\(p?.localizedPrice ?? "--")"
                    SpeakPayTitleL.text = "Open a free trial"
                    SpeakFreeTL1.isHidden = true
                    SpeakSave.isHidden = false
                    SpeakPayBut.setTitle("Start Now", for: .normal)
                }
            }
            
        }
    }
    
}
 
