//
//  ChatSettingListView.swift

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

import UIKit

enum ChatSettingSection1 {
    case nickname
    case gender
    case age
    case whoIm
}

class ChatSettingListView: CLContainer {
    var tableView: UITableView!
    var titleView: TitleView!

    var config: ChatSettingCacheConfig!
    
    var data: IMChatSetting?
    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() {
        tableView = UITableView(frame: .zero, style: .plain)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.estimatedRowHeight = 72
        tableView.backgroundColor = .clear
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: UIWindow.safeAreaBottom + 16, right: 0)
        tableView.contentInsetAdjustmentBehavior = .never
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.register(ChatSettingChatPersonalCell.self, forCellReuseIdentifier: "ChatSettingChatPersonalCell")
        tableView.register(ChatSettingOtherCell.self, forCellReuseIdentifier: "ChatSettingOtherCell")
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.leading.trailing.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(UIWindow.navBarTotalHeight)
        }

        titleView = {
            let v = TitleView()
            v.title = "Setting"
            return v
        }()

        titleView.frame = CGRect(x: 0, y: 0, width: UIScreen.width, height: titleView.preCalculateHeight())
        tableView.tableHeaderView = titleView
    }

    private func setupData() {
        config = AppCache.fetchCache(key: CacheKey.chatRedBadgeConfig.rawValue, type: ChatSettingCacheConfig.self) ?? ChatSettingCacheConfig()
    }

    private func setupEvent() {
    }
    
    
    // MARK: - Public
    
    func config(_ data: IMChatSetting?){
        self.data = data
        tableView.reloadData()
    }
}

extension ChatSettingListView: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ChatSettingChatPersonalCell", for: indexPath) as! ChatSettingChatPersonalCell
            cell.config(data)
            cell.tapChatPersonAction = { [weak self] in
                let vc = ChatPersonalSettingController()
                vc.setting = self?.data
                self?.viewController()?.navigationController?.pushViewController(vc, animated: true)
            }
            return cell
        }

        let cell = tableView.dequeueReusableCell(withIdentifier: "ChatSettingOtherCell", for: indexPath) as! ChatSettingOtherCell
        cell.config(data)
        cell.chatModelItem.tapTopButtonAction = {[weak self] in
            self?.tapSelectChatModel()
        }
        
        config = AppCache.fetchCache(key: CacheKey.chatRedBadgeConfig.rawValue, type: ChatSettingCacheConfig.self) ?? ChatSettingCacheConfig()
        cell.chatBubble.badge.isHidden = config.chatBubbleTapped
        cell.chatBackground.badge.isHidden = config.chatBackgroundTapped
        
        cell.chatBubble.tapTopButtonAction = { [weak self] in
            guard let self = self, let aiId = data?.aiId else {return}
            let vc = ChatBubbleGridController()
            vc.aiId = aiId
            vc.selectChatBubbleCode = data?.bubbleCode
            vc.data = self.data
            let navc = CLNavigationController(rootViewController: vc)
            navc.modalPresentationStyle = .fullScreen
            self.viewController()?.present(navc, animated: true)
            
            if !self.config.chatBubbleTapped{
                self.config.chatBubbleTapped = true
                AppCache.cache(key: CacheKey.chatRedBadgeConfig.rawValue, value: config)
                self.tableView.reloadData()
                NotificationCenter.post(name: .chatNaviMoreRedDotChanged)
            }
        }
        
        cell.chatBackground.tapTopButtonAction = {[weak self] in
            guard let self = self, let aiId = data?.aiId else {return}
            let vc = ChatBackgroundGridController()
            vc.aiId = aiId
            vc.selectBgUrl = data?.backgroundImg
            let navc = CLNavigationController(rootViewController: vc)
            navc.modalPresentationStyle = .fullScreen
            self.viewController()?.present(navc, animated: true)
            
            if !self.config.chatBackgroundTapped{
                self.config.chatBackgroundTapped = true
                AppCache.cache(key: CacheKey.chatRedBadgeConfig.rawValue, value: config)
                self.tableView.reloadData()
                NotificationCenter.post(name: .chatNaviMoreRedDotChanged)
            }
        }
        return cell
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = ChatSettingSectionHeader()
        if section == 0 {
            view.label.text = "My Chat Persona"
        } else {
            view.label.text = "Chat Settings"
        }
        return view
    }

    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 56
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NaviAlphaHandle.changeNaviTitleAlpha(scrollView: scrollView, titleLabel: navigationView?.titleLabel)
    }
    
    // MARK: Action
    
    func tapSelectChatModel(){
        guard let chatModels = AppDictManager.shared.chatModels, chatModels.count > 0 else{
            Hud.showIndicator()
            AppDictManager.shared.loadChatModelDict { ok in
                Hud.hideIndicator()
            }
            return
        }
        
        let sheet = ChatModePickSheet(currentSelectedModelCode: data?.modelCode)
        sheet.selectionCallback = { [weak self] selectedModel in
            self?.updateChatModel(selectedModel)
        }
        sheet.show()
    }

    private func updateChatModel(_ model: AIChatModel) {
        guard let aiId = data?.aiId else { return }
        
        Hud.showIndicator()
        var params = [String: Any]()
        params.updateValue(aiId, forKey: "aiId")
        params.updateValue(model.code ?? "", forKey: "code")
        
        AIRoleProvider.request(.chatModelSetup(params: params), modelType: EmptyModel.self) { [weak self] result in
            Hud.hideIndicator()
            switch result {
            case .success:
                // 更新本地数据
                self?.data?.modelCode = model.code
                self?.data?.modelName = model.name
                self?.tableView.reloadData()
                // 发送通知更新其他页面
                NotificationCenter.post(name: .chatSettingUpdated)
            case .failure:
                break
            }
        }
    }
}

class ChatSettingChatPersonalCell: UITableViewCell {
    var stackV = UIStackView()

    var nicknameItem = ChatSettingItemView()
    var genderItem = ChatSettingItemView()
    var ageItem = ChatSettingItemView()
    var whoIm = ChatSettingItemView()

    var tapChatPersonAction: (() -> Void)?

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        selectionStyle = .none
        backgroundColor = .clear

        setupViews()
    }

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

    private func setupViews() {
        stackV.backgroundColor = .c.csbn
        stackV.axis = .vertical
        stackV.layer.cornerRadius = 12
        stackV.layer.masksToBounds = true
        contentView.addSubview(stackV)
        stackV.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 24, bottom: 16, right: 24))
        }

        nicknameItem.titleLabel.text = "Nickname"
        nicknameItem.contentLabel.text = ""

        genderItem.titleLabel.text = "Gender"
        genderItem.contentLabel.text = ""

        ageItem.titleLabel.text = "Age"
        ageItem.contentLabel.text = ""

        whoIm.title = "Who i am"
        whoIm.bottomLine.isHidden = true

        stackV.addArrangedSubview(nicknameItem)
        stackV.addArrangedSubview(genderItem)
        stackV.addArrangedSubview(ageItem)
        stackV.addArrangedSubview(whoIm)

        nicknameItem.tapTopButtonAction = { [weak self] in
            self?.tapChatPersonAction?()
        }
        genderItem.tapTopButtonAction = { [weak self] in
            self?.tapChatPersonAction?()
        }
        ageItem.tapTopButtonAction = { [weak self] in
            self?.tapChatPersonAction?()
        }
        whoIm.tapTopButtonAction = { [weak self] in
            self?.tapChatPersonAction?()
        }
    }
    
    func config(_ data: IMChatSetting?){
        guard let setting = data else {return}
        
        nicknameItem.contentLabel.text = setting.nickname
        genderItem.contentLabel.text = setting.sex?.localizedText ?? Sex.noncomfirming.localizedText
        var age = "-"
        if let birthday = setting.birthday{
            let date = Date.dateFromMilliseconds(birthday)
            let ageYears = Date().years(from: date)
            age = "\(ageYears)"
        }
        ageItem.contentLabel.text = age
        
        if let whoAmI = setting.whoAmI, whoAmI.count > 0{
            whoIm.contentLabel.text = whoAmI
            whoIm.contentLabel.textColor = .text
        }else{
            whoIm.contentLabel.text = "Unfilled"
            whoIm.contentLabel.textColor = .c.ctpd
        }
    }
}

class ChatSettingOtherCell: UITableViewCell {
    var stackV = UIStackView()

    var stackV1 = UIStackView()
    var chatModelItem = ChatSettingItemView()

    var stackV2 = UIStackView()
    var chatBubble = ChatSettingItemView()
    var chatBackground = ChatSettingItemView()

    var stackV3 = UIStackView()
    var autoPlayVoice = ChatSettingItemView()

    var data: IMChatSetting?
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        selectionStyle = .none
        backgroundColor = .clear

        setupViews()
        setupData()
        setupEvent()
    }

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

    private func setupViews() {
        stackV.spacing = 16
        stackV.axis = .vertical
        contentView.addSubview(stackV)
        stackV.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 24, bottom: 16, right: 24))
        }

        stackV1.backgroundColor = .c.csbn
        stackV1.layer.cornerRadius = 12
        stackV1.layer.masksToBounds = true
        stackV1.axis = .vertical
        stackV.addArrangedSubview(stackV1)

        stackV2.backgroundColor = .c.csbn
        stackV2.layer.cornerRadius = 12
        stackV2.layer.masksToBounds = true
        stackV2.axis = .vertical
        stackV.addArrangedSubview(stackV2)

        stackV3.backgroundColor = .c.csbn
        stackV3.layer.cornerRadius = 12
        stackV3.layer.masksToBounds = true
        stackV3.axis = .vertical
        stackV.addArrangedSubview(stackV3)

        chatModelItem.titleLabel.text = "Chat Model"
        chatModelItem.contentLabel.text = "Role-playing"
        chatModelItem.bottomLine.isHidden = true

        chatBubble.titleLabel.text = "Chat Bubble"

        chatBackground.title = "Chat Backgroud"
        chatBackground.bottomLine.isHidden = true

        autoPlayVoice.title = "Auto play voice"
        autoPlayVoice.bottomLine.isHidden = true
        autoPlayVoice.setupSwitchView()

        stackV1.addArrangedSubview(chatModelItem)
        stackV2.addArrangedSubview(chatBubble)
        stackV2.addArrangedSubview(chatBackground)
        stackV3.addArrangedSubview(autoPlayVoice)
    }
    
    private func setupData(){
        
    }
    
    private func setupEvent(){
        autoPlayVoice.controlSwitch.addTarget(self, action: #selector(autoPlayVoiceSwitchChanged), for: .valueChanged)
    }
    
    func config(_ data: IMChatSetting?){
        self.data = data
        guard let setting = data else {return}
        
        chatModelItem.contentLabel.text = setting.modelName ?? ""
        autoPlayVoice.controlSwitch.isOn = (setting.isAutoPlayVoice ?? 0) == 1
    }
    
    @objc private func autoPlayVoiceSwitchChanged(_ sender: UISwitch){
        let isOn = sender.isOn
        
        if isOn && UserCore.shared.user?.isMember == false{
            AppRouter.goVIPCenter()
            sender.isOn = false
            return
        }
        
        guard let aiId = data?.aiId else{return}
        Hud.showIndicator()
        AIRoleProvider.request(.chatSetAutoPlayVoice(aiId: Int(aiId), isAutoPlayVoice: isOn), modelType: EmptyModel.self) { result in
            Hud.hideIndicator()
            switch result {
            case .success:
                NotificationCenter.post(name: .chatSettingUpdated)
            case .failure:
                sender.isOn = !isOn
            }
        }
    }
}

class ChatSettingItemView: UIView {
    var titleLabel: UILabel!
    var badge: BadgeView!
    
    var arrow: UIImageView!
    var contentLabel: UILabel!
    var bottomLine: CLLine!
    var topButton: UIButton!
    var tapTopButtonAction: (() -> Void)?

    lazy var controlSwitch: UISwitch = {
        let v = UISwitch()
        addSubview(v)
        v.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-16)
        }
        return v
    }()

    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }

    var content: String? {
        didSet {
            if let str = content, str.count > 0 {
                contentLabel.text = content
                contentLabel.textColor = .c.ctpn
            } else {
                contentLabel.text = "Unfilled"
                contentLabel.textColor = .c.ctsn
            }
        }
    }

    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(64)
        }
        titleLabel = {
            let v = UILabel()
            v.textColor = .text
            v.font = .t.tll
            v.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 755), for: .horizontal)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.centerY.equalToSuperview()
                make.bottom.equalToSuperview()
            }
            return v
        }()
        
        badge = {
            let v = BadgeView()
            v.onlyShowPoint = true
            v.badgeValue = 1
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalTo(titleLabel.snp.trailing).offset(8)
            }
            v.isHidden = true
            return v
        }()

        arrow = {
            let v = UIImageView()
            v.image = MWIconFont.image(fromIcon: .arrowRightBorder, size: CGSize(width: 12, height: 12), color: .c.ctsn)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.trailing.equalToSuperview().offset(-16)
                make.centerY.equalToSuperview()
            }
            return v
        }()

        contentLabel = {
            let v = UILabel()
            v.font = .t.tbm
            v.textColor = .text
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.trailing.equalTo(arrow.snp.leading).offset(-8)
                make.leading.greaterThanOrEqualTo(titleLabel.snp.trailing).offset(24)
            }
            return v
        }()

        bottomLine = {
            let v = CLLine()
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(16)
                make.trailing.equalToSuperview().offset(-16)
                make.height.equalTo(0.5)
                make.bottom.equalToSuperview()
            }
            return v
        }()

        topButton = {
            let v = UIButton()
            v.addTarget(self, action: #selector(tapTopButton), for: .touchUpInside)
            addSubview(v)
            v.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            return v
        }()
    }

    func setupSwitchView() {
        contentLabel.isHidden = true
        arrow.isHidden = true
        topButton.isHidden = true
        controlSwitch.isHidden = false
    }

    @objc private func tapTopButton() {
        tapTopButtonAction?()
    }
}

class ChatSettingSectionHeader: UIView {
    var label: UILabel!
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .c.cbd
        label = {
            let v = UILabel()
            v.textColor = .text
            v.font = .t.tts
            addSubview(v)
            v.snp.makeConstraints { make in
                make.centerY.equalToSuperview()
                make.leading.equalToSuperview().offset(24)
            }
            return v
        }()
    }

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