//
//  RoleClassificationSelect.swift

//
//  Created by Leon on 2025/7/21.
//
import UIKit

class RoleClassificationSelect: UIView {
    var bottomButton: StyleButton!
    var container: LTScrollContainer!
    var titleView: TitleView!
    var stepLabel: UILabel!

    var roleContainer: UIView!
    var roleFirstSectionFlowLayout: FlowAutoLayoutContainer!
    var roleFirstSectionTitleLabel: UILabel!
    var roleSecondSectionFlowLayout: FlowAutoLayoutContainer!
    var roleSecondSectionTitleLabel: UILabel!

    var personalityContainer: UIView!
    var personalityFlowLayout: FlowAutoLayoutContainer!

    var tagsContainer: UIView!
    var tagsFlowLayout: FlowAutoLayoutContainer!
    
    
    
    let startIndexOfRoleFirst = 5000
    let startIndexOfRoleSecond = 5100
    let startIndexOfPersonal = 5200
    let startIndexOfTags = 5300
    

    // Data.
    @Published var selectRoleCode: String = ""
    @Published var selectCharacterCode: String = ""
    @Published var selectTagCode: String = ""
    var selectCharacterNode : DictNode!

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

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

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

        // Role
        roleContainer = {
            let v = UIView()
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.equalToSuperview().offset(CGFloat.lrs)
                make.trailing.equalToSuperview().offset(-CGFloat.lrs)
            }

            let titleLabel = UILabel()
            titleLabel.textColor = .c.ctpn
            titleLabel.font = CLSystemToken.font(token: .ttl)
            v.addSubview(titleLabel)
            titleLabel.text = "Role"
            titleLabel.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.top.equalToSuperview()
            }

            let subTitle = UILabel()
            roleFirstSectionTitleLabel = subTitle
            subTitle.textColor = .c.ctpn
            subTitle.font = CLSystemToken.font(token: .tlm)
            v.addSubview(subTitle)
            subTitle.text = "Original"
            subTitle.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(16)
            }

            roleFirstSectionFlowLayout = FlowAutoLayoutContainer()
            v.addSubview(roleFirstSectionFlowLayout)
            roleFirstSectionFlowLayout.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalTo(subTitle.snp.bottom).offset(12)
                // make.bottom.equalToSuperview()
            }

            let subTitle2 = UILabel()
            roleSecondSectionTitleLabel = subTitle2
            subTitle2.textColor = .c.ctpn
            subTitle2.font = CLSystemToken.font(token: .tlm)
            v.addSubview(subTitle2)
            subTitle2.text = "Fanfiction"
            subTitle2.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.top.equalTo(roleFirstSectionFlowLayout.snp.bottom).offset(12)
            }

            roleSecondSectionFlowLayout = FlowAutoLayoutContainer()
            v.addSubview(roleSecondSectionFlowLayout)
            roleSecondSectionFlowLayout.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalTo(subTitle2.snp.bottom).offset(12)
                make.bottom.equalToSuperview()
            }

            return v
        }()

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

            let titleLabel = UILabel()
            titleLabel.textColor = .c.ctpn
            titleLabel.font = CLSystemToken.font(token: .ttl)
            v.addSubview(titleLabel)
            titleLabel.text = "Personality"
            titleLabel.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.top.equalToSuperview()
            }

            personalityFlowLayout = FlowAutoLayoutContainer()
            v.addSubview(personalityFlowLayout)
            personalityFlowLayout.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
                make.bottom.equalToSuperview()
            }
            return v
        }()

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

            let titleLabel = UILabel()
            titleLabel.textColor = .c.ctpn
            titleLabel.font = CLSystemToken.font(token: .ttl)
            v.addSubview(titleLabel)
            titleLabel.text = "Tags"
            titleLabel.snp.makeConstraints { make in
                make.leading.equalToSuperview()
                make.top.equalToSuperview()
            }

            tagsFlowLayout = FlowAutoLayoutContainer()
            v.addSubview(tagsFlowLayout)
            tagsFlowLayout.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalTo(titleLabel.snp.bottom).offset(12)
                make.bottom.equalToSuperview()
            }
            return v
        }()

//        setupRoleItems()
//        setupPersonalityItems()
//        setupTagsItem()

        titleView.title = "Classification"
        bottomButton.setTitle("Next", for: .normal)
    }

    private func setupDatas() {
        guard let aiDict = AppDictManager.shared.aiDict else { return }

        setupRoleItems(nodes: aiDict.roleDictList)

        setupFlowLayoutItems(nodes: aiDict.characterDictList, flowlayout: personalityFlowLayout)

        //setupFlowLayoutItems(nodes: aiDict.tagDictList, flowlayout: tagsFlowLayout)
    }

    private func setupRoleItems(nodes: [DictNode]?) {
        guard let roles = nodes else { return }
        if roles.count > 0 {
            let thisNode = roles[0]
            if let childs = thisNode.childDictList {
                for (index, per) in childs.enumerated() {
                    let button = createChipButtonBy(name: per.name)
                    button.tag = startIndexOfRoleFirst + index
                    roleFirstSectionFlowLayout.addArrangedSubview(button)
                    if index == 0 {
                        selectRoleCode = per.code!
                        button.isSelected = true
                    }
                }
            }
            roleFirstSectionTitleLabel.text = thisNode.name
        }

        if roles.count > 1 {
            let thisNode = roles[1]
            if let childs = thisNode.childDictList {
                for (index, per) in childs.enumerated() {
                    let button = createChipButtonBy(name: per.name)
                    button.tag = startIndexOfRoleSecond + index
                    roleSecondSectionFlowLayout.addArrangedSubview(button)
                }
            }
            roleSecondSectionTitleLabel.text = thisNode.name
        }
    }

    private func setupFlowLayoutItems(nodes: [DictNode]?, flowlayout: FlowAutoLayoutContainer) {
        guard let realNodes = nodes else { return }

        flowlayout.removeAllArrangedSubviews()
        
        for (index, per) in realNodes.enumerated() {
            let button = createChipButtonBy(name: per.name)
            
            flowlayout.addArrangedSubview(button)
            
            // Default select first node
            if index == 0 {
                if flowlayout == personalityFlowLayout {
                    selectCharacterCode = per.code!
                    selectCharacterNode = per
                    
                    // 默认选中当前Tags下的第一个tag
                    setupFlowLayoutItems(nodes: per.childDictList, flowlayout: tagsFlowLayout)
                } else if flowlayout == tagsFlowLayout {
                    selectTagCode = per.code!
                }
                button.isSelected = true
            }

            // Set tag for button
            if flowlayout == personalityFlowLayout {
                button.tag = startIndexOfPersonal + index
                
            }else if flowlayout == tagsFlowLayout {
                button.tag = startIndexOfTags + index
                flowlayout.setNeedsDisplay()
                flowlayout.layoutIfNeeded()
                setNeedsDisplay()
            }
        }
        
        
    }

    // MARK: - Public
    
    func restoreSelectPerson(selectCode: String?){
        guard let aiDict = AppDictManager.shared.aiDict, let code = selectCode, let characterDictList = aiDict.characterDictList else {return}
        selectCharacterCode = code
        for per in characterDictList {
            if code == (per.code ?? "") {
                selectCharacterNode = per
            }
        }
        // 其他按钮取消选中
        for per in personalityFlowLayout.subviews {
            if let button = per as? EPChipFilterButton {
                button.isSelected = false
            }
        }
        
        for (index, per) in characterDictList.enumerated() {
            if per.code == code {
                let button = personalityFlowLayout.viewWithTag(startIndexOfPersonal + index) as? EPChipFilterButton
                button?.isSelected = true
            }
        }
    }

    func restoreSelectTag(selectCode: String?){
        guard let aiDict = AppDictManager.shared.aiDict, let code = selectCode, let tagDictList = selectCharacterNode.childDictList else {return}
        selectTagCode = code
        // 其他按钮取消选中
        for per in tagsFlowLayout.subviews {
            if let button = per as? EPChipFilterButton {
                button.isSelected = false
            }
        }

        for (index, per) in tagDictList.enumerated() {
            if per.code == code {
                let button = tagsFlowLayout.viewWithTag(startIndexOfTags + index) as? EPChipFilterButton
                button?.isSelected = true
            }
        }
    }

    func restoreSelectRole(selectCode: String?){
        guard let aiDict = AppDictManager.shared.aiDict, let code = selectCode, let roleDictList = aiDict.roleDictList else {return}
        
        selectRoleCode = code
        // 其他按钮取消选中
        for per in roleFirstSectionFlowLayout.subviews {
            if let button = per as? EPChipFilterButton {
                button.isSelected = false
            }
        }

        for per in roleSecondSectionFlowLayout.subviews {
            if let button = per as? EPChipFilterButton {
                button.isSelected = false
            }
        }
        
        for (index, per) in roleDictList.enumerated() {
            if index == 0{
                if let nodes = per.childDictList{
                    for (indexNode, perNode) in nodes.enumerated() {
                        if perNode.code == code {
                            let button = roleFirstSectionFlowLayout.viewWithTag(startIndexOfRoleFirst + indexNode) as? EPChipFilterButton
                            button?.isSelected = true
                        }
                    }
                }
            }else if index == 1{
                if let nodes = per.childDictList{
                    for (indexNode, perNode) in nodes.enumerated() {
                        if perNode.code == code {
                            let button = roleSecondSectionFlowLayout.viewWithTag(startIndexOfRoleSecond + indexNode) as? EPChipFilterButton
                            button?.isSelected = true
                        }
                    }
                }
            }
        }

//        for (index, per) in roleDictList.enumerated() {
//            if per.code == code {
//                let button = roleFirstSectionFlowLayout.viewWithTag(startIndexOfRoleFirst + index) as? EPChipFilterButton
//                button?.isSelected = true
//            }else if per.code == code {
//                let button = roleSecondSectionFlowLayout.viewWithTag(startIndexOfRoleSecond + index) as? EPChipFilterButton
//                button?.isSelected = true
//            }
//        }
    }
    

    // MARK: - Helper

    private func createChipButtonBy(name: String) -> EPChipFilterButton {
        let button = EPChipFilterButton()
        button.text = name
        button.addTarget(self, action: #selector(tapChipButton(sender:)), for: .touchUpInside)
        return button
    }

    // MARK: - Button

    @objc private func tapChipButton(sender: UIButton) {
        guard let superView: FlowAutoLayoutContainer = sender.superview as? FlowAutoLayoutContainer else {
            return
        }
        
        guard let aiDict = AppDictManager.shared.aiDict else { return }
        
        if superView == roleFirstSectionFlowLayout || superView == roleSecondSectionFlowLayout{
            // Reset
            for per in roleFirstSectionFlowLayout.subviews {
                if let button = per as? EPChipFilterButton {
                    button.isSelected = false
                }
            }
            for per in roleSecondSectionFlowLayout.subviews {
                if let button = per as? EPChipFilterButton {
                    button.isSelected = false
                }
            }
            
            let index = superView.subviews.firstIndex(of: sender) ?? 0
            sender.isSelected = true
            
            if superView == roleFirstSectionFlowLayout{
                let node =  aiDict.roleDictList![0].childDictList![index]
                selectRoleCode = node.code ?? ""
            }else if superView == roleSecondSectionFlowLayout{
                let node =  aiDict.roleDictList![1].childDictList![index]
                selectRoleCode = node.code ?? ""
            }
            
        }else if superView == personalityFlowLayout{
            for per in superView.subviews {
                if let button = per as? EPChipFilterButton {
                    button.isSelected = false
                }
            }
            let index = superView.subviews.firstIndex(of: sender) ?? 0
            dlog("当前选中\(index) in \(superView)")
            sender.isSelected = true
            
            selectCharacterCode = aiDict.characterDictList![index].code ?? ""
            selectCharacterNode = aiDict.characterDictList![index]
            
            
            
            setupFlowLayoutItems(nodes: selectCharacterNode.childDictList, flowlayout: tagsFlowLayout)
        }else if superView == tagsFlowLayout{
            for per in superView.subviews {
                if let button = per as? EPChipFilterButton {
                    button.isSelected = false
                }
            }
            let index = superView.subviews.firstIndex(of: sender) ?? 0
            dlog("当前选中\(index) in \(superView)")
            sender.isSelected = true
            
            selectTagCode = selectCharacterNode.childDictList![index].code ?? ""
        }
        
        // Reset
//        for per in superView.subviews {
//            if let button = per as? EPChipFilterButton {
//                button.isSelected = false
//            }
//        }
//        let index = superView.subviews.firstIndex(of: sender) ?? 0
//        dlog("当前选中\(index) in \(superView)")
//        sender.isSelected = true
    }

    // MARK: - Test

    private func setupTestRoleItems() {
        do {
            let button = createChipButtonBy(name: "Original")
            roleFirstSectionFlowLayout.addArrangedSubview(button)
        }

        do {
            let button = createChipButtonBy(name: "Anime")
            roleFirstSectionFlowLayout.addArrangedSubview(button)
        }

        do {
            let button = createChipButtonBy(name: "Games")
            roleSecondSectionFlowLayout.addArrangedSubview(button)
        }

        do {
            let button = createChipButtonBy(name: "Film & TV")
            roleFirstSectionFlowLayout.addArrangedSubview(button)
        }

        do {
            let button = createChipButtonBy(name: "CC & GG")
            roleFirstSectionFlowLayout.addArrangedSubview(button)
        }

        do {
            let button = createChipButtonBy(name: "Film")
            roleFirstSectionFlowLayout.addArrangedSubview(button)
        }

        do {
            let button = createChipButtonBy(name: "FSSF_d")
            roleFirstSectionFlowLayout.addArrangedSubview(button)
        }
        roleFirstSectionFlowLayout.layoutIfNeeded()
    }

    private func setupTestPersonalityItems() {
        do {
            let button = createChipButtonBy(name: "Madness")
            personalityFlowLayout.addArrangedSubview(button)
        }
        do {
            let button = createChipButtonBy(name: "Calm")
            personalityFlowLayout.addArrangedSubview(button)
        }
        do {
            let button = createChipButtonBy(name: "Anime")
            personalityFlowLayout.addArrangedSubview(button)
        }
        do {
            let button = createChipButtonBy(name: "Calm2")
            personalityFlowLayout.addArrangedSubview(button)
        }
        do {
            let button = createChipButtonBy(name: "Test")
            personalityFlowLayout.addArrangedSubview(button)
        }
        personalityContainer.layoutIfNeeded()
    }

    private func setupTestTagsItem() {
        do {
            let button = createChipButtonBy(name: "Madness")
            tagsFlowLayout.addArrangedSubview(button)
        }
        do {
            let button = createChipButtonBy(name: "Calm")
            tagsFlowLayout.addArrangedSubview(button)
        }
        tagsFlowLayout.layoutIfNeeded()
    }
}
