//
//  AdvTipDeleteView.swift
//  PhoneManager
//
//  Created by edy on 2025/4/21.
//

import Foundation
import SnapKit

enum TipDeleteType {
    case deletePhotosMore
    case deletePhotoOne
    case deleteVideosMore
    case deleteVideoOne
}

struct AdvTipModel {
    let titleText: String
    let detailTitleText: String
    let showLessButton: Bool
    let deleteMoreText: String
    let deleteLessText:String
    
    init(titleText: String, detailTitleText: String, showLessButton: Bool, deleteMoreText: String, deleteLessText: String) {
        self.titleText = titleText
        self.detailTitleText = detailTitleText
        self.showLessButton = showLessButton
        self.deleteMoreText = deleteMoreText
        self.deleteLessText = deleteLessText
    }
}

class AdvTipDeleteView : UIView {
    
    var deleteButtonClickCallback : (Bool,Int)->Void = {isMore,count in }
    
    var deleteType : TipDeleteType?
    
    // 默认免费删除
    var freeDeleteCount : Int = 0
    
    
    var dataSource : [AssetModel] = []
    
    var tipDeleteModel : AdvTipModel = AdvTipModel(titleText: "", detailTitleText: "", showLessButton: false, deleteMoreText: "", deleteLessText: "")
    
    
    private var heightConstraint: Constraint?
    
    private var centerYConstraint: Constraint?
   
    
   
    lazy var tipView : UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.clipsToBounds = true
        view.layer.cornerRadius = 12
        return view
    }()
    
    lazy var closeButton : UIButton = {
        let view = UIButton(type: .custom)
        view.setImage(UIImage(named: "icon_close_pop_purple"), for: .normal)
        view.addTarget(self, action: #selector(closeButtonAction), for: .touchUpInside)
        return view
    }()
    
    lazy var tipTitle : UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        view.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        view.textColor = UIColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1)
        view.textAlignment = .center
        return view
    }()
    
    lazy var tipDetailTitle : UILabel = {
        let view = UILabel()
        view.numberOfLines = 0
        view.font = UIFont.systemFont(ofSize: 14, weight: .regular)
        view.textColor = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
        view.textAlignment = .center
        return view
    }()
    
    lazy var collectionView : UICollectionView = {
        let layout = CenteredHorizontalCollectionViewLayout()
        layout.scrollDirection = .horizontal
        layout.minimumInteritemSpacing = 8
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(ImageCell.self, forCellWithReuseIdentifier: ImageCell.reuseIdentifier)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.backgroundColor = .clear
        return collectionView
    }()
    
    
    lazy var deleteMoreButton : UIButton = {
        let view = UIButton(type: .custom)
        view.backgroundColor = UIColor(red: 0, green: 0.51, blue: 1, alpha: 1)
        view.setTitleColor(.white, for: .normal)
        view.clipsToBounds = true
        view.layer.cornerRadius = 24
        view.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        view.setImage(UIImage(named: "ic_ad_pop"), for: .normal)
        
        // 设置间距为 8
        let spacing: CGFloat = 8
        // 获取图片和文字的大小
        let imageSize = view.imageView?.image?.size ?? .zero
        let titleSize = view.titleLabel?.intrinsicContentSize ?? .zero
        // 计算 imageEdgeInsets 和 titleEdgeInsets
        view.imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2, bottom: 0, right: spacing / 2)
        view.titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: -spacing / 2)
        
        view.addTarget(self, action: #selector(deleteMoreButtonSelect), for: .touchUpInside)
        return view
    }()
    
    
    lazy var deleteLessButton : UIButton = {
        let view = UIButton(type: .custom)
        view.backgroundColor = .clear
        view.setTitleColor(UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1), for: .normal)
        view.clipsToBounds = true
        view.layer.cornerRadius = 24
        view.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .bold)
        view.addTarget(self, action: #selector(deleteLessButtonSelect), for: .touchUpInside)
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
//        self.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5000)
        self.addSubview(self.tipView)
        self.tipView.addSubview(self.closeButton)
        self.tipView.addSubview(self.tipTitle)
        self.tipView.addSubview(self.tipDetailTitle)
        
        self.tipView.addSubview(self.collectionView)
        self.tipView.addSubview(self.deleteMoreButton)
        self.tipView.addSubview(self.deleteLessButton)
        
        
        
        self.tipView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            centerYConstraint = make.centerY.equalToSuperview().offset(self.height + 205).constraint
            make.width.equalTo(345)
            heightConstraint = make.height.equalTo(410).constraint
        }
        
        self.closeButton.snp.makeConstraints { make in
            make.top.equalTo(20)
            make.right.equalTo(-20)
            make.width.height.equalTo(28)
        }
        self.tipTitle.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(229)
            make.height.equalTo(56)
            make.top.equalToSuperview().offset(52)
        }
        
        self.tipDetailTitle.snp.makeConstraints { make in
            make.top.equalTo(self.tipTitle.snp.bottom).offset(8)
            make.width.equalTo(305)
            make.height.equalTo(40)
            make.centerX.equalToSuperview()
        }
        self.collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.tipDetailTitle.snp.bottom).offset(16)
            make.height.equalTo(104)
        }
        self.deleteMoreButton.snp.makeConstraints { make in
            make.top.equalTo(self.collectionView.snp.bottom).offset(16)
            make.width.equalTo(305)
            make.height.equalTo(48)
            make.centerX.equalToSuperview()
        }
        self.deleteLessButton.snp.makeConstraints { make in
            make.top.equalTo(self.deleteMoreButton.snp.bottom).offset(4)
            make.width.equalTo(305)
            make.height.equalTo(48)
            make.centerX.equalToSuperview()
        }
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func removeFromSuperview() {
        UIView.animate(withDuration: AniDuration) {
            // 更新约束
            self.backgroundColor = .clear
            self.centerYConstraint?.update(offset: self.height + 205)
            self.layoutIfNeeded()
        }completion: { _ in
            super.removeFromSuperview()
        }
    }
    
}

extension AdvTipDeleteView : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func getOtherInfoByType(type : PhotsFileType) {
        
        // 首先获取第一个button显示的内容
        let photosCount = self.dataSource.count > 25 ? 25 : self.dataSource.count
        let deleteButtonTitle = "Delete \(photosCount) \(type.rawValue)"
        
        var deleteLessText = ""
        if type == .videos || type == .SimilarVideos {
            deleteLessText = "Delete Only \(self.freeDeleteCount) Videos"
        }else {
            deleteLessText = "Delete Only \(self.freeDeleteCount) Photos"
        }
        
        
        switch self.deleteType {
        case .deletePhotosMore:
            self.tipDeleteModel =  AdvTipModel.init(
                titleText: "Watch a rewarded ad to delete photos",
                detailTitleText: "You need to watch an ad to delete 25 photos with the free version.",
                showLessButton: true,
                deleteMoreText: deleteButtonTitle, deleteLessText: deleteLessText)
        case .deletePhotoOne:
            self.tipDeleteModel = AdvTipModel.init(
                titleText: "Watch a rewarded ad to delete photos",
                detailTitleText: "You need to watch an ad to delete 25 photos with the free version.",
                showLessButton: false,
                deleteMoreText: deleteButtonTitle, deleteLessText: "")
        case .deleteVideosMore:
            self.tipDeleteModel = AdvTipModel.init(
                titleText: "Watch a rewarded ad to delete videos",
                detailTitleText: "You need to watch an ad to delete 25 videos with the free version.",
                showLessButton: true,
                deleteMoreText: deleteButtonTitle, deleteLessText: deleteLessText)
        case .deleteVideoOne:
            self.tipDeleteModel = AdvTipModel.init(
                titleText: "Watch a rewarded ad to delete videos",
                detailTitleText: "You need to watch an ad to delete 25 videos with the free version.",
                showLessButton: false,
                deleteMoreText: deleteButtonTitle, deleteLessText: "")
        case .none:
            self.tipDeleteModel = AdvTipModel.init(
                titleText: "",
                detailTitleText: "",
                showLessButton: false,
                deleteMoreText: deleteButtonTitle, deleteLessText: "")
        }
        
        DispatchQueue.main.async {
            self.tipTitle.text = self.tipDeleteModel.titleText
            self.tipDetailTitle.text = self.tipDeleteModel.detailTitleText
            self.deleteMoreButton.setTitle(self.tipDeleteModel.deleteMoreText, for: .normal)
            self.deleteLessButton.setTitle(self.tipDeleteModel.deleteLessText, for: .normal)
        }
        // 更新页面
        updateCurrentPageStatus()
    }
    
    func updateCurrentPageStatus(){
        
        DispatchQueue.main.async {
            if self.tipDeleteModel.showLessButton == true {
                self.deleteLessButton.isHidden = false
                self.heightConstraint?.update(offset: 410)
            }else{
                self.deleteLessButton.isHidden = true
                self.heightConstraint?.update(offset: 360)
            }
            
            // 先显示背景，然后延迟显示弹框
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
                
                UIView.animate(withDuration: AniDuration) {
                    // 更新约束
                    self.centerYConstraint?.update(offset: 0)
                    self.layoutIfNeeded()
                }
            }
        }
    }
    
    
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return dataSource.count > 25 ? 25 : dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageCell.reuseIdentifier, for: indexPath) as! ImageCell
        //        // 这里重新写一个异步方法去加载图片
        //        Task {
        //            if let image = await PhotoAndVideoMananger.mananger.getImageByIdent(identifier: self.dataSource![indexPath.item].localIdentifier) {
        //                cell.imageView.image = image
        //            }
        //        }
        
        // 最多25张使用同步
        if let image = PhotoManager.shared.getImageFromAssetID(id: self.dataSource[indexPath.item].localIdentifier) {
            cell.imageView.image = image
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 104, height: 104)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    
    
    @objc func closeButtonAction(){
        deleteButtonClickCallback(false,-10)
        self.removeFromSuperview()
    }
    
    @objc func deleteMoreButtonSelect() {
        let photosCount = self.dataSource.count > 25 ? 25 : self.dataSource.count
        deleteButtonClickCallback(true,photosCount)
        self.removeFromSuperview()
        
    }
    @objc func deleteLessButtonSelect() {
        deleteButtonClickCallback(false,self.freeDeleteCount)
        self.removeFromSuperview()
    }
    
}



class ImageCell: UICollectionViewCell {
    static let reuseIdentifier = "ImageCell"
    let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.layer.cornerRadius = 12
        return imageView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(imageView)
        imageView.frame = contentView.bounds
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class CenteredHorizontalCollectionViewLayout: UICollectionViewFlowLayout {
    private var cachedAttributes: [UICollectionViewLayoutAttributes] = []
    private var contentWidth: CGFloat = 0

    override func prepare() {
        super.prepare()
        guard let collectionView = collectionView else { return }

        cachedAttributes.removeAll()
        contentWidth = 0

        let numberOfItems = collectionView.numberOfItems(inSection: 0)
        var runningOffset: CGFloat = 0

        for item in 0..<numberOfItems {
            let indexPath = IndexPath(item: item, section: 0)
            if let attributes = layoutAttributesForItem(at: indexPath) {
                if cachedAttributes.count > 0 {
                    runningOffset += minimumInteritemSpacing
                }
                attributes.frame.origin.x = runningOffset
                cachedAttributes.append(attributes)
                runningOffset += attributes.frame.width
                contentWidth += attributes.frame.width + minimumInteritemSpacing
            }
        }

        contentWidth -= minimumInteritemSpacing
        contentWidth += sectionInset.left + sectionInset.right

        let collectionViewWidth = collectionView.bounds.width
        var offsetX: CGFloat = 0
        if contentWidth < collectionViewWidth {
            offsetX = (collectionViewWidth - contentWidth) / 2
        }

        runningOffset = offsetX + sectionInset.left
        for attribute in cachedAttributes {
            attribute.frame.origin.x = runningOffset
            runningOffset += attribute.frame.width + minimumInteritemSpacing
        }
    }

    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        var visibleAttributes: [UICollectionViewLayoutAttributes] = []
        for attributes in cachedAttributes {
            if attributes.frame.intersects(rect) {
                visibleAttributes.append(attributes)
            }
        }
        return visibleAttributes
    }

    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes
    }

    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }

    override var collectionViewContentSize: CGSize {
        guard let collectionView = collectionView else { return .zero }
        let collectionViewWidth = collectionView.bounds.width
        if contentWidth < collectionViewWidth {
            return CGSize(width: collectionViewWidth, height: collectionView.bounds.height)
        }
        return CGSize(width: contentWidth, height: collectionView.bounds.height)
    }
}
    
    
