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

import UIKit

class SpeakPracticeReviewCell: UICollectionViewCell {

    
    @IBOutlet var SpeakLeftTips: UIView!
    @IBOutlet weak var SpeakLeftLabel: UILabel!
    
    @IBOutlet var SpeakRightTips: UIView!
    @IBOutlet weak var SpeakRightLabel: UILabel!
    private let viewmodel = SpeakPracticeNetViewModel()
    
    static let id = "SpeakPracticeReviewCell"
    private let leftMax:Double = -70
    private let rightMax:Double = 70
    var isShowingFront = true
    var wordDetail:SpeakPracticeWordDetailModel?
    
    enum SpeakPracticeReviewState {
        case left
        case right
        case none
    }
    
    private var beginP = CGPoint()
    var SpeakCallblack: ((_ state:SpeakPracticeReviewState)-> Void)?
    
    
    private var isShow:Bool{
        set {}
        get {
            return IAPViewModel.share.isSubscribed || SpeakDayEveryManager.manager.SpeakDayData.PracticeFreeNum ?? 0 > 0
        }
    }
    
    var data:SpeakPracticeWordModel? {
        didSet{
            isShowingFront = data?.isFront ?? true
            UIView.transition(with: isShowingFront ? Word : back , duration: 0, options: [.transitionFlipFromRight]) { }
            
            Word.SpeakPracticeWord.text = data?.word
            Word.setLabel(data?.markStatus == 1 ? 1 : (data?.markStatus == 2 ? 2 : 0 ) )
            Word.SpeakPracticeIcon.image = UIImage(named: "sp-Practicebg-\(((data?.wordId ?? 0)%14)+1)")
            Word.clipsToBounds = true
            Word.corners = 16
            Word.backgroundColor = .clear
            Word.SpeakPracticeFavorites.isSelected = data?.isCollected ?? false
            
            back.SpeakPracticeBackWord.text = data?.word
            back.SpeakPracticeBackFavorites.isSelected = data?.isCollected ?? false
            
            Word.isHidden = !isShowingFront
            back.isHidden = isShowingFront
            back.corners = 16
            wordDetail = SpeakWordTranslateData.data.WordTranslate?[data?.wordId ?? 0]
            if let translation = wordDetail?.translation {
                translationFunc()
            }else{
                translationHide()
            }
        }
    }
    
    
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.gesture(target: self, class: UIPanGestureRecognizer.self, selector: #selector(panGesture(_:)))
        self.gesture(target: self, class: UITapGestureRecognizer.self, selector: #selector(FlipTaps))
        back.snp.makeConstraints { make in
            make.left.right.bottom.top.equalToSuperview().inset(4)
        }
        Word.snp.makeConstraints { make in
            make.left.right.bottom.top.equalToSuperview()
        }
        SpeakLeftLabel.contentInsets = UIEdgeInsets(top: 3, left: 10, bottom: 3, right: 10)
        SpeakRightLabel.contentInsets = UIEdgeInsets(top: 3, left: 10, bottom: 3, right: 10)
        SpeakLeftTips.isHidden = true
        SpeakRightTips.isHidden = true
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        contentView.bringSubviewToFront(SpeakLeftTips)
        contentView.bringSubviewToFront(SpeakRightTips)
        self.layoutIfNeeded()
        back.shadow(cornerRadius: 16, shadowColor: .init(hex: 0x000000), offset: CGSize(width: 0, height: 0), opacity: 0.06, radius: 4)
    }
    
    private lazy var Word: SpeakPracticeWordView = {
        let w = SpeakPracticeWordView()
        contentView.addSubview(w)
        w.callblack = {  [weak self] fw in
            if let call = self?.callblack {
                call(fw)
            }
        }
        return w
    }()
    
    private lazy var back: SpeakPracticeBackView = {
        let b = SpeakPracticeBackView.xib()
        b.callblack = { [weak self] fw in
            if let call = self?.callblack {
                call(fw)
            }
        }
        contentView.addSubview(b)
        return b
    }()
    
    deinit {
        SpeakCallblack = nil
    }
}


extension SpeakPracticeReviewCell {
    
    private func netwokng() -> Void {
        viewmodel.cardTranslate(param: ["word":data?.word ?? ""]) {[weak self] (success, data:SpeakPracticeWordDetailModel?) in
            if success {
                self?.wordDetail = data
                SpeakWordTranslateData.data.WordTranslate?[self?.data?.wordId ?? 0] = data
                SpeakDayEveryManager.manager.SpeakDayData.PracticeFreeNum! -= 1
                SpeakDayEveryManager.manager.update()
                self?.translationHide()
            }
        }
    }
    
    
    @objc private func FlipTaps() -> Void {
        if wordDetail == nil && isShow == true {
            self.netwokng()
        }else if wordDetail == nil {
            self.translationHide()
        }
        UIView.transition(
            from: isShowingFront ? Word : back,
            to: isShowingFront ? back : Word,
            duration: 12/60.0,
            options: [.transitionFlipFromRight, .showHideTransitionViews],
            completion: { [weak self] _ in
                self?.isShowingFront.toggle()
                guard let call = self?.callblack else { return }
//                call( (self?.isShowingFront ?? true ? 1 : 0) )
            }
        )
    }
    
    @objc private func panGesture(_ recognizer:UIGestureRecognizer) -> Void {
        let p = recognizer.location(in: self)
        if recognizer.state == .began {
            beginP = p
        }else if recognizer.state == .cancelled || recognizer.state == .ended || recognizer.state == .failed {
            SpeakLeftTips.isHidden = true
            SpeakRightTips.isHidden = true
            if self.frame.origin.x < leftMax {
                if let call = SpeakCallblack {
                    call(.left)
                }
            }else if self.frame.origin.x > rightMax {
                if let call = SpeakCallblack {
                    call(.right)
                }
            }else{
                UIView.animate(withDuration: 0.2) {
                    self.frame = self.bounds
                }
            }
        }else {
            let newP:CGPoint = CGPoint(x: p.x - beginP.x, y: p.y - beginP.y)
            let bound = self.frame
            self.frame = CGRectMake(bound.origin.x + newP.x ,bound.origin.y + newP.y, bound.width, bound.height)
            guard let call = callblack else { return }
            if self.frame.origin.x < leftMax {
                call(SpeakPracticeReviewState.left)
                SpeakLeftTips.isHidden = false
                SpeakRightTips.isHidden = true
            }else if self.frame.origin.x > rightMax {
                call(SpeakPracticeReviewState.right)
                SpeakLeftTips.isHidden = true
                SpeakRightTips.isHidden = false
            }else{
                call(SpeakPracticeReviewState.none)
                SpeakLeftTips.isHidden = true
                SpeakRightTips.isHidden = true
            }
        }
    }
    
    
    private func translationFunc() -> Void {
        back.SpeakPracticeBackWord1.text = wordDetail?.translation
        back.SpeakPracticeBackUnlock.isHidden = true
        let anto = "Antonym: ".attributed().color(.init(hex: 0x3980F6)).build()
        let Example = "Example sentence:\n".attributed().color(.init(hex: 0x3980F6)).build()
        let att = "Synonyms: ".attributed().color(.init(hex: 0x3980F6)).build().combined(with: [wordDetail?.synonyms,"\n\n",anto,wordDetail?.antonym,"\n\n" ,Example,wordDetail?.example])
        back.SpeakPracticeBackDesc.attributedText = att
    }
    
    private func translationHide() -> Void {
        back.SpeakPracticeBackWord1.text = wordDetail?.translation
        back.SpeakPracticeBackUnlock.isHidden = false
        back.SpeakPracticeBackDesc.attributedText = "".attributed().build()
    }
}
