//
//  RolePhotoUnlockWaySetController.swift

//
//  Created by Leon on 2025/7/26.
//

import UIKit
import Combine

fileprivate let minCoin = 2000
fileprivate let maxCoin = 9999900

/// 通用设置图片解锁价格 vc
class RolePhotoUnlockWaySetController: CLViewController<RolePhotoUnlockWaySetView> {
    
    // Option 1: From 个人AI相册大图浏览
    var browseModel: PhotoBrowserModel?
    // Option 2: From Album AI generated
    var albumGenerated: AIUserImageQuery?
    
    var priceUpdateAction: ((_ price: Int?) -> Void)?
    
    @Published var selectUnLockway: Int = 0
    @Published var price = 0
    
    // Config
    

    
    private var cancellables = Set<AnyCancellable>()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupViews()
        setupDats()
        setupEvents()
    }

    private func setupViews() {
        navigationView.alpha0Title = "Unlock Method"
        container.container.scrollView.delegate = self
    }

    private func setupDats() {
        restoreData()
    }
    
    private func restoreData(){
        if let photo = browseModel {
            price = photo.aiAlbum.unlockPrice
            if price > 0{
                selectUnLockway = 1
            }
        }
        else if let album = albumGenerated {
            price = album.unlockPrice ?? 0
            if price > 0 {
                selectUnLockway = 1
            }
        }else{
            assert(false)
        }

    }

    private func setupEvents() {
        $price.sink {[weak self] price in
            let coin = Coin(cents: price)
            self?.container.priceTextField.textfield.text = coin.formatted
//            self?.container.priceTextField.textfield.text = "\(String.thousandString(float: Double(price)/100.0))"
        }.store(in: &cancellables)
        
        $selectUnLockway.sink {[weak self] unlockway in
            guard let `self` = self else {
                return
            }
            if unlockway == 0{
                self.price = 0
                self.container.selectView.contentStr = "Free"
                self.container.priceTextField.isHidden = true
            }else{// 1
                let coin = Coin(input: self.container.priceTextField.textfield.text ?? "")
                if coin.cents > 0{
                    self.price = coin.cents
                }else{
                    self.price = minCoin
                }
                self.container.selectView.contentStr = "Paid"
                self.container.priceTextField.isHidden = false
            }
        }.store(in: &cancellables)
        
        container.selectView.selectBlock = {[weak self] in
            self?.presentPickUnlockWay()
        }
        
        container.priceTextField.textfield.textDidChanged = {[weak self] textfield in
            guard let self = self else{return}
            
            let coin = Coin(input: textfield.text)
            let cents = coin.cents
            if cents > maxCoin{
                textfield.text = Coin(cents: maxCoin).formatted
                self.price = maxCoin
            }
        }
        
        container.priceTextField.textfield.textDidEndEditing = {[weak self] textfield in
            guard let self = self else{return}
            
            let priceUsd = Int(textfield.text ?? "1") ?? 1
            self.price = priceUsd * 100
            if self.price < minCoin{
                textfield.text = Coin(cents: minCoin).formatted
                self.price = minCoin
            }
        }
        
        container.bottomButton.addTarget(self, action: #selector(tapBottomButton), for: .touchUpInside)
    }
    
    // MARK: Helper
    
    private func presentPickUnlockWay(){
        let vc = SelectCommonController()
        var models = [SelectCommonModel]()
        
        var selectModel : SelectCommonModel!
        do{
            let model = SelectCommonModel()
            model.name = "Free"
            model.objInfo = 0
            models.append(model)
            if(selectUnLockway == 0){
                selectModel = model
            }
        }
        do{
            let model = SelectCommonModel()
            model.name = "Paid"
            model.objInfo = 1
            models.append(model)
            if(selectUnLockway == 1){
                selectModel = model
            }
        }
        
        vc.datas = models
        
        vc.markSelected = [selectModel]
        
        presentNaviRootVc(vc: vc)
        vc.tapSingleAction = {[weak self] obj in
            dlog("select obj : \(obj)")
            if let model = obj as? SelectCommonModel {
                self?.selectUnLockway = model.objInfo as! Int
            }
        }
    }
    
    // MARK: - Action

    @objc private func tapBottomButton() {
        if let photo = browseModel{
            let albumId = photo.aiAlbum.albumId
            
            Hud.showIndicator()
            AIRoleProvider.request(.aiRolePhotoUnlockPriceSet(aiUid: photo.aiId, albumId: albumId, unlockPrice: price), modelType: Bool?.self) {[weak self] result in
                Hud.hideIndicator()
                switch result {
                case .success:
                    self?.priceUpdateAction?(self?.price)
                    NotificationCenter.post(name: .aiRoleAlbumPhotoInfoChanged)
                    self?.close()
                case .failure:
                    break
                }
            }
        }else if albumGenerated != nil{
            priceUpdateAction?(self.price)
            close()
        }
    }
}

extension RolePhotoUnlockWaySetController: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, titleLabel: navigationView.titleLabel)
    }
}

class RolePhotoUnlockWaySetView: UIView {
    var bottomButton: StyleButton!
    var container: LTScrollContainer!
    var titleView: TitleView!
    var selectView: CLSelectView!
    var priceTextField: TitleTextField!

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

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupViews() {
        bottomButton = {
            let v = StyleButton(type: .custom)
            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)
            }
            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
        }()

        selectView = {
            let v = CLSelectView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        priceTextField = {
            let v = TitleTextField()
            v.textfield.setupLeftCoinIconView()
            v.textfield.keyboardType = .numberPad
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }
            return v
        }()

        titleView.title = "Unlock Method"
        selectView.titleLabel.text = "Unlock Method"
        selectView.placeholder = "Unlock Method"
        priceTextField.titleLabel.text = "Unlock Price"
        let minCoinShow = Coin(cents: minCoin).formatted
        let maxCoinShow = Coin(cents: maxCoin).formatted
        priceTextField.placeholder = "\(minCoinShow)-\(maxCoinShow)"
        bottomButton.setTitle("Save", for: .normal)
    }
}
