//
//  SessionListView.swift

//
//  Created by Leon on 2025/8/13.
//

import UIKit
import SwipeCellKit
import Combine

protocol SessionListViewDelegate: NSObjectProtocol {
    func selectRow(indexPath: IndexPath)
    /// 删除单条消息
    func deleteRow(indexPath: IndexPath)
}

class SessionListView: UIView{
    var tableView: UITableView!
    weak var delegate : SessionListViewDelegate?
    
    // -- Data
    var cellModels = [V2NIMConversation]()
    var msgStat: MessageStat?
    
    private var cancellables = Set<AnyCancellable>()
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
        setupData()
        setupEvent()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupViews() {
        tableView = {
            let v = UITableView(frame: .zero, style: .plain)
            v.separatorStyle = .none
            v.delegate = self
            v.dataSource = self
            v.estimatedRowHeight = 72
            v.backgroundColor = .clear
            v.contentInsetAdjustmentBehavior = .never
            v.contentInset = UIEdgeInsets(top: 8, left: 0, bottom: UIWindow.safeAreaBottom + 16, right: 0)
            if #available(iOS 15.0, *) {
                v.sectionHeaderTopPadding = 0
            }
            addSubview(v)
            v.snp.makeConstraints { make in
                make.leading.trailing.bottom.equalToSuperview()
                make.top.equalToSuperview()
            }
            return v
        }()
        
        tableView.register(SessionListCell.self, forCellReuseIdentifier: "SessionListCell")
        tableView.register(SessionNoticeCell.self, forCellReuseIdentifier: "SessionNoticeCell")

    }
    
    
    
    private func setupData(){
        
    }
    
    private func setupEvent(){
        IMManager.shared.$noticeStat.sink {[weak self] stat in
            self?.config(stat)
        }.store(in: &cancellables)
    }
    
    private func config(_ stat: MessageStat?){
        msgStat = stat
        tableView.reloadData()
    }
}

extension SessionListView: UITableViewDelegate, UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0{
            return 1
        }
        return cellModels.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "SessionNoticeCell", for: indexPath) as! SessionNoticeCell
            cell.config(msgStat)
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "SessionListCell", for: indexPath) as! SessionListCell
        let conversation = cellModels[indexPath.row]
        cell.config(conversation)
        cell.delegate = self
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let vc = SessionController()
//        viewController()?.navigationController?.pushViewController(vc, animated: true)
        delegate?.selectRow(indexPath: indexPath)
    }
    
    
}


extension SessionListView: SwipeTableViewCellDelegate {
    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeCellKit.SwipeActionsOrientation) -> [SwipeCellKit.SwipeAction]? {
        guard orientation == .right else { return nil }
        
        let deleteAction = SwipeAction(style: .default, title: nil) { [weak self] cellAction, _ in
            
            #warning("to do, 点击取消或者删除，cell没有恢复原状")
            
            let alert = Alert(title: "Tips", text: "Are you sure to delete the chat")
            let action1 = AlertAction(title: "Delete", actionStyle: .destructive) {
                self?.delegate?.deleteRow(indexPath: indexPath)
            }
            let action2 = AlertAction(title: "Cancel", actionStyle: .cancel)
            alert.addAction(action1)
            alert.addAction(action2)
            alert.show()

            cellAction.fulfill(with: .reset)
//            dlog("删除了")
//            self?.delegate?.deleteRow(indexPath: indexPath)
        }
        
        deleteAction.backgroundColor = .c.cin
        deleteAction.title = "Delete"
        return [deleteAction]
    }
    
    func collectionView(_ collectionView: UICollectionView, editActionsOptionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
        var options = SwipeOptions()
        options.expansionStyle = .fill
        // options.transitionStyle = .border
        return options
    }
    
}
