//
//  YHPictureReviewManager.swift
//  galaxy
//
//  Created by davidhuangA on 2024/8/6.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

import JXPhotoBrowser
import SDWebImage

class YHPictureReviewManager: NSObject {
    static let shared = YHPictureReviewManager()

    override init() {
        super.init()
    }

    private var curIndex: Int = 0
    private var arrPics: [String] = []
    private var arrPreviewItems: [YHPreviewMediaItem] = []
}

extension YHPictureReviewManager {
    func showNetWorkPicturs(curIndex: Int, arrPicturs: [String]) {
        guard curIndex > -1, arrPicturs.count > 0 else { return }

        self.curIndex = curIndex
        arrPics = arrPicturs

        let browser = YHPictureBrowserViewController()
        browser.numberOfItems = {
            self.arrPics.count
        }

        browser.reloadCellAtIndex = { context in
            if context.index >= self.arrPics.count {
                return
            }
            let string = self.arrPics[context.index]
            guard string.count > 0, let url = URL(string: string) else { return }
            let browserCell = context.cell as? JXPhotoBrowserImageCell
            browserCell?.index = context.index
            let placeholder = UIImage(named: "global_default_image")
            browserCell?.imageView.sd_setImage(with: url, placeholderImage: placeholder, options: [], completed: { _, _, _, _ in
                browserCell?.setNeedsLayout()
            })

            // 添加长按事件
            browserCell?.longPressedAction = { cell, _ in
                self.longPress(cell: cell)
            }
        }

        browser.getImgUrlBlock = { [weak self] index in
            guard let self = self else { return "" }
            if 0 <= index, index < self.arrPics.count {
                return self.arrPics[index]
            }
            return ""
        }

        // 数字样式的页码指示器
        browser.pageIndicator = JXPhotoBrowserNumberPageIndicator()
        browser.pageIndex = self.curIndex
        browser.show()
    }
}

extension YHPictureReviewManager {
    private func longPress(cell: JXPhotoBrowserImageCell) {
        let index = cell.index
        if index < arrPics.count, index > -1 {
            let view = YHLongtapPictureSheetView.sheetView()
            view.myUrl = arrPics[index]
            view.show()
        }
    }
    
    private func longPressMedia(cell: JXPhotoBrowserImageCell) {
        let index = cell.index
        if index < arrPreviewItems.count, index > -1 {
            let view = YHLongtapPictureSheetView.sheetView()
            let item = arrPreviewItems[index]
            if item.type == .image {
                switch item.source {
                case let .remoteURL(url):
                    view.myUrl = url
                    view.show()
                case .localImage:
                    break
                case .localVideoURL:
                    break
                }
            }
        }
    }
}

// MARK: - 新的混合媒体预览方法

extension YHPictureReviewManager {
    /// 显示本地媒体预览（从 YHSelectMediaItem 数组）
    /// - Parameters:
    ///   - curIndex: 当前索引
    ///   - selectMediaItems: 本地媒体项数组
    ///   - deleteCallback: 删除回调 (deletedIndex) -> Void
    func showLocalMedia(curIndex: Int,
                        selectMediaItems: [YHSelectMediaItem],
                        deleteCallback: ((_ deletedIndex: Int) -> Void)? = nil) {
        let previewItems = selectMediaItems.map { YHPreviewMediaItem(from: $0) }
        showPreviewMedia(curIndex: curIndex,
                         previewItems: previewItems,
                         deleteCallback: deleteCallback)
    }

    /// 显示远程媒体预览（从URL字符串数组，自动检测类型）
    /// - Parameters:
    ///   - curIndex: 当前索引
    ///   - urlStrings: URL字符串数组
    ///   - deleteCallback: 删除回调 (deletedIndex) -> Void
    func showRemoteMedia(curIndex: Int,
                         urlStrings: [String],
                         deleteCallback: ((_ deletedIndex: Int) -> Void)? = nil) {
        let previewItems = urlStrings.map { urlString -> YHPreviewMediaItem in
            let type = detectMediaType(from: urlString)
            return YHPreviewMediaItem(remoteURL: urlString, type: type)
        }
        showPreviewMedia(curIndex: curIndex,
                         previewItems: previewItems,
                         deleteCallback: deleteCallback)
    }

    /// 显示混合媒体预览（手动指定每个项目）
    /// - Parameters:
    ///   - curIndex: 当前索引
    ///   - previewItems: 预览媒体项数组
    ///   - deleteCallback: 删除回调 (deletedIndex) -> Void
    func showPreviewMedia(curIndex: Int,
                          previewItems: [YHPreviewMediaItem],
                          deleteCallback: ((_ deletedIndex: Int) -> Void)? = nil) {
        guard curIndex > -1, previewItems.count > 0 else { return }

        self.curIndex = curIndex
        arrPreviewItems = previewItems

        let browser = YHMediaBrowserViewController()
        browser.numberOfItems = { [weak self] in
            guard let self = self else {
                return 0
            }
            return self.arrPreviewItems.count
        }

        // 根据媒体类型返回对应的Cell类
        browser.cellClassAtIndex = { [weak self] index in
            guard let self = self else {
                return JXPhotoBrowserImageCell.self
            }
            guard index < self.arrPreviewItems.count else { return JXPhotoBrowserImageCell.self }
            let previewItem = self.arrPreviewItems[index]
            return previewItem.type == .video ? YHVideoCell.self : JXPhotoBrowserImageCell.self
        }

        browser.reloadCellAtIndex = { [weak self] context in
            guard let self = self else {
                return
            }
            if context.index >= self.arrPreviewItems.count {
                return
            }

            let previewItem = self.arrPreviewItems[context.index]

            if previewItem.type == .video {
                // 视频Cell
                let browserCell = context.cell as? YHVideoCell
                switch previewItem.source {
                case let .remoteURL(urlString):
                    if let url = URL(string: urlString) {
                        browserCell?.loadVideo(from: url)
                    }
                case let .localVideoURL(url):
                    browserCell?.loadVideo(from: url)
                case .localImage:
                    break // 视频不应该是本地图片
                }
            } else {
                // 图片Cell
                let browserCell = context.cell as? JXPhotoBrowserImageCell
                browserCell?.index = context.index
                let placeholder = UIImage(named: "global_default_image")

                switch previewItem.source {
                case let .remoteURL(urlString):
                    if let url = URL(string: urlString) {
                        browserCell?.imageView.sd_setImage(with: url, placeholderImage: placeholder, options: [], completed: { _, _, _, _ in
                            browserCell?.setNeedsLayout()
                        })
                    }
                case let .localImage(image):
                    browserCell?.imageView.image = image
                    browserCell?.setNeedsLayout()
                case .localVideoURL:
                    break // 图片不应该是视频URL
                }

                // 添加长按事件（仅图片）
                browserCell?.longPressedAction = { [weak self] cell, _ in
                    guard let self = self else {
                        return
                    }
                    self.longPressMedia(cell: cell)
                }
            }
        }

        // 视频播放控制
        browser.cellWillAppear = { [weak self] cell, index in
            guard let self = self else {
                return
            }
            if index < self.arrPreviewItems.count {
                let previewItem = self.arrPreviewItems[index]
                if previewItem.type == .video {
                    (cell as? YHVideoCell)?.playVideo()
                }
            }
        }

        browser.cellWillDisappear = { [weak self] cell, index in
            guard let self = self else {
                return
            }
            if index < self.arrPreviewItems.count {
                let previewItem = self.arrPreviewItems[index]
                if previewItem.type == .video {
                    (cell as? YHVideoCell)?.stopVideo()
                }
            }
        }

        // 完善的删除逻辑
        browser.deleteMediaBlock = { [weak self, weak browser] index in
            guard let self = self else {
                return
            }
            // 删除数据
            self.arrPreviewItems.remove(at: index)
            deleteCallback?(index)
            
            // 重新显示浏览器
            if !self.arrPreviewItems.isEmpty {
                browser?.dismiss(animated: false) { [weak self] in
                    guard let self = self else {
                        return
                    }
                    let newIndex = index < self.arrPreviewItems.count ? index : self.arrPreviewItems.count - 1
                    self.showPreviewMedia(curIndex: newIndex, previewItems: self.arrPreviewItems, deleteCallback: deleteCallback)
                }
            } else {
                browser?.dismiss(animated: true)
                self.clearData()
            }
        }
        
        browser.dismissBlock = { [weak self] in
            guard let self = self else {
                return
            }
            self.clearData()
        }

        // 数字样式的页码指示器
        browser.pageIndicator = JXPhotoBrowserNumberPageIndicator()
        browser.pageIndex = self.curIndex
        browser.show()
    }
    
    private func clearData() {
        arrPreviewItems.removeAll()
    }

    /// 根据URL检测媒体类型
    /// - Parameter urlString: URL字符串
    /// - Returns: 媒体类型
    private func detectMediaType(from urlString: String) -> YHMediaType {
        let lowercasedUrl = urlString.lowercased()

        // 视频文件扩展名
        let videoExtensions = ["mp4", "mov", "avi", "mkv", "wmv", "flv", "webm", "m4v"]

        // 检查URL是否包含视频扩展名
        for ext in videoExtensions {
            if lowercasedUrl.contains(".\(ext)") {
                return .video
            }
        }

        // 默认为图片
        return .image
    }
}
