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

import UIKit

class YHCategoryDropdownView: UIView {
    // MARK: - UI Components
    private lazy var mainButton: UIButton = {
        let button = UIButton(type: .custom)
        button.backgroundColor = UIColor(white: 0, alpha: 0.5)
        button.layer.cornerRadius = 4
        
        // 设置箭头图标
        let image = UIImage(named: "icon_arrow_down")
        button.setImage(image, for: .normal)
        button.tintColor = .white
        
        button.addTarget(self, action: #selector(toggleDropdown), for: .touchUpInside)
        return button
    }()
    
    private lazy var dropdownTableView: UITableView = {
        let tableView = UITableView()
        tableView.backgroundColor = UIColor(white: 0, alpha: 0.5)
        tableView.layer.cornerRadius = 4
        tableView.separatorStyle = .none
        tableView.isScrollEnabled = false
        tableView.register(YHDropCategoryCell.self, forCellReuseIdentifier: "YHDropCategoryCell")
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    // MARK: - Properties
    private var categories: [String] = []
    private var isExpanded = false
    private var selectedIndex = 0
    var onSelect: ((String) -> Void)?
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        addSubview(mainButton)
        addSubview(dropdownTableView)
        
        mainButton.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(36)
        }
        
        dropdownTableView.snp.makeConstraints { make in
            make.top.equalTo(mainButton.snp.bottom).offset(1)
            make.left.right.equalTo(mainButton)
            make.height.equalTo(0)
        }
        
        dropdownTableView.isHidden = true
    }
    
    // MARK: - Public Methods
    func configure(with categories: [String]) {
        self.categories = categories
        dropdownTableView.reloadData()
    }
    
    // MARK: - Private Methods
    @objc private func toggleDropdown() {
        isExpanded.toggle()
        
        let tableHeight = CGFloat(categories.count) * 36
        
        // 更新箭头方向
        UIView.animate(withDuration: 0.3) {
            self.mainButton.imageView?.transform = self.isExpanded ?
                CGAffineTransform(rotationAngle: .pi) : .identity
        }
        
        // 展开/收起动画
        dropdownTableView.isHidden = false
        dropdownTableView.snp.updateConstraints { make in
            make.height.equalTo(self.isExpanded ? tableHeight : 0)
        }
        
        UIView.animate(withDuration: 0.3, animations: {
            self.layoutIfNeeded()
            self.dropdownTableView.alpha = self.isExpanded ? 1 : 0
        }) { _ in
            self.dropdownTableView.isHidden = !self.isExpanded
        }
    }
}

// MARK: - UITableViewDelegate & DataSource
extension YHCategoryDropdownView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return categories.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "YHDropCategoryCell", for: indexPath) as? YHDropCategoryCell else {
            return UITableViewCell()
        }
        cell.titleLabel.text = categories[indexPath.row]
        cell.isSelected = indexPath.row == selectedIndex
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 36
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectedIndex = indexPath.row
        onSelect?(categories[indexPath.row])
        toggleDropdown()
        tableView.reloadData()
    }
}

// MARK: - CategoryCell
class YHDropCategoryCell: UITableViewCell {
    let titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 14)
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        backgroundColor = .clear
        selectionStyle = .none
        
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-12)
        }
    }
    
    override var isSelected: Bool {
        didSet {
            backgroundColor = isSelected ? UIColor(white: 1, alpha: 0.1) : .clear
        }
    }
}
