//
//  TSPhotoPickerManager.swift
//  AIEmoji
//
//  Created by 100Years on 2025/2/25.
//

import UIKit
import PhotosUI

class TSPhotoPickerManager: NSObject {
    
    // MARK: - Properties
    private weak var viewController: UIViewController?
    private var completionHandler: ((UIImage?) -> Void)?
    
    // MARK: - Initializers
    init(viewController: UIViewController) {
        self.viewController = viewController
    }
    
    // MARK: - Public Methods
    /// 打开照片选择器，单选一张照片
    func pickSinglePhoto(completion: @escaping (UIImage?) -> Void) {
        self.completionHandler = completion
        
        // 检查相册权限
        checkPhotoLibraryPermission { [weak self] authorized in
            guard let self = self else { return }
            if authorized {
                self.openPhotoPicker()
            } else {
                self.showPermissionAlert()
            }
        }
    }
    
    // MARK: - Private Methods
    /// 检查相册权限
    private func checkPhotoLibraryPermission(completion: @escaping (Bool) -> Void) {
        let status = PHPhotoLibrary.authorizationStatus()
        switch status {
        case .authorized:
            completion(true)
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { newStatus in
                DispatchQueue.main.async {
                    completion(newStatus == .authorized)
                }
            }
        default:
            completion(false)
        }
    }
    
    /// 打开照片选择器
    private func openPhotoPicker() {
        if #available(iOS 14, *) {
            var configuration = PHPickerConfiguration(photoLibrary: .shared())
            configuration.selectionLimit = 1 // 只能选择一张照片
            configuration.filter = .images // 只显示照片，不显示视频
            configuration.preferredAssetRepresentationMode = .current // 使用高质量图片
            
            let picker = PHPickerViewController(configuration: configuration)
            picker.delegate = self
            viewController?.present(picker, animated: true, completion: nil)
        } else {
            // iOS 14 以下使用旧的 UIImagePickerController
            let imagePicker = UIImagePickerController()
            imagePicker.sourceType = .photoLibrary
            imagePicker.delegate = self
            imagePicker.mediaTypes = ["public.image"] // 只选择照片
            viewController?.present(imagePicker, animated: true, completion: nil)
        }
    }
    
    /// 显示权限提示
    private func showPermissionAlert() {
        let alert = UIAlertController(
            title: "相册权限未开启",
            message: "请在设置中开启相册权限以选择照片",
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
        alert.addAction(UIAlertAction(title: "去设置", style: .default) { _ in
            if let url = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        })
        viewController?.present(alert, animated: true, completion: nil)
    }
}

// MARK: - PHPickerViewControllerDelegate (iOS 14+)
@available(iOS 14, *)
extension TSPhotoPickerManager: PHPickerViewControllerDelegate {
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true) {
            guard let result = results.first else {
                self.completionHandler?(nil)
                return
            }
            
            // 获取选中的图片
            result.itemProvider.loadObject(ofClass: UIImage.self) { [weak self] (object, error) in
                if let image = object as? UIImage {
                    DispatchQueue.main.async {
                        self?.completionHandler?(image)
                    }
                } else {
                    DispatchQueue.main.async {
                        self?.completionHandler?(nil)
                    }
                }
            }
        }
    }
}

// MARK: - UIImagePickerControllerDelegate & UINavigationControllerDelegate (iOS 14 以下)
extension TSPhotoPickerManager: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true) {
            if let image = info[.originalImage] as? UIImage {
                self.completionHandler?(image)
            } else {
                self.completionHandler?(nil)
            }
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
}
