//
//  SpeakElePracticeReviewViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/23.
//

import UIKit

class SpeakElePracticeReviewViewCtr: SpeakEleBaseViewCtr {

    @IBOutlet weak var SpeakNextBtn: UIButton!
    @IBOutlet weak var SpeakCollectionV: UICollectionView!
    
    @IBOutlet var SpeakItemBtns: [UIButton]!
    
    private let viewModel = SpeakPracticeNetViewModel()
    private let collectViewModel = SpeakEleProfileNetViewModel()
    private var startStudyT:Date = Date()
    var leasionName:String = ""
    @IBOutlet weak var SpeakTipsRight: UIView!
    @IBOutlet weak var SpeakTipsLeft: UIView!
    
    private var showTips:Bool {
        set {
            UserDefaults.standard.set(newValue, forKey: UnsafeRawUserDefaultsKey.UnsafePracticeFailTipsShow.rawValue)
            UserDefaults.standard.synchronize()
        }
        get {
            let tips = UserDefaults.standard.object(forKey: UnsafeRawUserDefaultsKey.UnsafePracticeFailTipsShow.rawValue) as? Bool ?? false
            return tips
        }
    }
    
    var leassion:Int = 0
    @BoundedZeroNumber var currentIdx = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "\(currentIdx+1) / \(datasource.count)"
        self.rightImage = "icon_wordbook"
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        SpeakTipsRight.gesture(target: self, class: UITapGestureRecognizer.self, selector: #selector(self.tipsHide(_:)))
        SpeakTipsLeft.gesture(target: self, class: UITapGestureRecognizer.self, selector: #selector(self.tipsHide(_:)))
    
        let Fab = UserDefaults.standard.object(forKey: UnsafeRawUserDefaultsKey.UnsafePracticeTipsShow.rawValue) as? Bool ?? false
        if Fab {
            SpeakTipsRight.alpha = 0
            SpeakTipsLeft.alpha = 0
        }else{
            SpeakTipsRight.alpha = 0
            SpeakTipsLeft.alpha = 1
            UserDefaults.standard.setValue(true, forKey: UnsafeRawUserDefaultsKey.UnsafePracticeTipsShow.rawValue)
        }
    }
    
    override func PopViewCtr() {
        let name = SpeakElePublicManager.share.userInfo.targetLanguage ?? ""
        let saveData = self.datasource.map { bt in
            var temp = bt
            temp.isFront = nil
            return temp
        }
        SpeakCache.cache.SaveModel(cache: saveData, state: .PracticeCache, name: name)
        super.PopViewCtr()
    }

    @objc private func tipsHide(_ res:UIGestureRecognizer) -> Void {
        let view = res.view
        if view == SpeakTipsLeft {
            view?.alpha = 0
            SpeakTipsRight.alpha = 1
        }else{
            view?.alpha = 0
        }
    }
    
    override func setup() {
        SpeakCollectionV.delegate = self
        SpeakCollectionV.dataSource = self
        SpeakCollectionV.isScrollEnabled = false
        SpeakCollectionV.register(UINib(nibName: SpeakPracticeReviewCell.id, bundle: nil), forCellWithReuseIdentifier: SpeakPracticeReviewCell.id)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.bringSubviewToFront(SpeakCollectionV)
        self.view.bringSubviewToFront(SpeakTipsRight)
        self.view.bringSubviewToFront(SpeakTipsLeft)
        startStudyT = Date()
    }
    
    override func rightTaps() {
        let vc = SpeakPracticeWordsListViewCtr()
        vc.leasionId = self.leassion
        vc.leasionName = self.leasionName
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func SpeakItemTaps(_ sender: UIButton) {
        Print(sender.tag)
        StrangeFamilar(state: sender.tag == 2 ? .left : .right)
    }
    
    @IBAction func SpeakNextTaps(_ sender: Any) {
        if currentIdx <= 0 {
            return
        }
        currentIdx -= 1
        performFlipAnimation()
    }
    
    private var isAnimating = false
    
    /// 返回
    private func performFlipAnimation() {
        if isAnimating == false {
            isAnimating = true
            guard let cell = SpeakCollectionV.cellForItem(at: IndexPath(row: currentIdx, section: 0)) else { return }
            var frame = cell.frame
            let data = self.datasource[currentIdx]
            frame.origin.x = (data.markStatus == 2 ? -500 : 500)
            cell.frame = frame
            cell.isHidden = false
            frame.origin = CGPoint()
            UIView.animate(withDuration: 0.25) {
                cell.frame = frame
                cell.alpha = 1
            } completion: { _ in
                self.isAnimating = false
                self.title = "\(self.currentIdx+1) / \(self.datasource.count)"
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let call = self.view.callblack {
            call(self.datasource)
        }
    }
    
    deinit {
        self.view.callblack = nil
    }
    
    var datasource:[SpeakPracticeWordModel] = []
    var dataMark:[SpeakPracticeWordModel] = []
}

extension SpeakElePracticeReviewViewCtr : UICollectionViewDelegate,UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{
    
    private func setFavaret(_ fw:Bool , indexPath:IndexPath) -> Void {
        let d = self.datasource[indexPath.row].wordId
        collectViewModel.collect(param: ["businessId":d,
                                         "type":2,
                                         "isCollect":fw]) {[weak self] su, data in
            self?.datasource[indexPath.row].isCollected = su ? fw : !fw
            let cell = self?.SpeakCollectionV.cellForItem(at: indexPath) as? SpeakPracticeReviewCell
            cell?.data = self?.datasource[indexPath.row]
        }
    }
    
    private func StrangeFamilar(state:SpeakPracticeReviewCell.SpeakPracticeReviewState) -> Void {
        
        let cell = SpeakCollectionV.cellForItem(at: IndexPath(row: currentIdx, section: 0))
        var frame = cell?.frame
        if state == .left {
            frame?.origin.x = (-500)
            UIView.animate(withDuration: 0.2) {
                cell?.frame = frame ?? CGRect()
            } completion: { su in
                if su {
                    frame?.origin.y = 0
                    cell?.frame = frame ?? CGRect()
                    cell?.alpha = 0
                    self.SpeakCollectionV.reloadData()
                }
            }
        }else{
            frame?.origin.x = (500)
            UIView.animate(withDuration: 0.2) {
                cell?.frame = frame ?? CGRect()
            } completion: { su in
                if su {
                    frame?.origin.y = 0
                    cell?.frame = frame ?? CGRect()
                    cell?.alpha = 0
                    self.SpeakCollectionV.reloadData()
                }
            }
        }
        
        let id = self.datasource[currentIdx].wordId
        let word = self.datasource[currentIdx].word
        self.datasource[currentIdx].markStatus = (state == .left ? 2 : 1)
        
        viewModel.turnCard(param: [
            "courseId": self.leassion,
            "wordId": id ?? 0,
            "conditionType": (state == .left ? 2 : 1),
            "word": word ?? ""
        ]) {[weak self] (su, data:SpeakNetBaseDeflutMode?) in
            
        }
        /// 学习完成
        if currentIdx >= self.datasource.count - 1 {
            let stopTm = Date()
            let secord = stopTm.timeIntervalSince1970 - startStudyT.timeIntervalSince1970
            let vc = SpeakPacticeFinishViewCtr()
            vc.data = self.datasource
            vc.wordTm = Int(secord)
            self.navigationController?.pushViewController(vc, animated: true)
            return
        }
        currentIdx += 1
        if showTips == false {
            showTips = true
            let tips = SpeakPacticeFailTipViewCtr()
            tips.modalPresentationStyle = .overFullScreen
            self.present(tips, animated: true)
        }
        
        self.title = "\(currentIdx+1) / \(datasource.count)"
        self.SpeakItemBtns.forEach({$0.isSelected = false})
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datasource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: SpeakPracticeReviewCell.id, for: indexPath) as! SpeakPracticeReviewCell
        cell.isHidden = (indexPath.row < currentIdx ? true : false)
        cell.data = datasource[indexPath.row]
//        cell.clipsToBounds = true
        cell.corners = 16
        cell.backgroundColor = .white
        cell.SpeakCallblack = { [weak self] state in
            self?.StrangeFamilar(state: state)
        }
        cell.callblack = { [weak self] state in
            if let st:SpeakPracticeReviewCell.SpeakPracticeReviewState = state as? SpeakPracticeReviewCell.SpeakPracticeReviewState {
                if st == .left {
                    self?.SpeakItemBtns[0].isSelected = true
                    self?.SpeakItemBtns[1].isSelected = false
                }else if st == .right{
                    self?.SpeakItemBtns[0].isSelected = false
                    self?.SpeakItemBtns[1].isSelected = true
                }else{
                    self?.SpeakItemBtns.forEach({$0.isSelected = false})
                }
            }else if let fav = state as? Bool {
                self?.setFavaret( fav,indexPath: indexPath)
            }
        }
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return collectionView.size
    }
}
