//
//  RolePublishView.swift

//
//  Created by Leon on 2025/7/21.
//
import Combine
import Lottie
import UIKit
class RolePublishView: UIView {
    var backButton: EPIconTertiaryButton!
    var bottomButton: StyleButton!
    var container: LTScrollContainer!
    var titleView: TitleView!
    var stepLabel: UILabel!

    // Option 1
    var uploadPicContainer: UIView!
    var uploadImageView: UploadImageView!

    // Option 2
    var appearanceResult: RoleCreateAppearanceResultView!
    var avatarView: RoleCreateAvatarView!

    var introduction: TitleTextView!
    var generate1Button: TextButton!

    var privacyPublicButton: EPChipAssistButton!
    var privacyPrivateButton: EPChipAssistButton!

    // Data
    @Published var buttonEnable: Bool = false
    
    @Published var privacyPublic: Bool = true
    @Published var introductionContent: String = ""
    @Published var contentAIGenerated: String = ""
    
    var tempAvatar: UploadPhotoM?
    @Published var avatarModel: UploadPhotoM?
    
    private var cancellables = Set<AnyCancellable>()

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

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - Views
    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
        }()
        container = {
            let v = LTScrollContainer()
            v.stack.spacing = 24
            v.stack.alignment = .leading
            addSubview(v)
            v.snp.makeConstraints { make in
                // make.top.equalTo(navigationView.snp.bottom)
                make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight)
                make.leading.trailing.equalToSuperview()
                make.bottom.equalTo(bottomButton.snp.top).offset(-16)
            }
            return v
        }()

        titleView = {
            let v = TitleView()
            v.optionInnerBottomPadding = 0
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
            }
            return v
        }()

        stepLabel = {
            let v = UILabel()
            v.font = CLSystemToken.font(token: .tlm)
            v.textColor = .c.ctsn
            v.text = "4/4"
            titleView.addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalTo(titleView.titleLabel)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        // Option1
        setupAppearance()
        // Option 2
        setupAppearanceResult()

        setupAvatar()
        
        introduction = {
            let v = TitleTextView()
            // 10~300
            v.maxLimit = 300
            v.minLimit = 10
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        generate1Button = {
            let v = TextButton()
            v.text = "自动生成"
            introduction.addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview()
                make.centerY.equalTo(introduction.titleLabel)
                make.height.equalTo(40)
            }
            return v
        }()

        
        setupPrivacy()

        //itleView.title = "Create"
        introduction.titleLabel.text = "Introduction"
        introduction.placeholder = "为用户介绍该虚拟角色"
        introduction.errorMsg = "只能包含10-300字符"
        //bottomButton.setTitle("Create", for: .normal)
    }

    private func setupAppearance() {
        uploadPicContainer = {
            let v = UIView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        let titleLabel = {
            let v = UILabel()
            v.font = .t.tlm
            v.textColor = .c.ctpn
            uploadPicContainer.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.leading.equalToSuperview()
            }
            return v
        }()

        uploadImageView = {
            let v = UploadImageView()
            uploadPicContainer.addSubview(v)
            v.snp.makeConstraints { make in
                // w:h = 345:200
                make.height.equalTo(v.snp.width).multipliedBy(200.0 / 345.0)
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
                make.bottom.equalToSuperview()
            }
            return v
        }()

        titleLabel.text = "Appearance"
    }

    private func setupAppearanceResult() {
        appearanceResult = {
            let v = RoleCreateAppearanceResultView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.trailing.equalToSuperview()
            }
            return v
        }()
        appearanceResult.isHidden = true
    }

    private func setupAvatar() {
        avatarView = RoleCreateAvatarView()
        container.stack.addArrangedSubview(avatarView)
        avatarView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(CGFloat.lrs)
            make.trailing.equalToSuperview().offset(-CGFloat.lrs)
        }
        avatarView.isHidden = true
    }

    // MARK:  Privacy

    private func setupPrivacy() {
        let view = UIView()
        container.stack.addArrangedSubview(view)
        view.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(CGFloat.lrs)
            make.trailing.equalToSuperview().offset(-CGFloat.lrs)
        }

        let titleLabel = {
            let v = UILabel()
            v.font = .t.tlm
            v.textColor = .c.ctpn
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.leading.equalToSuperview()
            }
            return v
        }()

        privacyPublicButton = {
            let v = EPChipAssistButton()
            v.iconCode = .eyeOn
            v.text = "Public"
            v.defaultIconColor = .c.ctpn
            v.addTarget(self, action: #selector(tapPrivacyButton(sender:)), for: .touchUpInside)
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.bottom.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
            }
            return v
        }()

        privacyPrivateButton = {
            let v = EPChipAssistButton()
            v.iconCode = .eyeOff
            v.text = "Private"
            v.defaultIconColor = .c.ctpn
            v.addTarget(self, action: #selector(tapPrivacyButton(sender:)), for: .touchUpInside)
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalTo(privacyPublicButton.snp.trailing).offset(12)
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
            }
            return v
        }()

        titleLabel.text = "Privacy"
    }

    private func setupDatas(){
        // See more EGImageInputView
        uploadImageView.state = .default
    }

    private func setupEvent() {
        $buttonEnable.sink {[weak self] enable in
            self?.bottomButton.isEnabled = enable
        }.store(in: &cancellables)
        
        $privacyPublic.sink { [weak self] result in
            self?.privacyPublicButton.isSelected = result
            self?.privacyPrivateButton.isSelected = !result
        }.store(in: &cancellables)

        $introductionContent.sink {  [weak self] str in
            self?.introduction.defaultText = str
        }.store(in: &cancellables)
        
        $contentAIGenerated.sink { [weak self] str in
            self?.introductionContent = str
        }.store(in: &cancellables)

        appearanceResult.$selectImageUrl.sink { [weak self] result in
            self?.selectFigureImageUrl(imgUrl: result)
        }.store(in: &cancellables)
        
        $avatarModel.sink {[weak self] model in
            if let url = model?.remoteFullPath{
                self?.avatarView.bind(imageUrl: url)
            }
        }.store(in: &cancellables)
        
        avatarView.tapCropAction = {[weak self] image in
            self?.cropAIAvatar(image: image)
        }
        
        introduction.textView.textPublisher.sink {[weak self] string in
            self?.introductionContent = string.trimmed
        }.store(in: &cancellables)
//        introduction.textDidChanged = {[weak self] clTextView in
//            self?.introductionContent = clTextView.text.trimmed
//        }
        
        
    
        // 选择了形象图 & introduction ok
        Publishers.CombineLatest(appearanceResult.$selectImageUrl.prepend(""), $introductionContent.prepend("")).map{
            url, content in
            if url.count > 0, content.count >= 10{
                return true
            }
            return false
        }.assign(to: &$buttonEnable)

        
        
    }

    // MARK: - Public
    public func showQueryGeneratedImages(generating: Bool) {
        uploadPicContainer.isHidden = generating
        appearanceResult.isHidden = generating == false
    }
    
    public func loadDataAndSelect(_ image: AIUserImageQuery?){
        guard let select = image else {return}
        
        //selectFigureImageUrl(imgUrl: select.imageUrl)
        appearanceResult.loadDataAndSelect(select)
        
    }
    
    // MARK: - Helper
    func selectFigureImageUrl(imgUrl: String?){
        if let url = imgUrl{
            avatarView.isHidden = url.isEmpty
            avatarView.bind(imageUrl: url)
            
            let photo = UploadPhotoM()
            photo.setupValidImageUrl(url: url)
            avatarModel = photo
        }
    }
    
    private func cropAIAvatar(image:UIImage?){
        guard let avatar = image else {return}
        
        let image = avatar
        
//        let image = UIImage(named: "egpic")!
        let cropViewController = CropViewController(image: image) { [unowned self] croppedImage in
            self.avatarView.bindImage(image: croppedImage)
            
            // 裁剪后的图片
            let photo = UploadPhotoM()
            photo.image = croppedImage
            photo.addThisItemTimeStamp = Date().timeStamp
            avatarModel = photo
        }
        let navc = CLNavigationController(rootViewController: cropViewController)
        UIWindow.getTopViewController()?.present(navc, animated: true, completion: nil)
        
    }
    
    // MARK: - Action

    // Action
    @objc private func tapPrivacyButton(sender: UIButton) {
        privacyPublic = !privacyPublic
    }
}

class RoleCreateAvatarView: UIView {
    var titleLabel: UILabel!
    var cropButton: TextButton!
    var avatarIv: CLImageView!

    var image: UIImage?

    var tapCropAction: ((_ image: UIImage?) -> Void)?

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

    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()
            }
            return v
        }()

        cropButton = {
            let v = TextButton()
            v.addTarget(self, action: #selector(tapCropButton), for: .touchUpInside)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview()
                make.centerY.equalTo(titleLabel)
            }
            v.isEnabled = false
            return v
        }()

        avatarIv = {
            let v = CLImageView(frame: .zero)
            v.layer.cornerRadius = 32
            v.clipsToBounds = true
            v.contentMode = .scaleAspectFill
            v.backgroundColor = .c.csbn
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.size.equalTo(CGSize(width: 64, height: 64))
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
                make.bottom.equalToSuperview()
            }
            return v
        }()

        titleLabel.text = "Avatar"
        cropButton.text = "Crop"
    }

    /// 从url获取的完整形象图
    public func bind(imageUrl: String) {
        avatarIv.loadImage(imageUrl, completionBlock:  { [weak self] result in
            switch result {
            case let .success(imageResult):
                self?.image = imageResult.image
                self?.cropButton.isEnabled = true
            case .failure:
                return
            }
        })
    }

    public func bindImage(image: UIImage?) {
        avatarIv.image = image
        cropButton.isEnabled = true
    }
    
    @objc private func tapCropButton(){
        guard let fullFigure = image else{return}
        tapCropAction?(fullFigure)
    }
}
