//
//  KeyboardExchangeView.swift
//  AiKeyboard
//
//  Created by Destiny on 2025/4/28.
//

import UIKit

protocol KeyboardExchangeViewDelegate: NSObjectProtocol {
    
    func exchangeViewBackClickAction()
    
    func exchangeViewSaveClickAction(keyboardList: [KeyboardModel], success: @escaping (() -> ()))
}

class KeyboardExchangeView: UIView {
    
    struct UX {
        static let cellWidth = (KeyboardConst.kb_kScreenW - 42.0) / 3.0
        static let cellHeight = 79.0
    }
    
    weak var delegate: KeyboardExchangeViewDelegate?
    
    var keyboardList: [KeyboardModel]? {
        didSet {
            self.collectionView.reloadData()
        }
    }
    
    lazy var backBtn: UIButton = {
        
        let btn = UIButton()
        btn.setImage(UIImage(named: "keyboard_back_btn"), for: .normal)
        btn.layer.shadowOffset = CGSize(width: 0, height: 0)
        btn.layer.shadowColor = UIColor.hexStringColor(hexString: "#000000", alpha: 0.12).cgColor
        btn.layer.shadowRadius = 6.1
        btn.addTarget(self, action: #selector(backBtnClickAction), for: .touchUpInside)
        return btn
    }()
    
    lazy var collectionView: UICollectionView = {
            
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.scrollDirection = .vertical
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        
        collectionView.dataSource = self
        collectionView.delegate = self
        
        collectionView.showsVerticalScrollIndicator = false
        collectionView.bounces = false
        
        collectionView.register(KeyboardExchangeCell.self, forCellWithReuseIdentifier: KeyboardExchangeCell.reuseIdentifier())
        
        return collectionView
    }()
    
    lazy var saveBtn: UIButton = {
        
        let btn = UIButton()
        
        if let image = UIImage.gradient([.hexStringColor(hexString: "#7D46FC"), .hexStringColor(hexString: "#BC87FF")], size: CGSize(width: 220, height: 40), radius: 22, locations: [0,1], direction: .horizontal) {
            
            btn.setBackgroundImage(image, for: .normal)
        }
        
        btn.setTitle("保存", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 14, weight: .medium)
        
        btn.addTarget(self, action: #selector(saveBtnClickAction), for: .touchUpInside)
        
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension KeyboardExchangeView {
    
    @objc func backBtnClickAction() {
        delegate?.exchangeViewBackClickAction()
//        self.removeFromSuperview()
    }
    
    @objc func saveBtnClickAction() {
        
        if let keyboardList = self.keyboardList {
            delegate?.exchangeViewSaveClickAction(keyboardList: keyboardList) {
//                self.removeFromSuperview()
            }
        }
    }
}

extension KeyboardExchangeView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.keyboardList?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KeyboardExchangeCell.reuseIdentifier(), for: indexPath) as! KeyboardExchangeCell
        if let model = self.keyboardList?[indexPath.row] {
            cell.config(model: model)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        for i in 0..<(self.keyboardList?.count ?? 0) {
            self.keyboardList?[i].isChoose = false
        }
        self.keyboardList?[indexPath.row].isChoose = true
        self.collectionView.reloadData()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        return CGSize(width: UX.cellWidth, height: UX.cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 9
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: KeyboardConst.kb_kScreenW, height: 45)
    }
}

extension KeyboardExchangeView {
    
    func initUI() {
        
        self.addSubview(backBtn)
        backBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 32, height: 32))
            make.top.equalTo(15)
            make.left.equalTo(12)
        }
        
        self.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(12)
            make.right.equalTo(-12)
            make.top.equalTo(backBtn.snp.bottom).offset(12)
            make.bottom.equalTo(0)
        }
        
        self.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: 220, height: 40))
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-12)
        }
    }
}
