//
//  HeartBeatLevelGridController.swift

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

import UIKit

class HeartBeatLevelGridController: CLViewController<HeartBeatLevelGridView> {
    var aiId: Int = 0
    
    var relation: AIUserHeartBeatRelation?
    var heartBeatLevelAccessDicts: [HeartbeatLeveLDict] = [HeartbeatLeveLDict]()
    
    
    lazy var popover = PopoverHideRalationView()
    override func viewDidLoad() {
        super.viewDidLoad()

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

    private func setupViews() {
        //navigationView.alpha0Title = "Crush Level"
        navigationView.title = "Crush Level"
        navigationView.bgView.alpha = 0
        let queryButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .faq)
            v.addTarget(self, action: #selector(queryAction), for: .touchUpInside)
            navigationView.rightStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 44, height: 44))
            }
            return v
        }()

        let moreButton = {
            let v = EPIconGhostButton(radius: .none, iconSize: .medium, iconCode: .more)
            v.addTarget(self, action: #selector(moreAction(sender:)), for: .touchUpInside)
            navigationView.rightStackH.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.size.equalTo(CGSize(width: 44, height: 44))
            }
            return v
        }()
        queryButton.isHidden = false
        moreButton.isHidden = false
    }

    private func setupDatas() {
        loadHeartBeatLevel()
    }
    
    private func loadHeartBeatLevel(){
        Hud.showIndicator()
        AIRoleProvider.request(.heartBeatLevelGet(aiId: aiId), modelType: HeartBeatLevelRelation.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let model):
                self?.heartBeatLevelAccessDicts = model?.heartbeatLeveLDictList ?? []
                self?.relation = model?.aiUserHeartbeatRelation
                self?.reloadViewDatas()
            case .failure:
                break
            }
        }
    }

    private func setupEvents() {
        container.headView.retrieveButton.addTarget(self, action: #selector(tapRetrieveButton), for: .touchUpInside)
        popover.controlSwitch.addTarget(self, action: #selector(tapPopoverControlSwitch), for: .valueChanged)
        NotificationCenter.default.addObserver(self, selector: #selector(notifiyRelationInfoUpdate), name: AppNotificationName.aiRoleRelationInfoUpdated.notificationName, object: nil)
    }
    
    @objc func notifiyRelationInfoUpdate(){
        loadHeartBeatLevel()
    }
    
    // MARK: Functions
    private func reloadViewDatas(){
        container.headView.config(relation)
        container.config(heartBeatLevelAccessDicts)
        
        popover.controlSwitch.isOn = !(relation?.isShow ?? false)
        //..
    }

    // MARK: Action

    @objc private func queryAction() {
        let content = "*通过聊天或送礼增加心动值，24小时不联系心动值会自动扣减\n\n*心动值会提升心动等级，通过升级解锁称号，功能，以及不同的角色对话阶段\n\n *虚拟角色会根据对话的情绪感受，酌情判断增加或者减少心动值"
        let alert  = Alert(title: "Tips", text: content)
        let action1 = AlertAction(title: "Got it", actionStyle: .confirm)
        alert.addAction(action1)
        alert.show()
    }

    @objc private func moreAction(sender: UIButton) {
        let popover = p_createPopoverView()
        popover.present(fromView: sender)
    }
    
    @objc private func tapRetrieveButton(){
        let sheet = RetrieveHeartbeatSheet()
        sheet.aiId = aiId
        sheet.config(self.relation)
        sheet.show()
    }

    @objc private func tapPopoverControlSwitch(sender: UISwitch) {
        let onOfSwitch = !sender.isOn
        //dlog("on\(onOfSwitch)")
        Hud.showIndicator()
        AIRoleProvider.request(.heartBeatRelationSwitch(aiId: aiId, isShow: onOfSwitch), modelType: EmptyModel.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                self?.loadHeartBeatLevel() // Refresh
                NotificationCenter.post(name: .heartbeatRelationHiddenUpdate)
            case .failure:
                sender.isOn = !onOfSwitch
                break
            }
        }
    }

    private func p_createPopoverView() -> FSPopoverView {
        let popoverView = FSPopoverView()
        popoverView.dataSource = self
        popoverView.showsArrow = false
        popoverView.showsDimBackground = false
        return popoverView
    }
}

extension HeartBeatLevelGridController: FSPopoverViewDataSource {
    func contentView(for popoverView: FSPopoverView) -> UIView? {
        return popover
    }

    func contentSize(for popoverView: FSPopoverView) -> CGSize {
        // return CGSize(width: 100, height: 60)
        let calSize = popover.label.sizeThatFits(CGSize(width: CGFLOAT_MAX, height: 20))
        let size = CGSize(width: calSize.width + 16 + 84, height: 60)
        dlog("hoee： \(size)")
        return size
    }

    func containerSafeAreaInsets(for popoverView: FSPopoverView) -> UIEdgeInsets {
        var insets = view.safeAreaInsets
        insets.left = 10.0
        insets.right = 10.0
        return insets
    }
}

class PopoverHideRalationView: UIView {
    var controlSwitch: UISwitch!
    var label: UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

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

    private func setupViews() {
        snp.makeConstraints { make in
            make.height.equalTo(60)
        }
        controlSwitch = {
            let v = UISwitch()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-16)
                make.centerY.equalToSuperview()
            }
            return v
        }()

        label = {
            let v = UILabel()
            v.font = .t.tll
            v.textColor = .text
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalTo(controlSwitch.snp.leading).offset(-16)
            }
            return v
        }()
        
        label.text = "Hide Relations"
    }
}
