//
//  CompressSortView.swift
//  PhoneManager
//
//  Created by edy on 2025/4/3.
//

import Foundation
import UIKit
import SnapKit

class CompressSortView: UIView, UITableViewDelegate, UITableViewDataSource {
    
    var currentIndex: Int = 0
    let tableData: [String] = ["Largest", "Smallest", "Newest", "Oldest"]
    var callBack : callBack<Any> = {sortType in}
    
    private var selectedViewBottomConstraint: Constraint?
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tableData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: CompressSortCell = tableView.dequeueReusableCell(withIdentifier: "CompressSortCell", for: indexPath) as! CompressSortCell
        cell.cellTag = indexPath.row
        cell.selectButton.setTitle(tableData[indexPath.row], for: .normal)
        cell.callBack = { [weak self] cellTag in
            guard let self = self else { return }
            self.currentIndex = cellTag as! Int
            self.tableView.reloadData()
        }
        if indexPath.row == currentIndex {
            cell.selectButton.layer.borderWidth = 1.0
            cell.selectButton.setTitleColor(UIColor(red: 0, green: 0.51, blue: 1, alpha: 1), for: .normal)
        } else {
            cell.selectButton.layer.borderWidth = 0
            cell.selectButton.setTitleColor(UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1), for: .normal)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 48 * RScreenW()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(self.backView)
        self.backView.addSubview(self.selectedView)
        self.selectedView.addSubview(self.lineView)
        self.selectedView.addSubview(self.titleLabel)
        self.selectedView.addSubview(self.tableView)
        self.selectedView.addSubview(self.applyButton)
        
        self.backView.snp.makeConstraints { make in
            make.top.left.right.bottom.equalToSuperview()
        }
        
        self.selectedView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(416)
            // 初始时将 selectedView 移到屏幕下方
            self.selectedViewBottomConstraint = make.bottom.equalToSuperview().offset(416).constraint
        }
        
        self.lineView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.width.equalTo(57)
            make.height.equalTo(4)
            make.centerX.equalToSuperview()
        }
        
        self.titleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(self.lineView.snp.bottom).offset(20)
            make.height.equalTo(20)
        }
        
        self.tableView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(self.titleLabel.snp.bottom).offset(4)
            make.height.equalTo(240)
        }
        
        self.applyButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(46)
            make.bottom.equalToSuperview().offset(-46)
        }
        
        // 先显示背景，然后延迟显示弹框
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            UIView.animate(withDuration: 0.1) {
                // 更新约束
                self.selectedViewBottomConstraint?.update(offset: 0)
                self.layoutIfNeeded()
            }
        }
    }
    
    override func removeFromSuperview() {
        UIView.animate(withDuration: 0.2) {
            // 更新约束
            self.backView.backgroundColor = .clear
            self.selectedViewBottomConstraint?.update(offset: 416)
            self.layoutIfNeeded()
        }completion: { _ in
            super.removeFromSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var backView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5000)
        view.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer()
        tap.addTarget(self, action: #selector(backViewClick))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var selectedView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var lineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1)
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let view = UILabel()
        view.text = "Sort by"
        view.textAlignment = .left
        view.textColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
        view.font = UIFont.systemFont(ofSize: 14, weight: .bold)
        return view
    }()
    
    lazy var tableView: UITableView = {
        let view = UITableView()
        view.register(CompressSortCell.classForCoder(), forCellReuseIdentifier: "CompressSortCell")
        view.backgroundColor = .clear
        view.separatorStyle = .none
        view.showsVerticalScrollIndicator = false
        view.delegate = self
        view.dataSource = self
        view.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        if #available(iOS 15.0, *) {
            view.sectionHeaderTopPadding = 0
        }
        return view
    }()
    
    lazy var applyButton: UIButton = {
        let view = UIButton(type: .custom)
        view.setTitle("Apply", for: .normal)
        view.layer.cornerRadius = 8
        view.clipsToBounds = true
        view.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        view.setTitleColor(.white, for: .normal)
        view.addTarget(self, action: #selector(applyAction), for: .touchUpInside)
        return view
    }()
    
    @objc func applyAction() {
        // 传给上层控制器，对照片进行排序
        callBack(currentIndex)
        // 移除自身
        self.removeFromSuperview()
    }
    
    @objc func backViewClick() {
        // 移除自身
        self.removeFromSuperview()
    }
    
}
