//
//  ChatBackgroundResultGridView.swift

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

import UIKit
import Combine
class ChatBackgroundResultGridView: CLContainer {
    var headView: ChatBackgroundGenerateGridHeadView!
    var layout = UICollectionViewFlowLayout()
    var cv: UICollectionView!

    var backButton: EPIconTertiaryButton!
    var bottomButton: StyleButton!
    // var titleView: TitleView!
    var headHeight: CGFloat = 104
    
    var datas: [AIUserImageQuery] = []
    
//    @Published var selectImgUrl: String?
    @Published var selectImgs = [AIUserImageQuery]()
    
    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() {
        backButton = {
            let v = EPIconTertiaryButton(radius: .round, iconSize: .large, iconCode: .arrowLeftBorder)
            let size = v.bgImageSize()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
                make.size.equalTo(CGSize(width: 88, height: size.height))
            }
            return v
        }()

        bottomButton = {
            let v = StyleButton(type: .custom)
            v.primary(size: .large)
            addSubview(v)
            v.snp.makeConstraints { make in
                // make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.leading.equalTo(backButton.snp.trailing).offset(16)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
            }
            return v
        }()

        cv = {
            let width = floor((UIScreen.width - 24 * 2 - 16) * 0.5)
            let height = floor(width * 219.0 / 164.0)
            layout.scrollDirection = .vertical
            layout.itemSize = CGSize(width: width, height: height)
            layout.minimumLineSpacing = 16
            layout.minimumInteritemSpacing = 16
            layout.sectionInset = UIEdgeInsets(top: 12, left: 24, bottom: UIWindow.safeAreaBottom, right: 24)

            cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
            cv.backgroundColor = .clear
            cv.showsHorizontalScrollIndicator = false
            cv.delegate = self
            cv.dataSource = self
            cv.contentInsetAdjustmentBehavior = .never
            cv.register(ChatBackgroundResultGridCell.self, forCellWithReuseIdentifier: "ChatBackgroundGenerateGridCell")
            cv.register(UICollectionReusableView.self,
                        forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                        withReuseIdentifier: "UICollectionReusableView")
            addSubview(cv)
            cv.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight)
                make.bottom.equalTo(bottomButton.snp.top).offset(-16)
            }
            return cv
        }()
        
        headView = {
            let v = ChatBackgroundGenerateGridHeadView()
            return v
        }()
        
        //titleView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: titleView.preCalculateHeight())
        bottomButton.setTitle("Confirm", for: .normal)
    }

    private func setupData() {
    }

    private func setupEvent() {
        $selectImgs.sink {[weak self] imgs in
            self?.bottomButton.isEnabled = imgs.count > 0
        }.store(in: &cancellables)
    }
    
    // MARK: Public
    public func config(_ datas: [AIUserImageQuery]?) {
        let validDatas = datas ?? []
        if validDatas.count >= 1{
            self.datas = validDatas
        }else{
            self.datas.removeAll(where: {$0.status != .completed})
            // 如果datas的数量不够6个，补齐datas的数量为6个，补充AIUserImageQuery()
            if self.datas.count < 6{
                for _ in 0...5 - self.datas.count {
                    self.datas.append(AIUserImageQuery())
                }
            }
        }
        
        // Reselect
        var tempSelectImages = [AIUserImageQuery]()
        for perNew in validDatas {
            for selectImg in selectImgs {
                if selectImg.imageUrl == perNew.imageUrl{
                    tempSelectImages.append(perNew)
                }
            }
        }
        selectImgs = tempSelectImages
        
        cv.reloadData()
    }
    
    public func setupLastGenerateProcessStart() {
        headView.generateButton.isEnabled = false
    }

    public func setupLastGenerateProcessEnd() {
        headView.generateButton.isEnabled = true
    }

}

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ChatBackgroundGenerateGridCell", for: indexPath) as! ChatBackgroundResultGridCell
        let data = datas[indexPath.item]
        cell.config(data: data)
        
        let isSelected = selectImgs.contains(where: { $0 === data })
        cell.setupSelected(isSelected)
        
        cell.tapFullBrowseAction = {[weak self] data, image in
            guard let self = self else{return}
            guard let url = data.imageUrl, !url.isEmpty else { return }

            var photoModels = [PhotoBrowserModel]()
            
            var startIndex = 0
            for (index, per) in self.datas.enumerated() {
                let model = PhotoBrowserModel()
                model.image = image
                model.sourceRect = cell.screenRect ?? .zero
                model.imageUrl = per.imageUrl
                if let imageUrl = per.imageUrl, imageUrl == url{
                    startIndex = index
                }
                photoModels.append(model)
            }
            
            ImageBrowser.show(models: photoModels, index: startIndex, type: .chatBackgroundGeneratedSelect)
        }

        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let data = datas[indexPath.item]
        
        guard data.status == .completed else{
            return
        }
        
        if selectImgs.contains(where: { $0 === data }) {
            selectImgs.removeAll { $0 === data }
        } else {
            // 加这行表示单选, 不加表示多选⚠️
            selectImgs.removeAll()
            selectImgs.append(data)
        }
        collectionView.reloadData()
        selectImgs = selectImgs
    }

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let header = collectionView.dequeueReusableSupplementaryView(
                ofKind: kind,
                withReuseIdentifier: "UICollectionReusableView",
                for: indexPath
            )
            if headView.superview == nil || headView.superview != header {
                headView.removeFromSuperview()
            }

            header.addSubview(headView)
            headView.snp.makeConstraints { make in
                make.top.leading.trailing.equalToSuperview()
                // make.bottom.equalToSuperview()
            }

            return header
        }
        return UICollectionReusableView()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: UIScreen.width, height: headHeight)
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, alphaViews: [navigationView?.titleLabel])
    }
}

class ChatBackgroundGenerateGridHeadView: UIView {
    var titleView: TitleView!
    var titleLabel: CLLabel!
    var generateButton: TextButton!
    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() {
        titleView = {
            let v = TitleView()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview()
            }
            return v
        }()
        
        titleLabel = {
            let v = CLLabel()
            v.font = .t.tlm
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(24)
                make.top.equalTo(titleView.snp.bottom).offset(12)
                make.bottom.equalToSuperview().offset(-12)
            }
            return v
        }()
        
        generateButton = {
            let v = TextButton()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-24)
                make.centerY.equalTo(titleLabel)
            }
            return v
        }()
        
        titleLabel.text = "Appearance"
        titleView.title = "Confirm the work"
        generateButton.setTitle("Regenerate", for: .normal)
    }

    private func setupData() {
    }

    private func setupEvent() {
    }
}

