//
//  TSDiyKeyboardVC.swift
//  AIEmoji
//
//  Created by 100Years on 2025/1/21.
//


import JXSegmentedView
class TSWallpaperVC: TSBaseVC {
    
    let segmentedViewH = 30.0
    
    var selectedElementComplete:((DiyStickerModel)->Void)?

    let viewModel = TSWallpaperViewModel()
    lazy var segmentedDataSource: JXSegmentedTitleImageDataSource = {
        let dataSource = JXSegmentedTitleImageDataSource()
        dataSource.normalImageInfos = viewModel.segmentedImageArray
        dataSource.titles = viewModel.segmentedTitleArray
        dataSource.itemWidth = viewModel.itemW
        dataSource.titleImageSpacing = 0
        dataSource.imageSize = CGSize(width: 20, height: 20)
        dataSource.imageSelectedZoomScale = 1.0
        dataSource.itemSpacing = 0
        dataSource.itemWidthSelectedZoomScale = 1.0
        
        dataSource.loadImageClosure = {(imageView, normalImageInfo) in
            imageView.image = UIImage(named: normalImageInfo)
        }
        return dataSource
    }()
    
    //头 view
    lazy var segmentedView: JXSegmentedView = {
        let segmentedView = JXSegmentedView()
        segmentedView.delegate = self
        segmentedView.dataSource = segmentedDataSource
        segmentedView.backgroundColor = "#F1F4F8".uiColor
        segmentedView.cornerRadius = segmentedViewH/2.0
        //配置指示器
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = viewModel.itemW-4
        indicator.indicatorHeight = segmentedViewH-4
        indicator.verticalOffset = 2
        indicator.indicatorColor = .white
        segmentedView.indicators = [indicator]
        
        segmentedView.listContainer = listContainerView
        
        return segmentedView
    }()
    
    
    //显示的 View
    lazy var listContainerView: JXSegmentedListContainerView = {
        let listContainerView = JXSegmentedListContainerView(dataSource: self)
        listContainerView.scrollView.isScrollEnabled = false
        return listContainerView
    }()
    
    
    lazy var saveBtn: UIButton = {
        let saveBtn = UIButton.createButton(title: "Save".localized,backgroundColor: .themeColor,font: .font(size: 12) ,titleColor: .mainBg){ [weak self]  in
            guard let self = self else { return }
            if let image = getCurrentDiyImage(){
                PhotoManagerShared.saveImageToAlbum(image) { success, error in
                    if success {
                        kSavePhotoSuccesswShared.show(atView: self.view)
                    }else{
                        debugPrint(error)
                    }
                }
            }
        }
        saveBtn.layer.cornerRadius = 13
        
        return saveBtn
    }()
    
    lazy var segmentedToolView: UIView = {
        let segmentedToolView = UIView()
        segmentedToolView.backgroundColor = .white
        return segmentedToolView
    }()
    
    lazy var colseBtn: UIButton = {
        let colseBtn = UIButton.createButton(image: UIImage(named:"down_arrow_white")){ [weak self]  in
            guard let self = self else { return }
            pop()
        }
        return colseBtn
    }()
    
    lazy var previewBtn: UIButton = {
        let previewBtn = UIButton.createButton(image: UIImage(named:"preview")){ [weak self]  in
            guard let self = self else { return }
            if let image = getCurrentDiyImage(),let color = getCurrentDiyPreviewColor(){
                let previewVC = TSWallpaperPreviewVC(image: image, tintColor: color)
                kPresentModalVC(target: self, modelVC: previewVC)
            }else{
                TSToastShared.showToast(text: "Data missing")
            }
        }
        return previewBtn
    }()
    
    override func createView() {
        setNavBarViewHidden(true)
        edgesForExtendedLayout = []
        contentView.snp.updateConstraints { make in
            make.top.equalTo(k_Height_StatusBar)
        }

        contentView.addSubview(listContainerView)
        listContainerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        

        contentView.addSubview(segmentedToolView)
        segmentedToolView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.height.equalTo(46)
            make.bottom.equalTo(-200-k_Height_safeAreaInsetsBottom())
        }
        
        contentView.addSubview(colseBtn)
        colseBtn.snp.updateConstraints { make in
            make.top.equalTo(10)
            make.width.equalTo(24)
            make.height.equalTo(24)
            make.leading.equalTo(16)
        }
        
        contentView.addSubview(previewBtn)
        previewBtn.snp.updateConstraints { make in
            make.bottom.equalTo(segmentedToolView.snp.top).offset(-16)
            make.width.equalTo(24)
            make.height.equalTo(24)
            make.leading.equalTo(16)
        }
        

        createPageView()
    }
    

    func createPageView() {
        segmentedToolView.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(viewModel.segmentedViewW)
            make.height.equalTo(segmentedViewH)
        }
        
        segmentedToolView.addSubview(saveBtn)
        saveBtn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.width.equalTo(68)
            make.height.equalTo(26)
            make.trailing.equalTo(-11)
        }
        
        kDelayMainShort {
            self.segmentedToolView.cornersRound(radius: 20, corner: [.topLeft,.topRight])
        }
    }
}


extension TSWallpaperVC {
    func getCurrentDiyImage() -> UIImage? {
        if let vc = listContainerView.validListDict[segmentedView.selectedIndex],
           let keyVC = vc as? TSDiyKeyboardViewVC,
           let image = keyVC.getDiyImage(){
            return image
        }
        return nil
    }
    
    func getCurrentDiyPreviewColor() -> UIColor? {
        if let model = viewModel.templateModels.safeObj(At: segmentedView.selectedIndex) {
            return model.textColor?.uiColor
        }
        return nil
    }
}

extension TSWallpaperVC: JXSegmentedViewDelegate {
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        navigationController?.interactivePopGestureRecognizer?.isEnabled = (segmentedView.selectedIndex == 0)
    }
}

extension TSWallpaperVC: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        if let titleDataSource = segmentedView.dataSource as? JXSegmentedBaseDataSource {
            return titleDataSource.dataSource.count
        }
        return 0
    }

    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        return TSDiyKeyboardViewVC(templateModel: viewModel.templateModels.safeObj(At: index) ?? DiyPaperTemplateModel(),
                                   keyBoardModel: viewModel.keyStickerModels.safeObj(At: index) ?? DiyStickerCategory())
    }
}


