//
//  ChatBackgroundGridView.swift

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

import UIKit
import Combine

class ChatBackgroundGridView: CLContainer {
    var bottomButton: StyleButton!
    var cv: UICollectionView!
    var layout = UICollectionViewFlowLayout()
    //var titleView: TitleView!
    var headView: ChatBackgroundGridHeadView!
    var headHeight: CGFloat = 168
    
    var aiId : Int?
    var inUseUrl: String?
    var datas: [IMChatBackground] = [IMChatBackground]()
    @Published var selectBgUrl: String?
    var selectBgModel: IMChatBackground?
    
    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() {
        bottomButton = {
            let v = StyleButton()
            v.primary(size: .large)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
                make.bottom.equalToSuperview().offset(-UIWindow.safeAreaBottom * 0.5 - 16)
            }
            v.isEnabled = false
            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(ChatBackgroundGridCell.self, forCellWithReuseIdentifier: "ChatBackgroundGridCell")
            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 = ChatBackgroundGridHeadView()
            return v
        }()
        bottomButton.setTitle("Set background", for: .normal)
    }

    private func setupData() {
    }

    private func setupEvent() {
        $selectBgUrl.sink {[weak self] str in
            self?.cv.reloadData()
            self?.refreshButtonState(selectImageUrl: str)
        }.store(in: &cancellables)
    }
    
    func config(_ datas: [IMChatBackground]?, selectBgUrl: String?){
        self.datas = datas ?? []
        inUseUrl = selectBgUrl
        self.selectBgUrl = selectBgUrl
        
        if let models = datas, let selectUrl = selectBgUrl{
            for per in models {
                if selectUrl == per.imgUrl!{
                    selectBgModel = per
                }
            }
        }
        
        cv.reloadData()
    }
    
    // MARK: - Helper
    
    func refreshButtonState(selectImageUrl: String?){
        
        guard let inUse = inUseUrl, let select = selectImageUrl else{
            bottomButton.isEnabled = false
            return
        }
        
        bottomButton.isEnabled = inUse != select
//        if let str = selectImageUrl, str.count > 0, datas.count > 0{ // 已选中的，按钮置灰
//            bottomButton.isEnabled = true
//        }else{
//            bottomButton.isEnabled = false
//        }
    }
}

extension ChatBackgroundGridView: 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: "ChatBackgroundGridCell", for: indexPath) as! ChatBackgroundGridCell
        let data = datas[indexPath.item]
        cell.config(data)
        //cell.configInUse(inUseUrl: inUseUrl)
        cell.configSelectUrl(selectBgUrl)
        
        cell.tapFullBrowseAction = {[weak self] data, image in
            guard let self = self else{return}
            guard let url = data.imgUrl, !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.imgUrl
                model.aiId = self.aiId
                model.chatBackground = per
                if let imageUrl = per.imgUrl, imageUrl == url{
                    startIndex = index
                }
                photoModels.append(model)
            }
            
            ImageBrowser.show(models: photoModels, index: startIndex, type: .chatBackgroundSet)
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let data = datas[indexPath.item]
        selectBgUrl = data.imgUrl
        selectBgModel = data
    }

    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 ChatBackgroundGridHeadView : UIView{
    var titleView: TitleView!
    var creatorEntrance : UIView!
    
    var operateButton: StyleButton!
    var stackV: UIStackView!
    var titleLabel : UILabel!
    var subTitleLabel:UILabel!
    
    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()
            v.title = "Chat Background"
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.top.equalToSuperview()
            }
            return v
        }()
        
        creatorEntrance = {
            let v = UIView()
            v.backgroundColor = .c.csen
            v.cornerRadius = 16
            addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalTo(titleView.snp.bottom).offset(12)
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
                make.height.equalTo(80)
                make.bottom.equalToSuperview()
            }
            return v
        }()
        
        operateButton = {
            let v = StyleButton()
            v.primary(size: .small)
            creatorEntrance.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.trailing.equalToSuperview().offset(-16)
            }
            return v
        }()
        
        stackV = {
            let v = UIStackView()
            v.axis = .vertical
            v.spacing = 4
            v.alignment = .leading
            creatorEntrance.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.trailing.lessThanOrEqualTo(operateButton.snp.leading).offset(-8)
                make.centerY.equalToSuperview()
            }
            return v
        }()
        
        titleLabel = {
            let v = UILabel()
            v.font = .t.tts
            v.textColor = .text
            stackV.addArrangedSubview(v)
            return v
        }()
        
        subTitleLabel = {
            let v = UILabel()
            v.font = .t.tbs
            v.textColor = .c.ctsn
            stackV.addArrangedSubview(v)
            return v
        }()
        
        titleLabel.text = "Create image"
        
        //setupCreateMode(create: true)
    }
    
    private func setupData(){
        // Default
        setupCreateMode(create: false)
    }
    
    private func setupEvent(){
        
    }
    
    // MARK: - Public
    func setupCreateMode(create:Bool){
        if create{
            subTitleLabel.text = "Unlocked"
            operateButton.setTitle("Create", for: .normal)
        }else{
            subTitleLabel.text = "Heartbeat Lv.10 unlock"
            operateButton.setTitle("Unlock", for: .normal)
        }
    }
}

class ChatBackgroundGridCell: UICollectionViewCell {
    var block: UIView!
    var imageView: UIImageView!
    var defaultTag:EPTagLabel!
    var viewFullButon : EPIconTertiaryDarkButton!
    var inUseIcon : UIImageView!

    var tapFullBrowseAction: ((_ data: IMChatBackground, _ image: UIImage?) -> Void)?
    
    var data: IMChatBackground?
    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() {
        block = {
            let v = UIView()
            v.cornerRadius = 16
            v.backgroundColor = .c.csbn
            v.layer.borderColor = UIColor.c.cpn.cgColor
            contentView.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()

        imageView = {
            let v = UIImageView()
            v.contentMode = .scaleAspectFill
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
        
        viewFullButon = {
            let v = EPIconTertiaryDarkButton(radius: .round, iconSize: .small, iconCode: .iconFullimage)
            v.addTarget(self, action: #selector(tapViewFullButton), for: .touchUpInside)
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(v.bgImageSize())
                make.trailing.equalToSuperview().offset(-12)
                make.bottom.equalToSuperview().offset(-12)
            }
            return v
        }()
        
        defaultTag = {
            let v = EPTagLabel(style: .blackOnColor)
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(8)
                make.top.equalToSuperview().offset(8)
            }
            v.isHidden = true
            return v
        }()
        
        inUseIcon = {
            let v = UIImageView()
            v.image = UIImage(named: "checkmark_tick")
            block.addSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 20, height: 20))
                make.top.equalToSuperview().offset(10)
                make.trailing.equalToSuperview().offset(-8)
            }
            v.isHidden = true
            return v
        }()
        
        defaultTag.text = "Default"
    }

    private func setupData() {
    }

    private func setupEvent() {
    }

    // MARK: - Public
    func config(_ data: IMChatBackground?){
        self.data = data
        guard let theData = data else{return}
        
        defaultTag.isHidden = !theData.isDefault.boolValue
        imageView.loadImage(theData.imgUrl)
        
        self .configInused(selected: data?.isSelected ?? false)
    }
    
    func configInUse(inUseUrl:String?){
//        guard let theDataCode = data?.imgUrl, let theUsedCode = inUseUrl, theUsedCode == theDataCode else{
//            inUseIcon.isHidden = true
//            return
//        }
//        inUseIcon.isHidden = false
    }
    
    func configInused(selected: Bool){
        inUseIcon.isHidden = !selected
    }
    
    func configSelectUrl(_ url: String?){
        if let theUrl = url, let dataUrl = data?.imgUrl, theUrl == dataUrl {
            setupSelected(selected: true)
        }else{
            setupSelected(selected: false)
        }
    }
    
    // MARK: - Helper
    
    private func setupSelected(selected: Bool) {
        block.layer.borderWidth = selected ? 2 : 0
    }
    
    // MARK: - Action
    
    @objc private func tapViewFullButton(){
        guard imageView.image != nil else{
            return
        }
        tapFullBrowseAction?(data!, imageView.image)
    }
}
