//
//  SpeakEleHomeViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/3.
import UIKit
import SnapKit


class SpeakEleHomeViewCtr: SpeakEleBaseViewCtr, UIPopoverPresentationControllerDelegate {
 
    @IBOutlet weak var headerBoard: UIView!
    @IBOutlet weak var SpeakProgressL: UILabel!
    @IBOutlet weak var SpeakEnglistShow: UIButton!

    @IBOutlet weak var SpeakHomeSignL: UILabel!
    @IBOutlet weak var SpeakSignView: UIStackView!
    
    @IBOutlet weak var SpeakFreeTm: UIButton!
    @IBOutlet weak var SpeakAIIcon: UIImageView!
    @IBOutlet weak var SpeakAIName: UILabel!
    
    private var lessonDataSource:[SpeakHomeLessonModel] = []
    private var offsetY = 0.0
    private let viewModel = SpeakHomeViewModel()
    private var lessonViews:[SpeakEleLessionView] = []

    private lazy var mainScrollview: UIScrollView = {
        let sView = UIScrollView()
        sView.isUserInteractionEnabled = true
        sView.isScrollEnabled = true
        return sView
    }()
     
    private lazy var topButton: UIButton = {
       let button = UIButton.init(type: .custom)
        button.setImage(UIImage(named: "sp-home-Back-Top"), for: .normal)
        button.addTarget(self, action: #selector(scrollTop), for: .touchUpInside)
       return button
   }()
    
    private lazy var freeTalk: UIButton = {
        let button = UIButton(type: .custom)
        button.setBackgroundImage(UIImage(named: "icon-chat-freeTalk"), for: .normal)
        button.addTarget(self, action: #selector(freeTalkTaps), for: .touchUpInside)
        return button
    }()
    
    private lazy var tipView: SpeakChangeStuLanguesView = {
        let tip = SpeakChangeStuLanguesView.xib()
        self.parent?.view.addSubview(tip)
        tip.frame = CGRectMake(0, -Dev.screenH, Dev.screenW, Dev.screenH)
        tip.callblack = {[weak self] idx in
            if let row = idx as? Int {
                if row == 0 {
                    self?.SpeakEnglistShow.setImage(UIImage(named: "sp-home-En"), for: .normal)
                    SpeakElePublicManager.share.userInfo.targetLanguage = "🇬🇧 English"
                }else{
                    SpeakElePublicManager.share.userInfo.targetLanguage = "🇪🇸 Español"
                    self?.SpeakEnglistShow.setImage(UIImage(named: "sp-home-Es"), for: .normal)
                }
                NotificationManager.scheduleDailyNotification()
                updateUserInformation {[weak self] su in
                    if su {
                        self?.viewModel.fetchSesson()
                        self?.viewModel.fetchUserInfo()
                    }
                }
            }
        }
        return tip
    }()
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        self.view.layoutIfNeeded()
        SpeakFreeTm.corners = SpeakFreeTm.height / 2.0
        SpeakAIIcon.corners = SpeakAIIcon.height / 2.0
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        makeUI()
        SpeakFreeTm.isHidden = IAPViewModel.share.isSubscribed
        SpeakSignView.gesture(gesture: UIView.Gesture.tap) {[weak self] res in
            guard let self = self else { return }
            let vc = SpeakHomeSignViewCtr()
            vc.modalPresentationStyle = .overFullScreen
            vc.modalTransitionStyle = .crossDissolve
            self.present(vc, animated: true)
            vc.view.callblack = {[weak self] event in
                self?.viewModel.fetchUserInfo()
                speakSignListViewModel.share.fetchSign { [weak self] in
                    self?.SpeakDataUpdate()
                    NotificationCenter.default.post(name: NSNotification.Name("calendarUpdate"), object: nil)
                }
            }
        }
        self.lessonDataSource = SpeakLeassonData.data.leassionData
        viewModel.dateUpdateComplate = {[weak self] data in
            if let sesson = data as? [SpeakHomeLessonModel] {
                self?.lessonDataSource = sesson
                SpeakLeassonData.data.leassionData = sesson
                if self?.lessonViews.count ?? 0 > 0 {
                    self?.reloadData()
                }else{
                    self?.makeLessonUI()
                }
            }
        }
        SpeakFreeTm.setImage(UIImage(named: "sp-home-clock")?.withRenderingMode(.alwaysTemplate), for: .normal)
        self.makeLessonUI()
        viewModel.AIser()
        Print("token:\(SpeakElePublicManager.share.userInfo.token)")
        NotificationCenter.default.addObserver(self, selector: #selector(IAPUpdateStatus), name: .subscriptionStatusChanged, object: nil)
     }

    private func setAISer() -> Void {
        let aiser = viewModel.AIser()
        let idx = SpeakElePublicManager.share.PublicData.AIerIndex
        let icon = "img_" + (aiser[safe: idx]?.name.lowercased() ?? "")
        self.SpeakAIIcon.image = UIImage(named: icon)
        SpeakAIName.text = aiser[safe: idx]?.name
    }
    
    /// 改变学习的语言
    @IBAction func SpeakChangeLangu(_ sender: Any) {
        if IAPViewModel.share.isSubscribed {
            self.view.bringSubviewToFront(tipView)
            tipView.selectIdx = SpeakElePublicManager.share.userInfo.targetLanguage == "🇬🇧 English" ? 0 : 1
            tipView.show()
        }
    }
    
    private func SpeakDataUpdate() -> Void {
        var signN = 0
        if let values = speakSignListViewModel.share.signList?.values {
            for (v) in values {
                signN += v.count
            }
        }
        SpeakHomeSignL.text = "\(signN)"
        let total = self.lessonDataSource.count
        let Pro = 1
        SpeakProgressL.text = "\(Pro)/\(total)"
        let tm = SpeakDayEveryManager.manager.SpeakDayData.studyFreeTm ?? 300
        let min = tm / 60
        let sec = tm % 60
        SpeakFreeTm.setTitle(String(format: "%02d:%02d", min,sec), for: .normal)
        SpeakFreeTm.titleLabel?.adjustsFontSizeToFitWidth = true
    }
    
    @IBAction func ShowPro(_ sender: Any) {
        if IAPViewModel.share.isSubscribed {
            Alert(message: "You have unlocked all the benefits")
            return
        }
        let iap = SpeakEleIAPViewCtr()
        iap.state = .other
        self.navigationController?.AnimationState = .present
        self.navigationController?.pushViewController(iap, animated: true)
    }
    
    @IBAction func SpeakChangeAI(_ sender: Any) {
        let changeAi = SpeakChangeAIViewCtr()
        let nav = SpeakEleBaseNavigationCtr(rootViewController: changeAi)
        nav.modalPresentationStyle = .overFullScreen
        nav.modalTransitionStyle = .crossDissolve
        changeAi.view.callblack = { [weak self] change in
            self?.setAISer()
            SpeakAIVideoPlayManager.share.loadVideo()
        }
        self.present(nav, animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        titleView.isHidden = true
        setAISer()
        viewModel.fetchSesson()
        viewModel.fetchUserInfo()
        speakSignListViewModel.share.fetchSign { [weak self] in
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.4) {
                self?.SpeakDataUpdate()
            }
        }
        if SpeakElePublicManager.share.userInfo.targetLanguage == "🇬🇧 English" {
            self.SpeakEnglistShow.setImage(UIImage(named: "sp-home-En"), for: .normal)
        }else{
            self.SpeakEnglistShow.setImage(UIImage(named: "sp-home-Es"), for: .normal)
        }
        /// 新用户直接进课程
        if SpeakElePublicManager.share.userInfo.newUser ?? true {
            SpeakElePublicManager.share.userInfo.newUser = false
            let vc = SpeakNewUserViewCtr()
            vc.isReStart = true
            vc.isMute = false
            vc.view.callblack = { [weak self] tip in
                self?.TipsSign(tip as? Bool ?? false)
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
    }
    
    @objc private func IAPUpdateStatus() -> Void {
        SpeakFreeTm.isHidden = IAPViewModel.share.isSubscribed
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension SpeakEleHomeViewCtr {
    
    private func reloadData() -> Void {
        var lessonId = 0
        for (v) in self.lessonDataSource {
            if v.isLocked == false {
                lessonId = v.lessonId ?? 0
            }
        }
        for (i,v) in lessonViews.enumerated() {
            let data = lessonDataSource[safe: i]
            v.data = data
            v.isStart = !(data?.lessonId == lessonId)
            if data?.lessonId == lessonId {
                offsetY = v.y - 70.0
            }
        }
    }
    
    private func TipsSign(_ sign:Bool) -> Void {
        guard let date = Date().toStr("yyyy-MM") else { return }
        if let month = speakSignListViewModel.share.signList?[date] {
            let db = Date().toStr("yyyy-MM-dd")
            let count = month.filter({$0.signDate == db}).count
            if count <= 0 && sign {
                let alert = SpeakEleSignTipsViewCtr()
                alert.modalPresentationStyle = .overFullScreen
                alert.alert()
            }
        }
    }
    
    @objc private func scrollTop() -> Void {
        if self.offsetY < 0 {
            self.offsetY = 0
        }
        UIView.animate(withDuration: 0.2) {
            self.mainScrollview.contentOffset = CGPoint(x: 0, y: self.offsetY)
        }
    }
    
    @objc private func freeTalkTaps() {
        let freeTalk = SpeakFreeTalkViewCtr()
        self.navigationController?.pushViewController(freeTalk, animated: true)
    }
    
    private func StartLeassion(_ idx:SpeakHomeLessonModel?) -> Void {
        let call:((SpeakLessonDescpModel?,Bool,Bool)->Void) = { [weak self] (DescpModel,restart,Mute) in
            let dialogue = SpeakDialogueViewCtr()
            dialogue.dataLesssion = DescpModel
            dialogue.isReStart = restart
            dialogue.isMute = Mute
            dialogue.view.callblack = { [weak self] tip in
                self?.TipsSign(tip as? Bool ?? false)
            }
            self?.navigationController?.pushViewController(dialogue, animated: true)
        }
        let payCall = {[weak self] in
            let iap = SpeakEleIAPViewCtr()
            iap.state = .other
            self?.navigationController?.AnimationState = .present
            self?.navigationController?.pushViewController(iap, animated: true)
        }
        
        let data = SpeakLessonDescpModel()
        data.id = idx?.lessonId
        data.name = idx?.lessonName
        data.lessonKey = idx?.lessonName
        data.lessonId = idx?.lessonIdString
        data.vocabularyList = idx?.vocabularyList
        data.lessonLevel = "\(idx?.lessonLevel ?? 1)"
        data.description = idx?.description
        data.grammarList = idx?.grammarList
        
        if idx?.isLocked == true {
            let alert = SpeakPublicTipsViewCtr(configs: SpeakPublicTipsViewCtr.PublicTipsModel(icon: UIImage(named: "img_course"),title: "skip a grade?",descAttr: "Do you want to unlock all courses immediately",sureAction: "Yes, unlock immediately",cancel: "Wait a minute"))
            alert.show()
            alert.view.callblack = { su in
                if let success = su as? Bool , success == true {
                    if IAPViewModel.share.isSubscribed {
                        call(data,false,false)
                    }else{
                        payCall()
                    }
                }
            }
        }else{
            if idx?.isLearned == true {
                let alert = SpeakPublicTipsViewCtr(configs: SpeakPublicTipsViewCtr.PublicTipsModel(icon: UIImage(named: "img_chahua"),title: "Continue with class?",descAttr: "Do you want to continue your previous studies?",sureAction: "Yes, keep learning",cancel: "I want to start classes again"))
                alert.show()
                alert.view.callblack = {[weak self] su in
                    if let success = su as? Bool {
                        if success {
                            call(data,!success ,false)
                        }else{
                            DispatchQueue.main.asyncAfter(deadline: .now()+0.2) {
                                let tips = SpeakTipssssssViewCtr()
                                tips.data = data
                                tips.modalPresentationStyle = .overFullScreen
                                tips.modalTransitionStyle = .crossDissolve
                                self?.present(tips, animated: true)
                                tips.view.callblack = {[weak self] Cdata in
                                    if let b = Cdata as? Bool {
                                        call(data ,true , b)
                                    }
                                    self?.viewModel.fetchSesson()
                                }
                            }
                        }
                    }else{
                    }
                }
            }else{
                let tips = SpeakTipssssssViewCtr()
                tips.data = data
                tips.modalPresentationStyle = .overFullScreen
                tips.modalTransitionStyle = .crossDissolve
                self.present(tips, animated: true)
                tips.view.callblack = {[weak self] Cdata in
                    if let b = Cdata as? Bool {
                        call(data ,true , b)
                    }
                    self?.viewModel.fetchSesson()
                }
            }
        }
    }
    
    private func makeUI() {
        self.view.insertSubview(mainScrollview, belowSubview: headerBoard)
        self.view.addSubview(topButton)
        self.view.addSubview(freeTalk)
        mainScrollview.snp.makeConstraints { make in
            make.top.equalTo(headerBoard.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(Dev.safeAreaInsets.bottom + 50)
        }
        topButton.snp.makeConstraints { make in
            make.bottom.equalTo(mainScrollview.snp.bottom).offset(15)
            make.right.equalTo(self.view.snp.right).offset(-16)
//            make.size.equalTo(CGSize(width: 48, height: 48))
        }
        freeTalk.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(16)
            make.centerY.equalTo(topButton.snp.centerY)
//            make.size.equalTo(CGSize(width: 48, height: 55))
        }
    }

    private func makeLessonUI() {
        self.view.layoutIfNeeded()
        if self.lessonDataSource.count > 0 {
            mainScrollview.subviews.forEach { view in
                if view is UIImageView || view is SpeakEleLessionView || view is SpeakEntryLevelView{
                    view.removeFromSuperview()
                }
            }
            lessonViews.removeAll()
            var source:[[SpeakHomeLessonModel]] = []
            var lessonId = 0
            for (v) in self.lessonDataSource {
                if v.isLocked == false {
                    lessonId = v.lessonId ?? 0
                }
            }
            for i in 1...6 {
                source.append(self.lessonDataSource.filter({$0.lessonLevel == i}))
            }
            let btnW:Double = 98, btnH:Double = 98 ,spaceing:Double = 56 + 98
            let Pro = SpeakEleQAViewModel().proficiency
            var offset:Double = 6
            for (i,data) in source.enumerated() {
                offset += 16
                if i > 0 {
                    offset += 16
                }
                let tl = Pro[i]
                let t = SpeakEntryLevelView.xib(tl)
                self.mainScrollview.addSubview(t)
                t.snp.makeConstraints { make in
                    make.width.equalToSuperview()
                    make.left.equalToSuperview()
                    make.top.equalToSuperview().offset(offset)
                    make.height.equalTo(22)
                }
                offset += 32
                var range = data.count/2
                if data.count % 2 == 0 {
                    let backV = UIImageView()
                    let iname = range % 2 == 1 ? "xuxian1" : "xuxian3"
                    backV.image = UIImage(named: iname)
                    backV.layer.zPosition = -100
                    mainScrollview.addSubview(backV)
                    backV.snp.remakeConstraints({ make in
                        if range % 2 == 1 {
                            make.right.equalTo(mainScrollview.snp.centerX)
                        }else{
                            make.left.equalTo(mainScrollview.snp.centerX)
                        }
                        make.top.equalToSuperview().offset((spaceing) * Double(range-1) + (btnH/2.0) + offset)
                        make.width.equalTo(137.adapterW())
                        make.height.equalTo((spaceing/2.0))
                    })
                    range -= 1
                    if range < 0 {
                        range = 0
                    }
                }
                for num in 0...range where num > 0 {
                    let backV = UIImageView()
                    let iname = num % 2 == 1 ? "sp-home-xuxianL" : "sp-home-xuxianR"
                    backV.image = UIImage(named: iname)
                    backV.layer.zPosition = -100
                    mainScrollview.addSubview(backV)
                    backV.snp.remakeConstraints({ make in
                        if num % 2 == 1 {
                            make.right.equalTo(mainScrollview.snp.centerX)
                        }else{
                            make.left.equalTo(mainScrollview.snp.centerX)
                        }
                        make.top.equalToSuperview().offset((spaceing) * Double(num-1) + (btnH/2.0) + offset)
                        make.width.equalTo(137.adapterW())
                        make.height.equalTo(spaceing)
                    })
                }
                for (j,sdata) in data.enumerated() {
                    let view = SpeakEleLessionView()
                    view.data = sdata
                    self.mainScrollview.addSubview(view)
                    self.lessonViews.append(view)
                    view.layer.zPosition = 100
                    view.isStart = !(sdata.lessonId == lessonId)
                    if sdata.lessonId == lessonId {
                        offsetY = (offset - 70)
                        if offsetY < 0 {
                            offsetY = 0
                        }
                    }
                    view.callblack = {[weak self] idx  in
                        self?.StartLeassion(idx as? SpeakHomeLessonModel)
                    }
                    if j % 4 == 3 {
                        view.snp.remakeConstraints { make in
                            make.left.equalToSuperview().inset(Dev.screenW - 24.adapterW() - btnW)
                            make.top.equalToSuperview().offset(offset)
                            make.size.equalTo(CGSizeMake(btnW, btnH))
                        }
                    }else if j % 2 == 1 {
                        view.snp.remakeConstraints { make in
                            make.left.equalToSuperview().offset(24.adapterW())
                            make.top.equalToSuperview().offset(offset)
                            make.size.equalTo(CGSizeMake(btnW, btnH))
                        }
                    }else{
                        view.snp.remakeConstraints { make in
                            make.centerX.equalToSuperview()
                            make.top.equalToSuperview().offset(offset)
                            make.size.equalTo(CGSizeMake(btnW, btnH))
                        }
                    }
                    if j == data.count - 1 {
                        offset += (btnH/2.0)
                    }else{
                        offset += (spaceing/2.0)
                    }
                    if i == source.count-1 && j == data.count - 1 {
                        self.mainScrollview.layoutIfNeeded()
                        self.mainScrollview.contentSize = CGSize(width: 0, height: CGRectGetMaxY(view.frame) + 80)
                    }
                }
                offset += (btnH/2.0)
            }
        }
        DispatchQueue.main.async {
            self.scrollTop()
        }
    }
}
