//
//  SpeakElePracticeViewCell.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/22.
//

import UIKit

class SpeakElePracticeViewCell: UICollectionViewCell {

    static let id = "SpeakElePracticeViewCell"
    var isShowingFront = true
    @IBOutlet weak var SpeakPracticeNormal: SpeakPracticeWordView!
    @IBOutlet weak var SpeakPracticeBack: UIView!
    private let viewmodel = SpeakPracticeNetViewModel()
    private let homeViewModel = SpeakDialogueViewModel()
    var wordDetail:SpeakPracticeWordDetailModel?
    
    private var isShow:Bool{
        set {}
        get {
            return IAPViewModel.share.isSubscribed || SpeakDayEveryManager.manager.SpeakDayData.PracticeFreeNum ?? 0 > 0
        }
    }
    
    var data:SpeakPracticeWordModel? {
        didSet{
            SpeakPracticeNormal.SpeakPracticeWord.text = data?.word
            SpeakPracticeNormal.SpeakPracticeFavorites.isSelected = data?.isCollected ?? false
            back.SpeakPracticeBackWord.text = data?.word
            back.SpeakPracticeBackFavorites.isSelected = data?.isCollected ?? false
            SpeakPracticeNormal.setLabel(-1)
            isShowingFront = data?.isFront ?? true
            UIView.transition(with: isShowingFront ? SpeakPracticeNormal : SpeakPracticeBack , duration: 0, options: [.transitionFlipFromRight]) { }
            SpeakPracticeNormal.isHidden = !isShowingFront
            SpeakPracticeBack.isHidden = isShowingFront
            wordDetail = SpeakWordTranslateData.data.WordTranslate?[data?.wordId ?? 0]
            if (wordDetail != nil) {
                self.showDescp()
            }else if !isShow{
                self.HideDescp()
            }
            SpeakPracticeNormal.SpeakPracticeIcon.image = UIImage(named: "sp-Practicebg-\(((data?.wordId ?? 0)%14)+1)")
        }
    }
    
    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?.showDescp()
            }
        }
    }
    
    private func netTranslate() -> Void {
        homeViewModel.translate(msg: data?.word ?? "") { text in
            self.back.SpeakPracticeBackWord1.text = text
        }
    }
    
    private func showDescp() -> 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 HideDescp() -> Void {
        back.SpeakPracticeBackWord1.text = wordDetail?.translation
        back.SpeakPracticeBackUnlock.isHidden = false
        back.SpeakPracticeBackDesc.attributedText = "".attributed().build()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.clipsToBounds = false
        SpeakPracticeNormal.gesture(target: self, class: UITapGestureRecognizer.self, selector: #selector(FlipTaps))
        SpeakPracticeBack.gesture(target: self, class: UITapGestureRecognizer.self, selector: #selector(FlipTaps))
        back.snp.makeConstraints { make in
            make.left.right.bottom.top.equalToSuperview().inset(5)
        }
        SpeakPracticeNormal.callblack = { [weak self] fw in
            if let call = self?.callblack{
                call(fw)
            }
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        self.layoutIfNeeded()
        back.shadow(cornerRadius: 16, shadowColor: .init(hex: 0x000000), offset: CGSize(width: 0, height: 2), opacity: 0.06, radius: 2)
    }
    
    @objc private func FlipTaps() -> Void {
        if wordDetail == nil && isShow == true {
            self.netwokng()
        }else if wordDetail == nil {
            self.netTranslate()
            self.HideDescp()
        }
        UIView.transition(
            from: isShowingFront ? SpeakPracticeNormal : SpeakPracticeBack,
            to: isShowingFront ? SpeakPracticeBack : SpeakPracticeNormal,
            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") )
            }
        )
    }
    
    private lazy var back: SpeakPracticeBackView = {
        let b = SpeakPracticeBackView.xib()
        b.callblack = { [weak self] fw in
            if let call = self?.callblack {
                call(fw)
            }
        }
        SpeakPracticeBack.addSubview(b)
        return b
    }()
    
    deinit {
        callblack = nil
    }
}
