//
//  RoleCreateAppearanceResultView.swift

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

import UIKit
import Combine
/// 形象生成结果页
class RoleCreateAppearanceResultView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
    var titleLabel: UILabel!
    var generateButton: TextButton!
    
    var stackV : UIStackView!
    var warningView : TipWarningView!
    var layout : UICollectionViewFlowLayout!
    var cv: UICollectionView!
    
//    var placeholderDatas
    /// 编辑时，之前使用中的图像
    @Published var usingFigureImage: AIUserImageQuery?
    
    var datas: [AIUserImageQuery] = []
    
    @Published var selectDatas: [AIUserImageQuery] = []
    @Published var selectImageUrl: String = ""
    
    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() {
        titleLabel = {
            let v = UILabel()
            v.font = .t.tlm
            v.textColor = .c.ctpn
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.leading.equalToSuperview().offset(CGFloat.lrs)
            }
            return v
        }()
        titleLabel.text = "Appearance Result"
        
        generateButton = {
            let v = TextButton()
            v.text = "Regenerate"
            addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.centerY.equalTo(titleLabel)
                make.height.equalTo(40)
            }
            return v
        }()
        
        stackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 12
            v.alignment = .leading
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
                make.leading.trailing.equalToSuperview()
                make.bottom.equalToSuperview()
            }
            return v
        }()
        
        warningView = {
            let v = TipWarningView()
            stackV.addArrangedSubview(v)
            v.contentStr = "Please wait patiently in the queue, 15 missions ahead"
            v.isHidden = false
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            v.isHidden = true
            return v
        }()
        
        cv = {
            layout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            layout.itemSize = CGSize(width: 150, height: 200)
            layout.minimumLineSpacing = 12
            layout.minimumInteritemSpacing = 12
            layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 12)
            
            let v = UICollectionView(frame: .zero, collectionViewLayout: layout)
            v.backgroundColor = .clear
            v.showsHorizontalScrollIndicator = false
            v.showsVerticalScrollIndicator = false
            v.register(RoleCreateAppearanceResultCell.self, forCellWithReuseIdentifier: "RoleCreateAppearanceResultCell")
            v.dataSource = self
            v.delegate = self
            v.contentInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)
            //addSubview(v)
            stackV.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.height.equalTo(200)
            }
            return v
        }()
    }
    
    private func setupData(){
        for _ in 0...5 {
            datas.append(AIUserImageQuery())
        }
        cv.reloadData()
    }
    
    private func setupEvent(){
        $usingFigureImage.sink {[weak self] imageQuery in
            
            if imageQuery != nil{
                self?.datas.removeAll()
                
                self?.layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 12)
                self?.cv.contentInset = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 12)
                
                self?.cv.reloadData()
            }
        }.store(in: &cancellables)
    }

    // MARK: - Public
    public func config(_ datas: [AIUserImageQuery]?, reset: Bool = false) {
        if let validDatas = datas, validDatas.count >= 1{
            self.datas = validDatas
        }else{
            // 填充占位数据，如果datas的数量不够6个，补齐datas的数量为6个，补充AIUserImageQuery()
            self.datas.removeAll(where: {$0.status != .completed})
            if self.datas.count < 6{
                for _ in 0...5 - self.datas.count {
                    self.datas.append(AIUserImageQuery())
                }
            }
        }
        
        if reset{
            selectDatas.removeAll()
            selectImageUrl = ""
        }
        
        cv.reloadData()
    }
    
    public func loadDataAndSelect(_ data: AIUserImageQuery?){
        guard let outImage = data else {return}
        
        datas = []
        usingFigureImage = outImage
        selectDatas = [outImage]
        selectImageUrl = outImage.imageUrl ?? ""
        
        cv.reloadData()
    }
    
    public func setupLastGenerateProcessStart(){
        generateButton.isEnabled = false
    }
    
    public func setupLastGenerateProcessEnd(){
        generateButton.isEnabled = true
    }

    // MARK: - UICollectionViewDataSource
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0{
            return usingFigureImage != nil ? 1 : 0
        }
        return datas.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var item: AIUserImageQuery!
        if indexPath.section == 0{
            item = usingFigureImage ?? AIUserImageQuery()
        }else{
            item = datas[indexPath.item]
        }
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RoleCreateAppearanceResultCell", for: indexPath) as! RoleCreateAppearanceResultCell
        
        cell.config(data: item)
        if let url = item.imageUrl, url == selectImageUrl {
            cell.setupSelected(true)
        } else {
            cell.setupSelected(false)
        }

        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)
            ImageBrowser.show(models: photoModels, index: 0, type: .normal)
        }

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var item: AIUserImageQuery!
        if indexPath.section == 0{
            guard let using = usingFigureImage else{
                return
            }
            item = using
        }else{
            item = datas[indexPath.item]
        }
        
        let status = item.status
        guard status == .completed, let url = item.imageUrl else { return }

        selectImageUrl = url
        selectDatas.removeAll()
        selectDatas.append(item)
        selectDatas = selectDatas
        collectionView.reloadData()
    }
}

