//
//  YHDynamicSheetPickerView.swift
//  galaxy
//
//  Created by alexzzw on 2024/12/23.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHDynamicSheetPickerView: UIView {
    let dataSource: [String]
    // 选择的行
    var selectRow: Int = 0
    private var selectBlock: ((Int) -> Void)?

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

    lazy var pickerView: UIPickerView = {
        let view = UIPickerView()
        view.dataSource = self
        view.delegate = self
        return view
    }()

    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        view.addGestureRecognizer(tap)
        return view
    }()

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

    lazy var topView: UIView = {
        let view = UIView()
        view.addSubview(titleLabel)
        view.addSubview(cancelBtn)
        view.addSubview(confirmBtn)
        view.addSubview(topLineView)
        titleLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        cancelBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(21)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 30, height: 20))
        }
        confirmBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-21)
            make.centerY.equalToSuperview()
            make.size.equalTo(CGSize(width: 30, height: 20))
        }
        topLineView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(21)
            make.right.equalToSuperview().offset(-21)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }

        return view
    }()

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

    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_M(ofSize: 17)
        label.text = "请选择"
        return label
    }()

    lazy var cancelBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("取消".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.addTarget(self, action: #selector(didClickCancelButton), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()

    lazy var confirmBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("确定".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.brandMainColor, for: .normal)
        btn.addTarget(self, action: #selector(didClickConfirmButton), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()

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

    init(dataSource: [String]) {
        self.dataSource = dataSource
        super.init(frame: UIScreen.main.bounds)
        createUI()
    }

    func show() {
        showSelectRow()
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }

    func showSelectRow() {
        if selectRow < dataSource.count {
            pickerView.selectRow(selectRow, inComponent: 0, animated: true)

        } else {
            selectRow = 0
            pickerView.selectRow(0, inComponent: 0, animated: true)
        }
    }

    static func show(dataSource: [String], title: String, selectIndex: Int, callBack: @escaping ((Int) -> Void)) {
        let picker = YHDynamicSheetPickerView(dataSource: dataSource)
        picker.title = title
        picker.selectRow = selectIndex < dataSource.count ? selectIndex : 0
        picker.selectBlock = callBack
        picker.show()
    }

    static func show(dataSource: [String], title: String, selectTitle: String?, callBack: @escaping ((Int) -> Void)) {
        let picker = YHDynamicSheetPickerView(dataSource: dataSource)
        picker.title = title
        if let selectTitle = selectTitle, let firstIndex = dataSource.firstIndex(of: selectTitle) {
            picker.selectRow = firstIndex
        } else {
            picker.selectRow = 0
        }

        picker.selectBlock = callBack
        picker.show()
    }

    func createUI() {
        addSubview(blackMaskView)
        addSubview(whiteContentView)
        whiteContentView.addSubview(topView)
        whiteContentView.addSubview(pickerView)

        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = whiteContentView.bounds
        layer.path = path.cgPath
        whiteContentView.layer.mask = layer

        if let title = title {
            titleLabel.text = title
        }

        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        let whiteContentHeight = 322.0

        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(whiteContentHeight)
        }

        topView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(52)
        }

        pickerView.snp.makeConstraints { make in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
}

extension YHDynamicSheetPickerView {
    @objc func didClickCancelButton() {
        dismiss()
    }

    @objc func didClickConfirmButton() {
        selectBlock?(selectRow)
        dismiss()
    }

    @objc func dismiss() {
        removeFromSuperview()
    }
}

// MARK: - UIPickerViewDelegate

extension YHDynamicSheetPickerView: UIPickerViewDelegate, UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if !dataSource.isEmpty {
            return dataSource.count
        }
        return 0
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if 0 <= row && row < dataSource.count {
            return dataSource[row]
        }
        return ""
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if 0 <= row && row < dataSource.count {
            selectRow = row
            // 刷新picker，看上面的代理
            pickerView.reloadComponent(component)
        }
    }

    func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat {
        return KScreenWidth - 16 * 2
    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        return 42.0
    }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textAlignment = .center
        label.numberOfLines = 2
        label.text = ""
        if 0 <= row && row < dataSource.count {
            label.text = dataSource[row]
        }
        if selectRow == row {
            label.font = UIFont.PFSC_M(ofSize: 14)

        } else {
            label.font = UIFont.PFSC_R(ofSize: 14)
        }

        // 选中背景色
        if #available(iOS 14.0, *), pickerView.subviews.count > 1 {
            pickerView.subviews[1].backgroundColor = UIColor.brandMainColor6
        }
        return label
    }
}
