//
//  YHMakePlanSelectAlertView.swift
//  galaxy
//
//  Created by EDY on 2025/3/29.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString

class YHMakePlanSelectAlertView: UIView {
    typealias Block = (Int) -> Void
    var block: Block?
    var centerView: UIView!
    var titleLabel: UILabel!
    var closeButton: UIButton!
    var sureButton: UIButton!
    var hasSelectLabel: UILabel!
    var cardView: YHMakePlanCardView!
    var lineView: UIView!
    var selectIndex: Int = 0
    var selectProductId: Int = 0
    var firstData: YHMakePlanMainModel?
    var dataSource: YHMakePlanMainModel? {
        didSet {
            updata()
        }
    }
    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 20))
        let label = UILabel()
        label.text = "产品类型"
        label.textColor = UIColor(hex: 0x8993a2)
        label.font = UIFont.PFSC_M(ofSize: 15)
        label.frame = CGRect(x: 20, y: 0, width: KScreenWidth, height: 20)
        view.addSubview(label)
        tableView.tableHeaderView = view
        tableView.register(cellWithClass: YHMakePlanCardCell.self)
        return tableView
    }()
    
    static func show(dataSource: YHMakePlanMainModel, callBack: @escaping ((Int) -> Void)) {
        let view = YHMakePlanSelectAlertView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.dataSource = dataSource
        view.firstData = dataSource
        view.block = callBack
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.5, alpha: 0.1)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setView() {
        backgroundColor = UIColor(hex: 0x0000, alpha: 0.5)
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius3
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(720)
        }
        
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .center
            label.text = "公司经营套餐选择"
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(16)
            make.height.equalTo(20)
            make.right.equalTo(-18)
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "address_close"), for: .normal)
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.width.equalTo(24)
            make.top.equalTo(18)
        }
        
        closeButton.YH_clickEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        
        lineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(52)
            make.height.equalTo(1)
            make.right.equalTo(-18)
        }
        
        let bottomLineView = {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            return view
        }()
        centerView.addSubview(bottomLineView)
        bottomLineView.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(214)
            make.height.equalTo(1)
            make.right.equalTo(-18)
        }
        
        hasSelectLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_M(ofSize: 15)
            label.textColor = UIColor(hex: 0x8993a2)
            label.text = "已选产品"
            return label
        }()
        centerView.addSubview(hasSelectLabel)
        hasSelectLabel.snp.makeConstraints { make in
            make.left.equalTo(18)
            make.top.equalTo(72)
            make.height.equalTo(20)
            make.right.equalTo(-18)
        }
        
        cardView = {
            let label = YHMakePlanCardView()
            label.containerView.backgroundColor = .clear
            return label
        }()
        centerView.addSubview(cardView)
        cardView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomLineView.snp.top).offset(-6.5)
            make.height.equalTo(121)
        }
        
        sureButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor = .black
            button.setTitleColor(UIColor(hex: 0xffffff), for: .normal)
            button.setTitle("确认", for: .normal)
            button.layer.cornerRadius = 4
            button.addTarget(self, action: #selector(orderButtonClick), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(sureButton)
        sureButton.snp.makeConstraints { make in
            make.bottom.equalTo(-42)
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(46)
        }

        centerView.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(bottomLineView.snp.bottom).offset(24)
            make.bottom.equalTo(-96)
        }
    }
    
    func updata() {
        guard let data = dataSource else { return }
        for i in 0 ..< data.sub_product.count {
            if data.sub_product[i].is_add_cart == true {
                selectIndex = i
            }
        }
        if data.sub_product.count > 0 {
            cardView.configureSub(with: data.sub_product[selectIndex])
            selectProductId = data.sub_product[selectIndex].product_id
        }
        tableView.reloadData()
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        dismiss()
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
    @objc func orderButtonClick() {
        if let block = block {
            if dataSource?.sub_product[selectIndex].is_add_cart == firstData?.sub_product[selectIndex].is_add_cart {
                dismiss()
                return
            }
            block(dataSource?.sub_product[selectIndex].product_id ?? 0)
        }
        dismiss()
    }
    
}

extension YHMakePlanSelectAlertView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if touch.view == self {
            return true
        }
        return false
    }
}

extension YHMakePlanSelectAlertView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//        return items.count
        return dataSource?.sub_product.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withClass: YHMakePlanCardCell.self) as? YHMakePlanCardCell else {
            return UITableViewCell()
        }
        guard let model = dataSource?.sub_product[indexPath.row] else { return UITableViewCell()}
        cell.configure(with: model)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 94
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectIndex = indexPath.row
        let count = dataSource?.sub_product.count ?? 0
        for i in 0 ..< count {
            if i == indexPath.row {
                dataSource?.sub_product[i].is_add_cart = true
                guard let model =  dataSource?.sub_product[i] else { return }
                cardView.configureSub(with: model)
            } else {
                dataSource?.sub_product[i].is_add_cart = false
            }
        }
        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

}

class YHMakePlanCardCell: UITableViewCell {
    
    // MARK: - UI Elements
    private let containerView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.borderWidth = 1
        view.layer.borderColor = UIColor.mainTextColor.cgColor
        return view
    }()
    
    private let bgImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "global_default_image")
        return imageView
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.text = "星企航6年服务"
        label.font = UIFont.PFSC_M(ofSize: 14)
        label.textColor = .mainTextColor
        return label
    }()
    
    private let priceLabel: UILabel = {
        let label = UILabel()
        label.text = "￥129980"
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.textColor = .mainTextColor
        return label
    }()
    
    // MARK: - Initialization
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
        setupConstraints()
        selectionStyle = .none
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup
    private func setupUI() {
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        contentView.addSubview(containerView)
        containerView.addSubview(bgImageView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(priceLabel)
    }
    
    private func setupConstraints() {
        containerView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(8)
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-8)
        }
        
        bgImageView.snp.makeConstraints { make in
            make.height.width.equalTo(46)
            make.left.equalToSuperview().offset(16)
            make.centerY.equalToSuperview()
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.left.equalToSuperview().offset(72)
            make.right.equalToSuperview().offset(-16)
        }
        
        priceLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(72)
            make.right.equalToSuperview().offset(-16)
            make.bottom.equalToSuperview().offset(-12)
        }
    }
    
    // MARK: - Configuration
    func configure(with service: YHMakePlanSubModel) {
        titleLabel.text = service.product_name
        priceLabel.text = "¥" + service.price.formattedPrice()
        if service.is_add_cart {
            containerView.layer.borderWidth = 1
            containerView.layer.borderColor = UIColor.mainTextColor.cgColor
        } else {
            containerView.layer.borderWidth = 1
            containerView.layer.borderColor = UIColor(hex: 0xe9ecf0).cgColor
        }
        if let url = URL(string: service.cover_img) {
            bgImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
        }
    }
}
