//
//  TSAIChatHistoryVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/12.
//

import SwipeCellKit

class TSAIChatHistoryVC: TSBaseVC {
    
    lazy var viewModel : TSAIChatHistoryVM = {
        let viewModel = TSAIChatHistoryVM()
        return viewModel
    }()
    
    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.itemSize = CGSize(width: k_ScreenWidth-32, height: 74)
        layout.minimumInteritemSpacing = 10.0
        layout.minimumLineSpacing = 18.0
        layout.headerReferenceSize = CGSizeMake(k_ScreenWidth, 48)
        return layout
    }()
    
    lazy var collectionView: UICollectionView = {
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        collectionView.register(TSAIChatHistoryCell.self, forCellWithReuseIdentifier: TSAIChatHistoryCell.cellID)
        collectionView.register(TSAIChatHistorySectionHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: TSAIChatHistorySectionHeaderView.reuseIdentifier)
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        return collectionView
    }()
    
    lazy var pageNullView: TSPageNullView = {
        let pageNullView = TSPageNullView()
        pageNullView.isHidden = true
        return pageNullView
    }()
    
    var deleteAllBtn:UIButton = UIButton()
    
    override func createView() {
        
        addNormalNavBarView()
        setPageTitle("History".localized)
        
        deleteAllBtn = setNavigationItem("", imageName: "delete_white", direction: .right, action: #selector(deleteAll))
        
        contentView.addSubview(pageNullView)
        contentView.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    override func dealThings() {
        updateListView()
    }
    

    func updateListView(){
        pageNullView.isHidden = viewModel.historyModelChatList.count > 0 ? true : false
        deleteAllBtn.isHidden = !pageNullView.isHidden
        collectionView.reloadData()
    }
    
    @objc func deleteAll(){
        showCustomAlert(message: "Are you sure to delete".localized, deleteHandler:  { [weak self]  in
            guard let self = self else { return }
            viewModel.deleteAll()
            self.viewModel.historyModelChatList.removeAll()
            self.updateListView()
        })
    }
}

extension TSAIChatHistoryVC: UICollectionViewDataSource ,UICollectionViewDelegate {
    
    public func numberOfSections(in collectionView: UICollectionView) -> Int {
        return viewModel.historyModelChatList.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let sectionModel = viewModel.historyModelChatList.safeObj(At: section) {
            return sectionModel.chatList.count
        }
        return 0
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TSAIChatHistoryCell.cellID, for: indexPath)
        
        if let sectionModel = viewModel.historyModelChatList.safeObj(At: indexPath.section),
            let itemModel = sectionModel.chatList.safeObj(At: indexPath.item),
           let cell = cell as? TSAIChatHistoryCell
        {
            cell.delegate = self
            cell.model = itemModel
        }
        
        return cell
    }

    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let sectionModel = viewModel.historyModelChatList.safeObj(At: indexPath.section),
           let itemModel = sectionModel.chatList.safeObj(At: indexPath.item)
        {
            
            let chatVC = TSAIChatContainerVC()
            chatVC.viewModel.uiStyle = .history
            chatVC.viewModel.dbAIChatList = itemModel
            chatVC.deleteBlock = { [weak self]  in
                guard let self = self else { return }
                //删除 UI 层的 cell
                sectionModel.chatList.remove(at: indexPath.item)
                if sectionModel.chatList.count == 0 {
                    self.viewModel.historyModelChatList.remove(at: indexPath.section)
                }
                updateListView()
                
            }
            self.navigationController?.pushViewController(chatVC, animated: true)
        }
    }
    
    
    public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if let sectionModel = viewModel.historyModelChatList.safeObj(At: indexPath.section) {
            if kind == UICollectionView.elementKindSectionHeader {
                if let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: TSAIChatHistorySectionHeaderView.reuseIdentifier, for: indexPath) as? TSAIChatHistorySectionHeaderView {
                    header.titleLabel.text = sectionModel.title
                    return header
                }
            }
        }
        return TSAIChatHistorySectionHeaderView()
    }
}

extension TSAIChatHistoryVC: SwipeCollectionViewCellDelegate {
    
    func collectionView(_ collectionView: UICollectionView, editActionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
        guard orientation == .right else { return nil }

        // 删除操作
        let deleteAction = SwipeAction(style: .destructive, title: nil) {[weak self] action, indexPath in
            guard let self = self else { return }
            showCustomAlert(message: "Are you sure to delete".localized, deleteHandler:  {
                if let sectionModel = self.viewModel.historyModelChatList.safeObj(At: indexPath.section),
                let itemModel = sectionModel.chatList.safeObj(At: indexPath.item){
                    sectionModel.chatList.remove(at: indexPath.item)
                    itemModel.delete()
                
                    if sectionModel.chatList.count == 0 {
                        self.viewModel.historyModelChatList.remove(at: indexPath.section)
                    }
                    
                    self.updateListView()
                }
            })
        }
        
        deleteAction.backgroundColor = "#E83E3E".uiColor
        deleteAction.image = UIImage(named: "delete_white")
        return [deleteAction]
    }
    
    func collectionView(_ collectionView: UICollectionView, editActionsOptionsForItemAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeOptions {
        var options = SwipeOptions()
//        options.expansionStyle = .destructive(automaticallyDelete: false) // 完全滑动时是否自动触发操作
        options.transitionStyle = .border // 滑动动画样式
        return options
    }
    
}
class TSAIChatHistoryCell: SwipeCollectionViewCell {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        creatUI()
    }
    
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    
    static let cellID = "TSAIChatHistoryCell"
    
    lazy var titleLabel: UILabel = {
        let titleLabel = UILabel.createLabel( font:.font(size: 16.0),textColor: .white)
        return titleLabel
    }()
    
    lazy var infoLabel: UILabel = {
        let titleLabel = UILabel.createLabel( font:.font(size: 14.0),textColor: .white.withAlphaComponent(0.4))
        return titleLabel
    }()
    
    
    var model:TSDBAIChatList?{
        didSet{
            if let dbMessage = model?.messages.first {
                titleLabel.text = dbMessage.kindValue
                infoLabel.text = dbMessage.sentDate.dateTimeString
            }
        }
    }
    
    func creatUI() {

        backgroundColor = "#333333".uiColor
        cornerRadius = 16.0
        
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(16)
        }

        contentView.addSubview(infoLabel)
        infoLabel.snp.makeConstraints { make in
            make.top.equalTo(44)
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.height.equalTo(14)
        }
    }
}

class TSAIChatHistorySectionHeaderView: UICollectionReusableView {
    static let reuseIdentifier = "TSAIChatHistorySectionHeaderView"
    
    let titleLabel: UILabel = {
        let label = UILabel.createLabel(text: "",font: .font(size: 16),textColor: .white)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.leading.equalTo(16)
            make.trailing.equalTo(-16)
            make.centerY.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
