//
//  SpeakEleQAMoreViewCtr.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/16.
//

import UIKit

class SpeakEleQAMoreViewCtr: SpeakEleBaseViewCtr {
    
    private var items:[String] = []
    private var callblock:((String)->Void)?
    
    // MARK: - ib

    @IBOutlet weak var SpeakTitleL: UILabel!
    @IBOutlet weak var ContentV: UIView!
    @IBOutlet weak var SpeakInputBox: SpeakResizableTextView!
    @IBOutlet weak var SpeakMoreTableView: UITableView!
    private let viewModel = SpeakEleQAViewModel()
    
    var state:SpeakMessageType = .language
    
    init(items: [String] ,state:SpeakMessageType) {
        self.items = items
        self.state = state
        super.init(nibName: "SpeakEleQAMoreViewCtr", bundle:  nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .init(hex: 0x000000,alpha: 0.5)
        viewModel.fetchData()
        titleView.isHidden = true
    }
    
    override func setup() -> Void {
        SpeakMoreTableView.delegate = self
        SpeakMoreTableView.dataSource = self
        SpeakMoreTableView.sectionHeaderTopPadding = 0
        SpeakMoreTableView.rowHeight = 50
        SpeakMoreTableView.register(SpeakMoreTableViewCell.self, forCellReuseIdentifier: SpeakMoreTableViewCell.id)
        SpeakInputBox.onTextChanged = {[weak self] string in
            self?.filter()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if state == .language {
            SpeakInputBox.placeholder = "Enter the language"
            SpeakTitleL.text = "More Language"
        }
        if state == .language {
            items = viewModel.SpeakLanguages
        }else if state == .hobby{
            items = viewModel.SpeakHoby
        }
        filter()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        ContentV.cornerRect(radius: 16, [.topLeft,.topRight])
    }

    func show(_ complate:@escaping(String)->Void) -> Void {
        self.callblock = complate
        self.modalPresentationStyle = .overFullScreen
        SpWindow.rootViewController?.present(self, animated: true)
    }
    
    @IBAction func closeTaps(_ sender: Any) {
        self.dismiss(animated: true)
    }
    
    @IBAction func SpeakSearch(_ sender: Any) {
        
    }
    
    private func filter() -> Void {
        let search = SpeakInputBox.text ?? ""
        if search.count > 0 {
            filterItem = items.filter({$0.contains(search)})
        }else{
            filterItem = items
        }
    }
    
    var filterItem:[String] = [] {
        didSet{
            self.SpeakMoreTableView.reloadData()
        }
    }
}

extension SpeakEleQAMoreViewCtr : UITableViewDelegate, UITableViewDataSource {
    
    private func HigthigText(_ text:String) -> NSAttributedString {
        let searchText = self.SpeakInputBox.text ?? ""
        let attributedString = NSMutableAttributedString(string: text)
        if searchText.count > 0 {
            let color:UIColor = .init(hex: 0x3980F6)
            let searchRange = NSRange(text.startIndex..., in: text)
            do {
                let regex = try NSRegularExpression(pattern: searchText)
                regex.enumerateMatches(in: text, range: searchRange) { match, _, _ in
                    if let range = match?.range {
                        attributedString.addAttribute(.foregroundColor, value: color, range: range)
                    }
                }
            } catch {
                print("Error creating regex: \(error)")
            }
        }
        return attributedString
    }
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filterItem.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: SpeakMoreTableViewCell.id, for: indexPath) as! SpeakMoreTableViewCell
        cell.titleL.attributedText = HigthigText(filterItem[safe: indexPath.row] ?? "")
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let call = callblock else { return }
        let sts = filterItem[indexPath.row]
        self.dismiss(animated: true) {
            call(sts)
        }
    }
    
}

class SpeakMoreTableViewCell: UITableViewCell {
    
    static let id = "SpeakMoreTableViewCell"
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup() -> Void {
        titleL.snp.makeConstraints { make in
            make.left.right.bottom.top.equalToSuperview()
        }
    }
    
    lazy var titleL: UILabel = {
        let t = UILabel()
        t.textColor = .black
        t.font = UIFont.montserrat(.medium,size: 16)
        t.textAlignment = .center
        contentView.addSubview(t)
        return t
    }()
    
}
