//
//  RolePhotoResultMultiPickView.swift

//
//  Created by Leon on 2025/9/19.
//
import Combine

class RolePhotoResultsPickView: CLContainer {
    var regenerateType: RolePhotoGenerateType = .album
    
    var backButton: EPIconTertiaryButton!
    var bottomButton: StyleButton!

    var layout = UICollectionViewFlowLayout()
    var cv: UICollectionView!

    var headView = RolePhotoResultMultiPickHeadView()
    var headHeight = 104.0 + 12.0

    var datas = [AIUserImageQuery]()
    
   // var selectImgUrls = [String]()
    @Published var selectImgs = [AIUserImageQuery]()
    
    private var cancellables = Set<AnyCancellable>()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        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)
            }
            v.isEnabled = false
            return v
        }()

        cv = {
            layout = UICollectionViewFlowLayout()
            let itemW = floor((UIScreen.width - 24 * 2 - 16) * 0.5)
            let itemH = itemW * 219 / 163.0
            layout.itemSize = CGSize(width: itemW, height: itemH)
            layout.minimumLineSpacing = 16
            layout.minimumInteritemSpacing = 16
            layout.sectionInset = UIEdgeInsets(top: 0, left: 24, bottom: 16, right: 24)

            let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
            v.backgroundColor = .clear
            v.showsHorizontalScrollIndicator = false
            v.showsVerticalScrollIndicator = false
            v.register(RolePhotoGenerateSetGridCell.self, forCellWithReuseIdentifier: "RolePhotoGridCell")
            v.register(UICollectionReusableView.self,
                        forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader,
                        withReuseIdentifier: "UICollectionReusableView")
            v.dataSource = self
            v.delegate = self
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight)
                make.bottom.equalTo(bottomButton.snp.top).offset(-16)
            }
            return v
        }()

        bottomButton.setTitle("Complete", for: .normal)
        headView.titleView.title = "Confirm the work"
    }
    
    private func setupEvent(){
        $selectImgs.sink {[weak self] imgs in
            self?.bottomButton.isEnabled = imgs.count > 0
        }.store(in: &cancellables)
    }

    // MARK: - 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()
    }
    
    func reloadCv(){
        cv.reloadData()
    }


    public func setupLastGenerateProcessStart() {
        headView.generateButton.isEnabled = false
    }

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

extension RolePhotoResultsPickView: 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: "RolePhotoGridCell", for: indexPath) as! RolePhotoGenerateSetGridCell
        cell.regenerateType = regenerateType
        cell.delegate = viewController() as? any RolePhotoGenerateSetGridCellDelegate
        let data = datas[indexPath.item]
        cell.config(data: data)
        
        let isSelected = selectImgs.contains(where: { $0 === data })
        cell.setupSelected(isSelected)
        
        cell.tapFullBrowseAction = { data, image in
            guard let url = data.imageUrl, !url.isEmpty else { return }

            var photoModels = [PhotoBrowserModel]()
            let model = PhotoBrowserModel()
            model.image = image
            model.sourceRect = cell.screenRect ?? .zero
            model.imageUrl = url
            photoModels.append(model)
            #warning("to do, change .normal")
            ImageBrowser.show(models: photoModels, index: 0, type: .normal)
        }
        
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let data = datas[indexPath.item]
        
        guard data.status == .completed else{
            return
        }
        
        switch regenerateType{
        case .album:
            if selectImgs.contains(where: { $0 === data }) {
                selectImgs.removeAll { $0 === data }
            } else {
                // ⚠️ 都改成单选
                selectImgs.removeAll()
                selectImgs.append(data)
            }
        case.figure:
            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()
            }

            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 RolePhotoResultMultiPickHeadView: UIView {
    var titleView: TitleView!

    var titleLabel: CLLabel!
    var generateButton: TextButton!

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

    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.top.equalTo(titleView.snp.bottom).offset(12)
                make.leading.equalToSuperview().offset(24)
            }
            return v
        }()

        generateButton = {
            let v = TextButton()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.centerY.equalTo(titleLabel)
                make.height.equalTo(40)
                make.bottom.equalToSuperview()
            }
            return v
        }()
        titleLabel.text = "Appearance"
        generateButton.text = "Regenerate"
    }
}
