//
//  YHHKRecordsStayingPersonnelCell.swift
//  galaxy
//
//  Created by alexzzw on 2024/9/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHHKRecordsStayingPersonnelCell: YHResignDocumentCell {
    private static let offsetX: CGFloat = 18
    private static let offsetTop: CGFloat = 8
    private static let offsetBottom: CGFloat = 24
    private static let minimumLineSpacing: CGFloat = 12
    private static let minimumInteritemSpacing: CGFloat = 8
    
    private static let labelToTop: CGFloat = 16
    private static let labelHeight: CGFloat = 20
    
    var selectItemAction: ((YHHKRecordsUserItem) -> Void)?
    var deselectItemAction: ((YHHKRecordsUserItem) -> Void)?
    
    var didHeightChanged: ((CGFloat) -> Void)?
    
    var didFinishLoading: (() -> Void)?

    var collectionData: [YHHKRecordsUserItem] = [] {
        didSet {
            hasFinishedLoading = false
            infoCollectionView.reloadData()
        }
    }
    
    private var hasFinishedLoading = false
    
    private var minWidth: CGFloat {
        return (KScreenWidth - YHHKRecordsStayingPersonnelCell.offsetX * 2 - YHHKRecordsStayingPersonnelCell.minimumInteritemSpacing * 3 - 2 * kMargin) / 4.0
    }
    
    private var maxWidth: CGFloat {
        return (KScreenWidth - YHHKRecordsStayingPersonnelCell.offsetX * 2 - 2 * kMargin)
    }

    static let cellReuseIdentifier = "YHHKRecordsStayingPersonnelCell"
    
    private lazy var asteriskIcon: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "asterisk_icon_6")
        return view
    }()
    
    private lazy var infoTitleLabel: UILabel = {
        let label = UILabel()
        label.font = .PFSC_R(ofSize: 14)
        label.textColor = UIColor(hexString: "#222222")
        return label
    }()
    
    private lazy var bottomLineView: UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    private lazy var layout: YHCollectionViewLeftAlignedFlowLayout = {
        return YHCollectionViewLeftAlignedFlowLayout()
    }()
    
    private lazy var infoCollectionView: UICollectionView = {
        layout.minimumLineSpacing = YHHKRecordsStayingPersonnelCell.minimumLineSpacing
        layout.minimumInteritemSpacing = YHHKRecordsStayingPersonnelCell.minimumInteritemSpacing
        layout.scrollDirection = .vertical
        layout.sectionInset = UIEdgeInsets(top: YHHKRecordsStayingPersonnelCell.offsetTop, left: YHHKRecordsStayingPersonnelCell.offsetX, bottom: YHHKRecordsStayingPersonnelCell.offsetBottom, right: YHHKRecordsStayingPersonnelCell.offsetX)
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.showsVerticalScrollIndicator = false
        collectionView.allowsMultipleSelection = true
        collectionView.isScrollEnabled = false
        collectionView.register(YHHKRecordsPersonnelSelectCell.self, forCellWithReuseIdentifier: YHHKRecordsPersonnelSelectCell.cellReuseIdentifier)
        return collectionView
    }()
    
    private var collectionViewContentSize: CGSize = CGSize.zero {
        didSet {
            if collectionViewContentSize != oldValue {
                infoCollectionView.snp.remakeConstraints { make in
                    make.top.equalTo(infoTitleLabel.snp.bottom)
                    make.left.right.equalToSuperview()
                    make.height.equalTo(collectionViewContentSize.height)
                    make.bottom.equalTo(bottomLineView.snp.top)
                }
                didHeightChanged?(collectionViewContentSize.height + YHHKRecordsStayingPersonnelCell.labelToTop + YHHKRecordsStayingPersonnelCell.labelHeight)
            }
        }
    }

    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")
    }
    
    deinit {
        if infoCollectionView.observationInfo != nil {
            infoCollectionView.removeObserver(self, forKeyPath: "contentSize", context: nil)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        infoCollectionView.collectionViewLayout.invalidateLayout()
    }
    
    func setupCellInfo(title: String?) {
        infoTitleLabel.text = title
    }
    
    func defaultSelectItems(rows: [Int]) {
        rows.forEach { row in
            if collectionData.count > row {
                infoCollectionView.selectItem(at: IndexPath(item: row, section: 0), animated: false, scrollPosition: .left)
            }
        }
    }
}

extension YHHKRecordsStayingPersonnelCell {
    
    private func setupUI() {
        updateCellCorner(.mid)
        subContainerView.addSubview(asteriskIcon)
        subContainerView.addSubview(infoTitleLabel)
        subContainerView.addSubview(bottomLineView)
        subContainerView.addSubview(infoCollectionView)
        
        asteriskIcon.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18)
            make.centerY.equalTo(infoTitleLabel)
            make.width.height.equalTo(6)
        }
        
        infoTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(asteriskIcon.snp.right).offset(2)
            make.top.equalToSuperview().offset(YHHKRecordsStayingPersonnelCell.labelToTop)
            make.height.equalTo(YHHKRecordsStayingPersonnelCell.labelHeight)
        }
        
        bottomLineView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(18)
            make.right.equalToSuperview().offset(-18)
            make.height.equalTo(0.5)
        }
        infoCollectionView.snp.makeConstraints { make in
            make.top.equalTo(infoTitleLabel.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomLineView.snp.top)
        }
        infoCollectionView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        guard keyPath == "contentSize" else {
            return
        }
        collectionViewContentSize = infoCollectionView.contentSize
    }
}

extension YHHKRecordsStayingPersonnelCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return collectionData.count > 0 ? 1 : 0
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return collectionData.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if collectionData.count > indexPath.item, let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHHKRecordsPersonnelSelectCell.cellReuseIdentifier, for: indexPath) as? YHHKRecordsPersonnelSelectCell {
            let data = collectionData[indexPath.item]
            cell.setupCellInfo(data.user_name)
            return cell
        }
        return UICollectionViewCell()
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if collectionData.count > indexPath.item {
            let data = collectionData[indexPath.item]
            let attrString = NSAttributedString(string: data.user_name, attributes: [.font: YHHKRecordsPersonnelSelectCell.labelFont])
            var width = attrString.yh_width(containerHeight: YHHKRecordsPersonnelSelectCell.cellHeight) + 2 * YHHKRecordsPersonnelSelectCell.offsetX
            if width < minWidth {
                width = minWidth
            }
            if width > maxWidth {
                width = maxWidth
            }
            return CGSize(width: width, height: YHHKRecordsPersonnelSelectCell.cellHeight)
            
        }
        return CGSize.zero
    }
    
    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        if indexPath.item == collectionView.numberOfItems(inSection: 0) - 1, !hasFinishedLoading {
            // CollectionView 中的最后一个 cell 即将显示
            hasFinishedLoading = true
            DispatchQueue.main.async {
                self.didFinishLoading?()
            }
        }
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if collectionData.count > indexPath.item {
            let data = collectionData[indexPath.item]
            data.isSelected = true
            selectItemAction?(data)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        if collectionData.count > indexPath.item {
            let data = collectionData[indexPath.item]
            data.isSelected = false
            deselectItemAction?(data)
        }
    }
}
