//
//  FriendMainSearchView.swift

//
//  Created by Leon on 2025/8/15.
//

import UIKit
import JXSegmentedView
import JXPagingView

class FriendMainSearchView: UIView{
    var naviContainer: UIView!
    var cancelButton: TextButton!
    var searchField: CLTextField!
    
    private let segmentedViewHeight = 48

    private lazy var segmentedView = JXSegmentedView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: CGFloat(segmentedViewHeight)))
    private lazy var listContainerView = JXSegmentedListContainerView(dataSource: self)

    private let dataSource = JXSegmentedTitleDataSource()
    private let titles = ["Message", "Friends"]
    
    lazy var messageListVc = ChatSearchListController()
    lazy var friendsListVc = FriendSearchListController()
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        naviContainer = {
            let v = UIView()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.height.equalTo(44)
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(UIWindow.statusBarHeight)
            }
            addSubview(v)
            return v
        }()
        
        cancelButton = {
            let v = TextButton()
            v.text = "Cancel"
            naviContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.trailing.equalToSuperview().offset(-24)
            }
            return v
        }()
        
        searchField = {
            let v = CLTextField()
            v.switchToNaviSearchField()
            v.limit.maxCharacterNumber = 50
            v.placeholder = "Search"
            naviContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalTo(cancelButton.snp.leading).offset(-24)
                make.leading.equalToSuperview().offset(24)
                make.centerY.equalToSuperview()
            }
            return v
        }()
     
        setupJXViews()
    }
    
    private func setupJXViews(){
        dataSource.searchListMainStyle()
        dataSource.titles = titles

        segmentedView.searchListMainStyle()
        segmentedView.dataSource = dataSource
        segmentedView.delegate = self

        addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.height.equalTo(segmentedViewHeight)
            make.leading.equalToSuperview()
            //make.bottom.equalToSuperview()
            make.top.equalTo(naviContainer.snp.bottom).offset(8)
            make.trailing.equalToSuperview()
        }

        listContainerView.contentScrollView().isScrollEnabled = false
        addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom).offset(8)
        }

        segmentedView.listContainer = listContainerView
    }
    
    private func setupData(){
        
    }
    
    private func setupEvent(){
        // 添加搜索文本变化监听
        searchField.addTarget(self, action: #selector(searchTextChanged), for: .editingChanged)
        
        // 添加搜索按钮点击监听
        searchField.addTarget(self, action: #selector(searchButtonTapped), for: .editingDidEndOnExit)
    }
    
    @objc private func searchTextChanged() {
        guard searchField.text != nil else { return }
        
        // 实时搜索，延迟执行以避免频繁请求
        NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(performSearch), object: nil)
        perform(#selector(performSearch), with: nil, afterDelay: 0.5)
    }
    
    @objc private func searchButtonTapped() {
        searchField.resignFirstResponder()
        performSearch()
    }
    
    @objc private func performSearch() {
        guard let searchText = searchField.text else { return }
        
//        messageListVc.performSearch(with: searchText)
//        friendsListVc.performSearch(with: searchText)
        

        // 根据当前选中的标签页执行相应的搜索
        let currentIndex = segmentedView.selectedIndex
        if currentIndex == 0 { // Message 标签页
            messageListVc.performSearch(with: searchText)
        } else if currentIndex == 1 { // Friends 标签页
            friendsListVc.performSearch(with: searchText)
        }
    }
}

extension FriendMainSearchView: JXSegmentedListContainerViewDataSource, JXSegmentedViewDelegate{
    
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        guard let searchText = searchField.text else { return }
        if index == 0 { // Message 标签页
            messageListVc.performSearch(with: searchText)
        } else if index == 1 { // Friends 标签页
            friendsListVc.performSearch(with: searchText)
        }
    }
    
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        return titles.count
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        if index == 0 {
            if let searchText = searchField.text{
                messageListVc.performSearch(with: searchText)
            }
            return messageListVc
        } else {
            if let searchText = searchField.text{
                friendsListVc.performSearch(with: searchText)
            }
            return friendsListVc
        }
    }
    
    
} 
