//
//  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!
    
    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
    }

    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)
            }
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        SpeakEasyV.shadow(cornerRadius: 16,shadowColor: .init(hex: 0x000000,alpha: 1),opacity: 0.06,radius: 16)
        SpeakPayContentV.shadow(cornerRadius: 8,shadowColor: .init(hex: 0x000000,alpha: 1),opacity: 0.06,radius: 8)
    }
    
    @IBAction func SpeakCloseTaps(_ sender: Any) {
        if state == .guide {
            let QAndA = SpeakEleQAViewCtr()
            self.navigationController?.pushViewController(QAndA, animated: true)
        }else if state == .plan {
            if SpeakElePublicManager.share.PublicData.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
    }
    
    @IBAction func SpeakPayTaps(_ sender: Any) {
        viewModel.purchase(isFree ? .week : .year ) { respose in
            switch respose {
            case .success(let su):
                
                break
            case .failure(let error):
                
                break
            }
        }
    }
    
    @IBAction func SpeakRestoreTaps(_ sender: Any) {
        viewModel.restore(isFree ? .week : .year, completion: { respose in
            switch respose {
            case .success(let su):
                
                break
            case .failure(let error):
                
                break
            }
        })
    }
}


extension SpeakEleIAPViewCtr {
    
    private func configsUI() -> Void {
        if self.Products.count > 1 {
            if isFree {
                if let p = self.Products[safe: 0] {
                    SpeakPayDescritionL.text = "Unlimited dialogue learning, unlimited answer correction, real-time Al feedback, unlimited word parsing\nFree for 3 days, then \(p?.localizedPrice ?? "--") per week"
                    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] {
                    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)
                }
            }
            
        }
    }
    
}
 
