//
//  SpeakProfileMoreViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/29.
//

import UIKit

class SpeakProfileMoreViewCtr: SpeakEleBaseViewCtr {
    
    
    @IBOutlet weak var SpeakProfileTableView: UITableView!
    private let viewModel = SpeakEleQAViewModel()
    private let userViewModel = SpeakUserNetViewModel()
    
    var maxSelect:Int = 1
    
    private var state:SpeakTitleState = .Interest
    
    private var selectSet = NSMutableSet()
    
    init(state:SpeakTitleState) {
        self.state = state
        self.viewModel.fetchData()
        super.init(nibName: "SpeakProfileMoreViewCtr", bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if self.state == .TargetLanguage || self.state == .Target || self.state == .NativeLanguage{
            maxSelect = 1
        }else if self.state == .Interest {
            maxSelect = 4
        }
        self.title = self.state.rawValue
        self.view.backgroundColor = .init(hex: 0xF6F7F9)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.filter("")
    }

    override func setup() {
        SpeakProfileTableView.delegate = self
        SpeakProfileTableView.dataSource = self
        SpeakProfileTableView.sectionHeaderTopPadding = 0
        SpeakProfileTableView.rowHeight = 60
        SpeakProfileTableView.sectionFooterHeight = 55
        SpeakProfileTableView.register(UINib(nibName: SpeakProfileMoreTableViewCell.id, bundle: nil), forCellReuseIdentifier: SpeakProfileMoreTableViewCell.id)
        SpeakProfileTableView.showsVerticalScrollIndicator = false
        SpeakProfileTableView.showsHorizontalScrollIndicator = false
    }

    var dataSource:[String] {
        
        set{}
        get{
            if state == .TargetLanguage {
                var iap = ["🇬🇧 English"]
                if IAPViewModel.share.isSubscribed {
                    iap.append("🇪🇸 Español")
                }
                return iap
            }else if state == .NativeLanguage {
                return viewModel.SpeakLanguages
            }else if state == .Interest{
                return viewModel.SpeakHoby
            }else{
                return viewModel.studyTime
            }
        }
    }
    
    var data:[String] = []
    
    @IBAction func SpeakProfileSummit(_ sender: Any) {
        if selectSet.count > 0{
            if self.state == .TargetLanguage {
                if let i = selectSet.allObjects.first as? Int {
                    let en = data[safe:i] ?? "🇬🇧 English"
                    let ens = (en == "🇬🇧 English" ? "en" : "es")
                    userViewModel.update(param: ["targetLanguage":ens]) { su in
                        NotificationCenter.default.post(name: NSNotification.Name.ProfilesettingUpdateUI, object: nil)
                        SpeakElePublicManager.share.userInfo.targetLanguage = en
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }else if self.state == .NativeLanguage {
                if let i = selectSet.allObjects.first as? Int {
                    let en = data[safe:i] ?? ""
                    if SpeakElePublicManager.share.userInfo.nativeLanguage == en {
                        return
                    }
                    SpeakWordTranslateData.data.WordTranslate = [:]
                    userViewModel.update(param: ["nativeLanguage":en]) { su in
                        SpeakElePublicManager.share.userInfo.nativeLanguage = en
                        NotificationCenter.default.post(name: NSNotification.Name.ProfilesettingUpdateUI, object: nil)
                        self.navigationController?.popViewController(animated: true)
                    }
                }
            }else if self.state == .Interest {
                var sts = ""
                for i in self.selectSet.allObjects {
                    sts += (data[safe: (i as? Int ?? 0)] ?? "")
                }
                if sts.count > 0 {
                    SpeakElePublicManager.share.PublicData.MHobby = sts
                    NotificationCenter.default.post(name: NSNotification.Name.ProfilesettingUpdateUI, object: nil)
                    self.navigationController?.popViewController(animated: true)
                }
            }else if self.state == .Target {
                if let sub = self.selectSet.allObjects.first as? Int {
                    SpeakElePublicManager.share.PublicData.MStudytime = data[safe:sub] ?? ""
                    NotificationCenter.default.post(name: NSNotification.Name.ProfilesettingUpdateUI, object: nil)
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
}

extension SpeakProfileMoreViewCtr : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return data.count
    }
 
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SpeakProfileMoreTableViewCell.id, for: indexPath) as! SpeakProfileMoreTableViewCell
        cell.selectionStyle = .none
        cell.isBot = (indexPath.row == data.count - 1)
        cell.isTop = indexPath.row == 0
        cell.SpeakMoreProTitleL.text = data[indexPath.row]
        cell.SpeakMoreProState.isSelected = selectSet.contains(indexPath.row)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.maxSelect <= 1{
            selectSet.removeAllObjects()
        }
        if selectSet.contains(indexPath.row) {
            selectSet.remove(indexPath.row)
            tableView.reloadData()
        }else{
            if selectSet.count < maxSelect{
                selectSet.add(indexPath.row)
                tableView.reloadData()
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header =  UIView()
        let hv = SpeakSearchTextField.xib()
        hv.delegate = self
        header.addSubview(hv)
        hv.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().inset(12)
        }
        return header
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if state == .Interest || state == .NativeLanguage {
            return 64
        }
        return 0.01
    }
}

extension SpeakProfileMoreViewCtr : UITextFieldDelegate {
    
    private func filter(_ text:String) -> Void {
        if text.count > 0 {
            data = dataSource.filter({$0.contains(text)})
        }else{
            data = dataSource
        }
        self.SpeakProfileTableView.reloadData()
    }
    
    func textFieldDidChangeSelection(_ textField: UITextField) {
        self.filter(textField.text ?? "")
    }
    
}
