//
//  SessionInputSuggestionsView.swift

//
//  Created by Leon on 2025/8/26.
//
import Combine

class SessionInputSuggestionsView: UIView {
    var bgView: UIView!
    
    var cv: UICollectionView!
    var layout = UICollectionViewFlowLayout()
    
    var indicator: IndicatorView!
    
    var pageControl: UIPageControl!

    @Published var strings: [String]?
    var datas: [[String]] = [[String]]()
    
    var tapItemWithAction: ((_ string: String, _ edit: Bool) -> Void)?
    
    // Flag
    var requestNewDatasNextTime = false
    
    private var cancellables = Set<AnyCancellable>()
    
    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() {
        backgroundColor = .c.csbn

        let height = 232.0
        
        bgView = {
            let v = UIView()
            v.backgroundColor = backgroundColor
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalToSuperview().offset(UIWindow.safeAreaBottom + 16)
            }
            return v
        }()
                
//        snp.makeConstraints { make in
//            make.height.equalTo(height)
//        }
        
        indicator = {
            let v = IndicatorView(color: .white)
            v.size = CGSize(width: 24, height: 24)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.center.equalToSuperview()
            }
            return v
        }()
        

        cv = {
            let width = UIScreen.width
            layout.scrollDirection = .vertical
            layout.itemSize = CGSize(width: width, height: height)
            layout.minimumLineSpacing = 0
            layout.minimumInteritemSpacing = 0
            layout.scrollDirection = .horizontal
            layout.sectionInset = .zero
            

            cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
            cv.backgroundColor = .clear
            cv.showsHorizontalScrollIndicator = false
            cv.delegate = self
            cv.dataSource = self
            cv.isPagingEnabled = true
            cv.contentInsetAdjustmentBehavior = .never
            cv.register(SessionInputSuggestionsPageCell.self, forCellWithReuseIdentifier: "SessionInputSuggestionsPageCell")
            addSubview(cv)
            cv.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom)
                make.height.equalTo(height)
            }
            return cv
        }()

        pageControl = {
            let v = UIPageControl()
            v.numberOfPages = 0
            v.currentPage = 0
            v.pageIndicatorTintColor = .white.withAlphaComponent(0.45)
            v.currentPageIndicatorTintColor = .white
            v.hidesForSinglePage = true
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(cv.snp.bottom).offset(8)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom - 8)
            }
            return v
        }()
    }

    private func setupData() {
    }

    private func setupEvent() {
        NotificationCenter.default.addObserver(self, selector: #selector(notifyChargeDone), name: AppNotificationName.chargeDonePushTradeId.notificationName, object: nil)
        
        $strings.sink {[weak self] suggestions in
            if (suggestions ?? []).count > 0{
                self?.indicator.isHidden = true
                self?.indicator.stopIndicator()
            }else{
                self?.indicator.isHidden = false
                self?.indicator.startIndicator()
            }
        }.store(in: &cancellables)
    }
    
    @objc private func notifyChargeDone(){
        hide()
    }

    public func show(id: Int) {
        isHidden = false
        
        if requestNewDatasNextTime || datas.count == 0{
            loadTextSuggestion(id: id)
        }else{
            // 延用旧的数据
            handleTextSuggestions(suggestions: strings)
        }
    }
    
    /// 带清空显示数据
    public func hide(){
        isHidden = true
    }

    func loadTextSuggestion(id: Int) {
        resetToEmpty()
        
        AICowProvider.request(.supChatContent(aiId: id), modelType: [String].self) { [weak self] result in
            switch result {
            case let .success(model):
                self?.strings = model
                self?.handleTextSuggestions(suggestions: model)
                self?.requestNewDatasNextTime = false
            case .failure:
                // 可能是余额不足
                self?.hide()
                break
            }
        }
    }
    
    private func handleTextSuggestions(suggestions:[String]?){
        datas.removeAll()
        
        if let strings = suggestions, !strings.isEmpty {
            // Calculate number of pages needed (9 items, 3 per page = 3 pages)
            let itemsPerPage = 3
            let pageCount = Int(ceil(Double(strings.count) / Double(itemsPerPage)))

            // Split strings into chunks of 3
            for i in 0 ..< pageCount {
                let startIndex = i * itemsPerPage
                let endIndex = min(startIndex + itemsPerPage, strings.count)
                let pageData = Array(strings[startIndex ..< endIndex])
                datas.append(pageData)
            }
        }
        cv.reloadData()
        pageControl.numberOfPages = datas.count
        pageControl.currentPage = 0
    }
    
    // MARK: - Helper
    
    private func resetToEmpty(){
        datas.removeAll()
        strings = []
        cv.reloadData()
        pageControl.currentPage = 0
        pageControl.numberOfPages = 0
    }
}

extension SessionInputSuggestionsView: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return datas.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SessionInputSuggestionsPageCell", for: indexPath) as! SessionInputSuggestionsPageCell
        let strings = datas[indexPath.item]
        cell.config(strings)
        cell.tapItemWithAction = { [weak self] string, edit in
            self?.tapItemWithAction?(string, edit)
        }
        return cell
    }
}

extension SessionInputSuggestionsView: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let page = Int(scrollView.contentOffset.x / UIScreen.width)
        pageControl.currentPage = page
    }
}

class SessionInputSuggestionsPageCell: UICollectionViewCell {
    var stackV: UIStackView!

    var item1: SessionInputSuggestionsItem!
    var item2: SessionInputSuggestionsItem!
    var item3: SessionInputSuggestionsItem!
    var coinUnlockItem: SessionInputCoinUnlockItem!

    var tapItemWithAction: ((_ string: String, _ edit: Bool) -> Void)?
    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() {
        stackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 16
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(16)
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
            }
            return v
        }()

        item1 = {
            let v = SessionInputSuggestionsItem()
            stackV.addArrangedSubview(v)
            return v
        }()

        item2 = {
            let v = SessionInputSuggestionsItem()
            stackV.addArrangedSubview(v)
            return v
        }()

        item3 = {
            let v = SessionInputSuggestionsItem()
            stackV.addArrangedSubview(v)
            v.isHidden = true
            return v
        }()

        coinUnlockItem = {
            let v = SessionInputCoinUnlockItem()
            stackV.addArrangedSubview(v)
            v.isHidden = true
            return v
        }()
    }

    func config(_ strings: [String]) {
        for perItem in stackV.arrangedSubviews {
            perItem.isHidden = true
        }

        for (index, per) in strings.enumerated() {
            if index == 0 {
                item1.isHidden = false
                item1.label.text = per
            } else if index == 1 {
                item2.isHidden = false
                item2.label.text = per
            } else if index == 2 {
                item3.isHidden = false
                item3.label.text = per
            }
        }
    }

    private func setupData() {
    }

    private func setupEvent() {
        item1.tapItemWithAction = { [weak self] string, edit in
            self?.tapItemWithAction?(string, edit)
        }
        item2.tapItemWithAction = { [weak self] string, edit in
            self?.tapItemWithAction?(string, edit)
        }
        item3.tapItemWithAction = { [weak self] string, edit in
            self?.tapItemWithAction?(string, edit)
        }
    }
}

class SessionInputSuggestionsItem: UIView {
    var editButton: EPIconGhostButton!
    var label: CLLabel!
    var topButton: UIButton!

    var tapItemWithAction: ((_ string: String, _ edit: Bool) -> Void)?

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupViews() {
        backgroundColor = .c.cseln
        cornerRadius = 12
        snp.makeConstraints { make in
            make.height.equalTo(48)
        }

        editButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .iconOrderRemark)
            v.addTarget(self, action: #selector(tapEditButton), for: .touchUpInside)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
                make.trailing.equalToSuperview().offset(-8)
                make.centerY.equalToSuperview()
            }
            return v
        }()

        label = {
            let v = CLLabel()
            v.font = .t.tbl
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalTo(editButton.snp.leading).offset(-8)
            }
            return v
        }()

        topButton = {
            let v = UIButton()
            v.addTarget(self, action: #selector(tapTopButton), for: .touchUpInside)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.bottom.equalToSuperview()
                make.leading.equalToSuperview()
                make.trailing.equalTo(label)
            }
            return v
        }()
    }

    @objc private func tapTopButton() {
        tapItemWithAction?(label.text ?? "", false)
    }

    @objc private func tapEditButton() {
        tapItemWithAction?(label.text ?? "", true)
    }
}

class SessionInputCoinUnlockItem: UIView {
    var gradientView: GradientView!
    var label: UILabel!
    var topButton: UIButton!
    override init(frame: CGRect) {
        super.init(frame: frame)

        gradientView = {
            let gradient = CLSystemToken.gradient(token: .ccvn)
            let v = GradientView(colors: gradient.colors(), gradientType: .leftToRight)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()

        label = {
            let v = UILabel()
            v.textAlignment = .center
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(8)
                make.trailing.equalToSuperview().offset(-8)
            }
            return v
        }()

        topButton = {
            let v = UIButton()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.bottom.equalToSuperview()
                make.leading.equalToSuperview()
                make.trailing.equalTo(label)
            }
            return v
        }()

        let aStr = NSAttributedString.getIconTitleAttributeByWords(words: "Heart member unlock", icon: .iconVip)
        label.attributedText = aStr
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
