//
//  YHCircleMediaCell.swift
//  galaxy
//
//  Created by alexzzw on 2025/9/27.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AVFoundation

class YHCircleMediaCell: UICollectionViewCell {
    var deleteCallback: (() -> Void)?
    
    // MARK: - UI Components
    private lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.clipsToBounds = true
        imageView.backgroundColor = UIColor.brandGrayColor2
        return imageView
    }()
    
    private lazy var deleteButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(systemName: "xmark.circle.fill"), for: .normal)
        button.tintColor = .white
        button.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        button.layer.cornerRadius = 10
        button.addTarget(self, action: #selector(deleteButtonTapped), for: .touchUpInside)
        button.isHidden = true
        return button
    }()
    
    private lazy var playIcon: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "circle_play_icon")
        imageView.isHidden = true
        return imageView
    }()
    
    private lazy var durationLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        label.textColor = .white
        label.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        label.textAlignment = .center
        label.layer.cornerRadius = 8
        label.clipsToBounds = true
        label.isHidden = true
        return label
    }()
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Setup UI
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(playIcon)
        contentView.addSubview(durationLabel)
        contentView.addSubview(deleteButton)
        
        imageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        playIcon.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(40)
        }
        
        durationLabel.snp.makeConstraints { make in
            make.bottom.right.equalToSuperview().inset(8)
            make.height.equalTo(20)
            make.width.greaterThanOrEqualTo(35)
        }
        
        deleteButton.snp.makeConstraints { make in
            make.top.right.equalToSuperview().inset(4)
            make.width.height.equalTo(20)
        }
    }
    
    // MARK: - Configure Cell
    func configure(with mediaItem: YHSelectMediaItem) {
        resetCell()
        
        switch mediaItem.type {
        case .image:
            configureForImage(mediaItem)
        case .video:
            configureForVideo(mediaItem)
        }
    }
    
    private func resetCell() {
        imageView.image = nil
        playIcon.isHidden = true
        durationLabel.isHidden = true
        durationLabel.text = nil
    }
    
    private func configureForImage(_ mediaItem: YHSelectMediaItem) {
        if let url = mediaItem.imageURL {
            imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "global_default_image"), context: nil)
        } else {
            imageView.image = mediaItem.image
        }
        playIcon.isHidden = true
        durationLabel.isHidden = true
    }
    
    private func configureForVideo(_ mediaItem: YHSelectMediaItem) {
        // 显示视频相关UI
        playIcon.isHidden = false
        
        // 生成视频缩略图
        if let videoURL = mediaItem.videoURL {
            generateVideoThumbnail(from: videoURL) { [weak self] thumbnail in
                DispatchQueue.main.async {
                    self?.imageView.image = thumbnail
                }
            }
        }
        
        // 显示视频时长
//        if let duration = mediaItem.duration {
//            durationLabel.text = formatDuration(duration)
//            durationLabel.isHidden = false
//        } else if let videoURL = mediaItem.videoURL {
//            // 如果没有时长信息，尝试获取
//            getVideoDuration(from: videoURL) { [weak self] duration in
//                DispatchQueue.main.async {
//                    if duration > 0 {
//                        self?.durationLabel.text = self?.formatDuration(duration)
//                        self?.durationLabel.isHidden = false
//                    }
//                }
//            }
//        }
    }
    
    // MARK: - Video Helpers
    private func generateVideoThumbnail(from url: URL, completion: @escaping (UIImage?) -> Void) {
        DispatchQueue.global(qos: .userInitiated).async {
            let asset = AVAsset(url: url)
            let imageGenerator = AVAssetImageGenerator(asset: asset)
            imageGenerator.appliesPreferredTrackTransform = true
            imageGenerator.maximumSize = CGSize(width: 300, height: 300)
            
            let time = CMTime(seconds: 0.0, preferredTimescale: 600)
            
            do {
                let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
                let thumbnail = UIImage(cgImage: cgImage)
                completion(thumbnail)
            } catch {
                print("生成视频缩略图失败: \(error)")
                completion(nil)
            }
        }
    }
    
    private func getVideoDuration(from url: URL, completion: @escaping (TimeInterval) -> Void) {
        DispatchQueue.global(qos: .userInitiated).async {
            let asset = AVAsset(url: url)
            let duration = CMTimeGetSeconds(asset.duration)
            completion(duration.isNaN ? 0 : duration)
        }
    }
    
    private func formatDuration(_ duration: TimeInterval) -> String {
        let totalSeconds = Int(duration)
        let minutes = totalSeconds / 60
        let seconds = totalSeconds % 60
        
        if minutes > 0 {
            return String(format: "%d:%02d", minutes, seconds)
        } else {
            return String(format: "0:%02d", seconds)
        }
    }
    
    // MARK: - Actions
    @objc private func deleteButtonTapped() {
        deleteCallback?()
    }
}
