//
//  GiftCountChooseController.swift

//
//  Created by Leon on 2025/8/24.
//
import SnapKit
import UIKit

// MARK: - GiftCountChooseCell

class GiftCountChooseCell: UITableViewCell {
    let countLabel: UILabel
    let line: UIView
    let selectedIcon : UIImageView

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        countLabel = UILabel()
        line = UIView()
        selectedIcon = UIImageView()
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        backgroundColor = .clear
        contentView.backgroundColor = .clear
        selectionStyle = .none

        // Setup countLabel
        countLabel.textAlignment = .center
        countLabel.font = .t.tnms
        countLabel.textColor = .text
        contentView.addSubview(countLabel)
        countLabel.snp.makeConstraints { make in
            //make.edges.equalToSuperview()
            make.centerY.equalToSuperview()
            make.leading.equalToSuperview().offset(16)
        }
        
        selectedIcon.image = UIImage(named: "checkmark_tick")
        contentView.addSubview(selectedIcon)
        selectedIcon.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.trailing.equalToSuperview().offset(-16)
        }
        selectedIcon.isHidden = true

        // Setup line
//        line.backgroundColor = .c.con
//        contentView.addSubview(line)
//        line.snp.makeConstraints { make in
//            make.leading.equalToSuperview().offset(8)
//            make.trailing.equalToSuperview().offset(-8)
//            make.height.equalTo(1)
//            make.bottom.equalToSuperview()
//        }
    }

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

// MARK: - GiftCountChooseController

class GiftCountChooseController: UIViewController {
    private let sourceRect: CGRect
    private let container: UIView
    private let datas: [String]
    private let bgImageView: UIImageView
    private let tableView: UITableView
    private static let cellId = "GiftCountCell"
    private static let rowHeight: CGFloat = 48
    var selectedValue: String?

    var chooseBlock: ((String) -> Void)?
    var popoverDismiss: (() -> Void)?

    init(sourceRect: CGRect, selectedValue: String? = nil) {
        self.sourceRect = sourceRect
        self.selectedValue = selectedValue
        container = UIView()
        container.layer.borderColor = UIColor.c.cpn.cgColor
        container.layer.borderWidth = 2
        container.layer.cornerRadius = 16
        container.layer.masksToBounds = true
        
        datas = ["100", "50", "20", "10", "5", "3", "1"].reversed()
        bgImageView = UIImageView()
        tableView = UITableView(frame: .zero, style: .plain)
        super.init(nibName: nil, bundle: nil)
        modalPresentationStyle = .fullScreen
        view.backgroundColor = .clear
        setupUI()
    }

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

    @objc private func close() {
        popoverDismiss?()
        view.removeFromSuperview()
        removeFromParent()
    }

    private func setupUI() {
        // Background button for dismissal
        let button = UIButton()
        view.addSubview(button)
        button.addTarget(self, action: #selector(close), for: .touchUpInside)
        button.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }

        // Setup container
        let w: CGFloat = 120// 76
        let h: CGFloat = 232 //Self.rowHeight * CGFloat(datas.count) + 8
        let x: CGFloat = sourceRect.origin.x - (w / 2)
        let y: CGFloat = sourceRect.origin.y - 20 - h - 8 // 8: padding for arrow
        container.frame = CGRect(x: x, y: y, width: w, height: h)
        container.backgroundColor = .c.csfn
        view.addSubview(container)

        // Setup table view
        tableView.dataSource = self
        tableView.delegate = self
        tableView.rowHeight = Self.rowHeight
        tableView.layer.cornerRadius = 8
        //tableView.isScrollEnabled = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.tableFooterView = UIView()
        tableView.register(GiftCountChooseCell.self, forCellReuseIdentifier: Self.cellId)
        container.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 0, bottom: 8, right: 0))
        }

        // 延迟滚动到选中项
        DispatchQueue.main.async {
            self.scrollToSelectedValue()
        }
    }
    
    private func scrollToSelectedValue() {
        guard let selectedValue = selectedValue,
              let selectedIndex = datas.firstIndex(of: selectedValue) else {
            return
        }
        
        let indexPath = IndexPath(row: selectedIndex, section: 0)
        tableView.scrollToRow(at: indexPath, at: .middle, animated: false)
    }

  
    
    deinit{
        dlog("♻️GiftCountChooseController")
    }
}

// MARK: - UITableViewDataSource, UITableViewDelegate

extension GiftCountChooseController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: Self.cellId, for: indexPath) as! GiftCountChooseCell
        let currentValue = datas[indexPath.row]
        cell.countLabel.text = currentValue
        cell.line.isHidden = indexPath.row == datas.count - 1
        
        // 显示选中状态的图标
        cell.selectedIcon.isHidden = currentValue != selectedValue
        
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        let selectedValue = datas[indexPath.row]
        self.selectedValue = selectedValue
        chooseBlock?(selectedValue)
        close()
    }
}
