//
//  YHIncomeTypeSelectViewController.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/16.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHIncomeTypeSelectViewController: YHBaseViewController {
    private lazy var infoTitleLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_M(ofSize: 17)
        label.textColor = .mainTextColor
        label.text = "选择收入类型(多选)"
        return label
    }()

    private lazy var closeButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "work_example_close"), for: .normal)
        button.addTarget(self, action: #selector(closeButtonClicked), for: .touchUpInside)
        return button
    }()

    private lazy var topLineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hexString: "#F0F0F0")
        return view
    }()

    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .grouped)
        view.estimatedSectionHeaderHeight = 0.01
        view.estimatedSectionFooterHeight = 12
        view.sectionHeaderHeight = 0.01
        view.sectionFooterHeight = 12
        view.backgroundColor = .white
        view.contentInsetAdjustmentBehavior = .never
        view.separatorStyle = .none
        view.rowHeight = UITableView.automaticDimension
        view.estimatedRowHeight = 52.0
        view.dataSource = self
        view.delegate = self
        view.showsVerticalScrollIndicator = false
        view.register(YHIncomeTypePopViewSelectCell.self, forCellReuseIdentifier: YHIncomeTypePopViewSelectCell.cellReuseIdentifier)

        return view
    }()

    private lazy var sureButton: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        button.setTitle("确认", for: .normal)
        button.setTitle("确认", for: .highlighted)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .normal)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .highlighted)
        button.setTitleColor(UIColor(hex: 0xFFFFFF), for: .disabled)
        button.addTarget(self, action: #selector(clickSureButton), for: .touchUpInside)
        button.layer.cornerRadius = kCornerRadius3
        button.clipsToBounds = true
        button.backgroundColor = .brandMainColor
        return button
    }()

    private lazy var bottomView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()

    private lazy var datas: [YHIncomeTypeSelectModel] = {
        YHIncomeType.allCases.map {
            YHIncomeTypeSelectModel(type: $0, isSelected: false)
        }
    }()

    var sureButtonEvent: (([YHIncomeType]) -> Void)?

    private var selectedTypes: [YHIncomeType] = []
    init(selectedTypes: [YHIncomeType]) {
        self.selectedTypes = selectedTypes
        super.init(nibName: nil, bundle: nil)
    }

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

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupDatas()
    }

    @objc private func clickSureButton() {
        sureButtonEvent?(selectedTypes.sorted(by: { $0.rawValue < $1.rawValue }))
        dismiss(animated: true)
    }

    @objc private func closeButtonClicked() {
        dismiss(animated: true)
    }

    private func setupUI() {
        gk_navBarAlpha = 0
        gk_navigationBar.isHidden = true
        view.backgroundColor = UIColor.white
        view.addSubview(infoTitleLabel)
        view.addSubview(closeButton)
        view.addSubview(topLineView)
        view.addSubview(tableView)
        view.addSubview(bottomView)
        bottomView.addSubview(sureButton)
        infoTitleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.centerX.equalToSuperview()
        }

        closeButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-21)
            make.height.width.equalTo(24)
            make.centerY.equalTo(infoTitleLabel)
        }

        topLineView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-21)
            make.left.equalToSuperview().offset(21)
            make.height.equalTo(0.5)
            make.top.equalTo(infoTitleLabel.snp.bottom).offset(12)
        }

        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.height.equalTo(64)
        }

        sureButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(kMargin)
            make.right.equalToSuperview().offset(-kMargin)
            make.centerY.equalToSuperview()
            make.height.equalTo(48)
        }

        tableView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.top.equalTo(topLineView.snp.bottom).offset(12)
            make.bottom.equalTo(bottomView.snp.top)
        }
        tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNonzeroMagnitude))
        tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 20))
        preferredContentSize = CGSize(width: KScreenWidth, height: KScreenHeight - k_Height_NavigationtBarAndStatuBar - 44)
    }

    private func setupDatas() {
        datas.forEach { [weak self] model in
            guard let self = self else {
                return
            }
            if self.selectedTypes.contains(model.type) {
                model.isSelected = true
            }
        }
    }
}

extension YHIncomeTypeSelectViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        return 1
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let model = datas[indexPath.section]
        if let cell = tableView.dequeueReusableCell(withIdentifier: YHIncomeTypePopViewSelectCell.cellReuseIdentifier) as? YHIncomeTypePopViewSelectCell {
            cell.setupCellInfo(title: model.type.nameString(), isSelected: model.isSelected)
            return cell
        }
        return UITableViewCell()
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 12.0
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        guard datas.count > indexPath.section else {
            return
        }
        let model = datas[indexPath.section]
        model.isSelected.toggle()
        if model.isSelected {
            if !selectedTypes.contains(model.type) {
                selectedTypes.append(model.type)
            }
        } else {
            if let index = selectedTypes.firstIndex(where: { type in
                type == model.type
            }) {
                selectedTypes.remove(at: index)
            }
        }

        tableView.reloadRows(at: [indexPath], with: .automatic)
    }
}
