//
//  VIPPrivilegesShowController.swift

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

import UIKit

class VIPPrivilegesShowController: CLBaseTableController {
    var headView: VIPPrivilegesHeadView!
    var bottomButton: StyleButton!
    
    var data: MemberDetailOutput?
    
    var privileges = [MemberPrivDict]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupViews()
        setupDatas()
        setupEvents()
    }

    private func setupViews() {
        let title = "Crushlevel VIP"
        navigationView.bgView.alpha = 0
        navigationView.alpha0Title = title
        view.bringSubviewToFront(navigationView)

        bottomButton = {
            let v = StyleButton()
            v.primary(size: .large)
            v.addTarget(self, action: #selector(tapBottomButton), for: .touchUpInside)
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(24)
                make.trailing.equalToSuperview().offset(-24)
                make.bottom.equalToSuperview().offset(-16 - UIWindow.safeAreaBottom * 0.5)
            }
            return v
        }()

        tableView.snp.remakeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalToSuperview()
            make.bottom.equalTo(bottomButton.snp.top).offset(-16)
        }

        tableView.register(VIPPrivilegesListCell.self, forCellReuseIdentifier: "VIPPrivilegesListCell")
        tableView.bounces = false
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 16 + UIWindow.safeAreaBottom, right: 0)
        headView = {
            let v = VIPPrivilegesHeadView(frame: CGRect(x: 0, y: 0, width: UIScreen.width, height: 124 + UIWindow.navBarTotalHeight))
            return v
        }()

        tableView.tableHeaderView = headView

        bottomButton.setTitle("Subscribe", for: .normal)
    }

    private func setupDatas() {
        loadVIPInfo()
        loadVIPTiers()
    }
    
    private func loadVIPInfo(){
        Hud.showIndicator()
        WalletProvider.request(.vipDetail, modelType: MemberDetailOutput.self) {[weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success(let model):
                self?.data = model
                self?.privileges = model?.memberPrivList ?? []
                self?.handleVIPInfoOutput(output: model)
                self?.tableView.reloadData()
            case .failure:
                break
            }
        }
    }
    
    private func handleVIPInfoOutput(output: MemberDetailOutput?){
        guard let vipInfo = output?.userMemberInfo else {
            return
        }
        
        guard  let memberType = vipInfo.memberType else{
            return
        }
        
        headView.config(info: vipInfo)
        
        if vipInfo.getVIPValid(), memberType == .vip{
            bottomButton.isHidden = true
            tableView.snp.remakeConstraints { make in
                make.leading.trailing.bottom.equalToSuperview()
                make.top.equalToSuperview()
            }
        }
    }
    
    private func loadVIPTiers(){
        CLPurchase.shared.loadVIPTiersProducts { products in
            
        }
    }

    private func setupEvents() {
        NotificationCenter.default.addObserver(self, selector: #selector(notifyVIPChanged(_:)), name: AppNotificationName.vipStateChange.notificationName, object: nil)
    }
    
    
    @objc private func notifyVIPChanged(_ noti: Notification){
        loadVIPInfo()
    }
    

    // MARK: - Action

    @objc private func tapBottomButton() {
        let sheet = VIPSubscribeSheet()
        sheet.show()
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return privileges.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "VIPPrivilegesListCell", for: indexPath) as! VIPPrivilegesListCell
        let data = privileges[indexPath.row]
        cell.config(data)
        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("didSelectRowAt \(indexPath.row)")
    }

    override func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, alphaViews: [navigationView.titleLabel, navigationView.bgView])
    }
}
