//
//  RolesFilterController.swift

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

import UIKit

enum RolesFilterType {
    case meet
    case discover
}

class RolesFilterController: CLBaseViewController {
    let startOfGenderIndex = 5000
    let startOfAgeIndex = 5100

    var operateButton: StyleButton!
    var container: LTScrollContainer!

    var titleView: TitleView!

    var genderView: FlowAutoLayoutContainer!
    var ageView: FlowAutoLayoutContainer!

    var typeView: RoleFilterTypeView!

    var ageTypes = [AIRoleListRequestAge.AGE_1,
                    AIRoleListRequestAge.AGE_2,
                    AIRoleListRequestAge.AGE_3,
                    AIRoleListRequestAge.AGE_4,
                    AIRoleListRequestAge.AGE_5,
    ]
    
    var filterType: RolesFilterType = .discover

    var rolesFilterModel : RolesFilterModel!

    var completion: ((_ rolesFilterModel: RolesFilterModel) -> Void)?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        setupViews()
        setupDatas()
        setupEvents()
    }

    private func setupViews() {
        let title = "Filter"
        navigationView.alpha0Title = title
        navigationView.setupBackButtonCloseIcon()

        operateButton = {
            let v = StyleButton()
            v.primary(size: .large)
            v.setTitle("Complete", for: .normal)
            v.addTarget(self, action: #selector(operateButtonTapped), 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
        }()

        container = {
            let v = LTScrollContainer()
            v.stack.spacing = 32
            view.addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
                make.top.equalTo(navigationView.snp.bottom)
                make.bottom.equalTo(operateButton.snp.top).offset(-16)
            }
            return v
        }()

        titleView = {
            let v = TitleView()
            v.title = title
            container.stack.addArrangedSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.equalToSuperview()
            }
            return v
        }()
        container.stack.setCustomSpacing(12, after: titleView)

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

            let perTitleLabel = {
                let v = CLLabel()
                v.font = .t.ttm
                perContainer.addSubview(v)
                v.snp.makeConstraints { make in
                    make.top.equalToSuperview()
                    make.leading.equalToSuperview()
                }
                return v
            }()
            perTitleLabel.text = "Gender"

            genderView = {
                let v = FlowAutoLayoutContainer()
                perContainer.addSubview(v)
                v.snp.makeConstraints { make in
                    make.leading.trailing.equalToSuperview()
                    make.top.equalTo(perTitleLabel.snp.bottom).offset(16)
                    make.bottom.equalToSuperview()
                }
                return v
            }()
        }

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

            let perTitleLabel = {
                let v = CLLabel()
                v.font = .t.ttm
                perContainer.addSubview(v)
                v.snp.makeConstraints { make in
                    make.top.equalToSuperview()
                    make.leading.equalToSuperview()
                }
                return v
            }()
            perTitleLabel.text = "Age"

            ageView = {
                let v = FlowAutoLayoutContainer()
                perContainer.addSubview(v)
                v.snp.makeConstraints { make in
                    make.leading.trailing.equalToSuperview()
                    make.top.equalTo(perTitleLabel.snp.bottom).offset(16)
                    make.bottom.equalToSuperview()
                }
                return v
            }()
        }

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

    private func setupDatas() {
        do {
            let items = [Sex.male, Sex.female, Sex.noncomfirming]
            for (index, per) in items.enumerated() {
                let button = createChipButtonBy(name: per.localizedText)
                button.tag = startOfGenderIndex + index
                
                if let sexsSelect = rolesFilterModel.sex{
                    if sexsSelect.contains(per){
                        button.isSelected = true
                    }
                }
                
//                if let selectedSex = rolesFilterModel.sex, per == selectedSex {
//                    button.isSelected = true
//                }
                genderView.addArrangedSubview(button)
            }
        }

        do {
            var titles = [String]()
            for per in ageTypes {
                if let string = per.localized {
                    titles.append(string)
                }
            }
            for (index, per) in ageTypes.enumerated() {
                let button = createChipButtonBy(name: per.localized!)
                button.tag = startOfAgeIndex + index
                if let selecteAge = rolesFilterModel.age, selecteAge == per {
                    button.isSelected = true
                }
                ageView.addArrangedSubview(button)
            }
        }

        typeView.selectTypes(rolesFilterModel.roleCodeList)
    }

    private func setupEvents() {
    }

    // 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: - Action

    @objc private func tapChipButton(sender: UIButton) {
        guard let superView: FlowAutoLayoutContainer = sender.superview as? FlowAutoLayoutContainer else {
            return
        }

        // 根据filterType决定单选还是多选
        if sender.isSelected {
            sender.isSelected = false
        } else {
            if filterType == .meet || filterType == .discover { // 单选模式看下面：
                for per in superView.subviews {
                    if let button = per as? EPChipFilterButton {
                        button.isSelected = false
                    }
                }
            }
            // discover模式：多选，不需要清除其他选择
            sender.isSelected = true
        }
    }

    @objc private func operateButtonTapped() {
        var confirmFilterModel = RolesFilterModel()
        
        // 获取选中的性别
        if filterType == .discover {
            // discover模式：多选
            var selectedSexes: [Sex] = []
            for subview in genderView.subviews {
                if let button = subview as? EPChipFilterButton, button.isSelected {
                    let index = button.tag - startOfGenderIndex
                    if index >= 0 && index < 3, let sex = Sex(rawValue: index) {
                        selectedSexes.append(sex)
                    }
                }
            }
            if !selectedSexes.isEmpty {
                confirmFilterModel.sex = selectedSexes
            }
        } else {
            // meet模式：单选
            var selectedSex: Sex?
            for subview in genderView.subviews {
                if let button = subview as? EPChipFilterButton, button.isSelected {
                    let index = button.tag - startOfGenderIndex
                    if index >= 0 && index < 3 {
                        selectedSex = Sex(rawValue: index)
                    }
                    break
                }
            }
            if let selectedSex = selectedSex {
                confirmFilterModel.sex = [selectedSex]
            }
        }
        
        // 获取选中的年龄
        var selectedAge: AIRoleListRequestAge?
        for subview in ageView.subviews {
            if let button = subview as? EPChipFilterButton, button.isSelected {
                let index = button.tag - startOfAgeIndex
                if index >= 0 && index < ageTypes.count {
                    selectedAge = ageTypes[index]
                }
                break
            }
        }
        
        // 获取选中的角色类型
        let selectedRoleTypes = typeView.getSelectedTypes()
        
        // 更新过滤模型
        if selectedAge != nil {
            confirmFilterModel.age = selectedAge
        }

        if selectedRoleTypes.count > 0 {
            confirmFilterModel.roleCodeList = selectedRoleTypes
        }else {
            confirmFilterModel.roleCodeList = nil
        }
        
        completion?(confirmFilterModel)
        
        // 关闭当前页面
        dismiss(animated: true)
    }
}
