//
//  YHVideoProgressControl.swift
//  galaxy
//
//  Created by alexzzw on 2024/12/4.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHVideoProgressControl: UIView {
    // MARK: - UI Components
    private lazy var segmentCollection: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        layout.minimumLineSpacing = 4
        layout.minimumInteritemSpacing = 4
        
        let collection = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collection.backgroundColor = .clear
        collection.showsHorizontalScrollIndicator = false
        collection.register(SegmentCell.self, forCellWithReuseIdentifier: "SegmentCell")
        collection.delegate = self
        collection.dataSource = self
        collection.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        collection.allowsSelection = true
        collection.delaysContentTouches = false
        return collection
    }()
    
    private lazy var progressSlider: UISlider = {
        let slider = UISlider()
        slider.minimumTrackTintColor = .white
        slider.maximumTrackTintColor = .white.withAlphaComponent(0.24)
        slider.setThumbImage(UIImage(named: "live_slider_thumb"), for: .normal)
        slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged)
        return slider
    }()
    
    private lazy var playButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "live_icon_play"), for: .normal)
        button.setImage(UIImage(named: "live_icon_pause"), for: .selected)
        button.addTarget(self, action: #selector(playButtonTapped), for: .touchUpInside)
        return button
    }()
    
    private lazy var currentTimeLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .PFSC_M(ofSize: 12)
        return label
    }()
    
    private lazy var timeSeparator: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "live_time_separator"))
        return imageView
    }()
    
    private lazy var totalTimeLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white.withAlphaComponent(0.70)
        label.font = .PFSC_R(ofSize: 12)
        return label
    }()
        
    private lazy var giftButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setBackgroundImage(UIImage(named: "live_room_msg_gift"), for: .normal)
        button.setTitle("0", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.titleLabel?.font = .PFSC_M(ofSize: 10)
        button.addTarget(self, action: #selector(giftButtonTapped), for: .touchUpInside)
        button.titleEdgeInsets = UIEdgeInsets(top: 5, left: 0, bottom: -5, right: 0)
        return button
    }()
    
    private lazy var bottomVisualEffectView: UIVisualEffectView = {
        let effect = UIBlurEffect(style: .dark)
        let view = UIVisualEffectView(effect: effect)
        view.alpha = 0.9
        return view
    }()
    
    private lazy var markersContainer: UIView = {
        let view = UIView()
        view.isUserInteractionEnabled = false // 确保不影响滑块的交互
        return view
    }()

    private var markers: [UIView] = []
    private var lastRatios: [Double] = []
    
    // MARK: - Properties
    private var segments: [String] = []
    private var currentSegmentIndex: Int?
    private var isPlaying = false
    private var currentTime: TimeInterval = 0
    private var duration: TimeInterval = 0
    
    var onPlayStatusChanged: ((Bool) -> Void)?
    var onSegmentSelected: ((Int) -> Void)?
    var onTimeChanged: ((TimeInterval) -> Void)?
    var giftButtonClickEvent: (() -> Void)?
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        addSubview(bottomVisualEffectView)
        addSubview(segmentCollection)
        addSubview(progressSlider)
        addSubview(markersContainer)
        addSubview(playButton)
        addSubview(currentTimeLabel)
        addSubview(timeSeparator)
        addSubview(totalTimeLabel)
        addSubview(giftButton)
        bottomVisualEffectView.frame = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height)
        bottomVisualEffectView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalToSuperview()
        }
        // 渐变效果
        let gradinetLayer = CAGradientLayer()
        gradinetLayer.colors = [UIColor.black.withAlphaComponent(0).cgColor, UIColor.black.withAlphaComponent(0).cgColor, UIColor.black.withAlphaComponent(0.16).cgColor, UIColor.black.withAlphaComponent(0.16).cgColor]
        gradinetLayer.startPoint = CGPoint(x: 0.5, y: 0)
        gradinetLayer.endPoint = CGPoint(x: 0.5, y: 1)
        gradinetLayer.frame = bottomVisualEffectView.bounds
        bottomVisualEffectView.layer.mask = gradinetLayer
        
        segmentCollection.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(22)
            make.right.equalToSuperview().offset(-4)
        }
        progressSlider.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.top.equalTo(segmentCollection.snp.bottom).offset(8)
        }
        
        markersContainer.snp.makeConstraints { make in
            make.edges.equalTo(progressSlider)
        }

        playButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        playButton.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(8)
            make.top.equalTo(progressSlider.snp.bottom).offset(12)
            make.size.equalTo(CGSize(width: 32, height: 32))
        }
        
        currentTimeLabel.snp.makeConstraints { make in
            make.left.equalTo(playButton.snp.right).offset(5)
            make.centerY.equalTo(playButton)
        }
        
        timeSeparator.snp.makeConstraints { make in
            make.centerY.equalTo(playButton)
            make.left.equalTo(currentTimeLabel.snp.right).offset(8)
            make.size.equalTo(CGSize(width: 4, height: 11))
        }
        
        totalTimeLabel.snp.makeConstraints { make in
            make.left.equalTo(timeSeparator.snp.right).offset(8)
            make.centerY.equalTo(playButton)
        }
        
        giftButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.centerY.equalTo(playButton)
            make.width.height.equalTo(38)
        }
        
    }
    
    // MARK: - Public Methods
    func configure(with segments: [String]) {
        self.segments = segments
        segmentCollection.reloadData()
    }
    
    /// 计算为0-1的比例值
    func setupMarkers(marks: [Double]) {
        guard marks != lastRatios else {
            return
        }
        lastRatios = marks
        // 清除现有的标记
        markers.forEach { $0.removeFromSuperview() }
        markers.removeAll()
        // 计算间距
        // 使用 slider 的实际宽度
        let totalWidth = progressSlider.bounds.width  // 使用 slider 的宽度
        let trackRect = progressSlider.trackRect(forBounds: progressSlider.bounds)
        let thumbWidth = progressSlider.thumbRect(forBounds: progressSlider.bounds,
                                            trackRect: trackRect,
                                            value: 0).width
        let usableWidth = totalWidth - thumbWidth

        // 创建新的标记点
        for item in marks {
            let marker = UIView()
            marker.backgroundColor = .white
            markersContainer.addSubview(marker)
            markers.append(marker)
            let x = (usableWidth * item) + thumbWidth/2
            marker.snp.makeConstraints { make in
                make.centerX.equalTo(progressSlider).offset(x - totalWidth/2)
                make.centerY.equalToSuperview()
                make.width.equalTo(1)
                make.height.equalTo(2)
            }
        }
    }
    
    func updateTime(_ current: TimeInterval, duration: TimeInterval, currentIndex: Int? = nil) {
        self.currentTime = current
        self.duration = duration
        progressSlider.value = Float(current / duration)
        currentTimeLabel.text = String(format: "%02d:%02d", Int(current) / 60, Int(current) % 60)
        totalTimeLabel.text = String(format: "%02d:%02d", Int(duration) / 60, Int(duration) % 60)
        if currentIndex != currentSegmentIndex {
            currentSegmentIndex = currentIndex
            if let currentIndex = currentIndex {
                if segmentCollection.numberOfSections > 0, segmentCollection.numberOfItems(inSection: 0) > currentIndex {
                    segmentCollection.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: .centeredHorizontally, animated: true)
                    segmentCollection.reloadData()
                }
            } else {
                segmentCollection.reloadData()
            }
            
        }
//        if let currentIndex = currentIndex, currentIndex != currentSegmentIndex {
//            currentSegmentIndex = currentIndex
//            if segmentCollection.numberOfSections > 0, segmentCollection.numberOfItems(inSection: 0) > currentIndex {
//                if currentIndex > 0 {
//                    segmentCollection.scrollToItem(at: IndexPath(item: currentIndex, section: 0), at: .centeredHorizontally, animated: true)
//                }
//                segmentCollection.reloadData()
//            }
//        }
    }
    
    func setPlaying(_ playing: Bool) {
        guard isPlaying != playing else {
            return
        }
        isPlaying = playing
        playButton.isSelected = playing
    }
    
    func updateGiftCount(_ count: Int) {
        guard count > 0 else {
            giftButton.isHidden = true
            giftButton.setTitle("0", for: .normal)
            return
        }
        giftButton.isHidden = false
        if count > 99 {
            giftButton.setTitle("99+", for: .normal)
        } else {
            giftButton.setTitle("\(count)", for: .normal)
        }
    }
    
    // MARK: - Actions
    @objc private func playButtonTapped() {
        isPlaying.toggle()
        playButton.isSelected = isPlaying
        onPlayStatusChanged?(isPlaying)
    }
    
    @objc private func sliderValueChanged() {
        let time = TimeInterval(progressSlider.value) * duration
        onTimeChanged?(time)
    }
    
    @objc private func giftButtonTapped() {
        giftButtonClickEvent?()
    }
}

// MARK: - UICollectionView DataSource & Delegate
extension YHVideoProgressControl: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return segments.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard segments.count > indexPath.item, let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SegmentCell", for: indexPath) as? SegmentCell else {
            return UICollectionViewCell()
        }
        cell.configure(with: segments[indexPath.item], isSelected: indexPath.item == currentSegmentIndex)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let text = segments[indexPath.item]
        let attr = NSAttributedString(string: text, attributes: [.font: UIFont.systemFont(ofSize: 10)])
        let width = attr.yh_width(containerHeight: 22) + 8
        return CGSize(width: width, height: 22)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        currentSegmentIndex = indexPath.item
        collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
        collectionView.reloadData()
        onSegmentSelected?(indexPath.item)
    }
}

// MARK: - SegmentCell
class SegmentCell: UICollectionViewCell {
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 10)
        label.textAlignment = .center
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
//        super.touchesBegan(touches, with: event)
//        print("Cell touched")
//    }
    
    private func setupUI() {
        backgroundColor = .black.withAlphaComponent(0.3)
        layer.cornerRadius = 2
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    func configure(with title: String, isSelected: Bool) {
        titleLabel.text = title
        titleLabel.textColor = isSelected ? .mainTextColor : .white
        backgroundColor = isSelected ? .white : .black.withAlphaComponent(0.3)
    }
}
