//
//  YHPlayerControlView.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

protocol YHPlayerControlViewDelegate: AnyObject {
    func playerControlView(_ view: YHPlayerControlView, didTapBack button: UIButton)
    func playerControlView(_ view: YHPlayerControlView, didTapPlay button: UIButton)
    func playerControlView(_ view: YHPlayerControlView, didSeekTo position: Float)
    func playerControlView(_ view: YHPlayerControlView, didChangeQuality quality: YHVideoQuality)
    func playerControlView(_ view: YHPlayerControlView, didTapFullscreen button: UIButton)
}

class YHPlayerControlView: UIView {
    // MARK: - Properties
    weak var delegate: YHPlayerControlViewDelegate?
    
    // MARK: - UI Components
    private lazy var dimView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.4)
        return view
    }()
    
    private lazy var topBar: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    private lazy var backButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "icon_back_white"), for: .normal)
        button.tintColor = .white
        button.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        return button
    }()
    
    private lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 16, weight: .medium)
        return label
    }()
    
    private lazy var bottomBar: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    private lazy var playButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_play"), for: .normal)
        button.setImage(UIImage(named: "icon_pause"), for: .selected)
        button.addTarget(self, action: #selector(playButtonTapped), for: .touchUpInside)
        return button
    }()
    
    private lazy var progressSlider: UISlider = {
        let slider = UISlider()
        slider.minimumTrackTintColor = UIColor.brandMainColor
        slider.maximumTrackTintColor = .white.withAlphaComponent(0.3)
        slider.setThumbImage(UIImage(named: "icon_slider_thumb"), for: .normal)
        slider.addTarget(self, action: #selector(sliderValueChanged(_:)), for: .valueChanged)
        slider.addTarget(self, action: #selector(sliderTouchBegan(_:)), for: .touchDown)
        slider.addTarget(self, action: #selector(sliderTouchEnded(_:)), for: [.touchUpInside, .touchUpOutside, .touchCancel])
        return slider
    }()
    
    private lazy var timeLabel: UILabel = {
        let label = UILabel()
        label.textColor = .white
        label.font = .systemFont(ofSize: 12)
        label.text = "00:00 / 00:00"
        return label
    }()
    
    private lazy var qualityButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("清晰度", for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 14)
        button.setTitleColor(.white, for: .normal)
        button.addTarget(self, action: #selector(qualityButtonTapped), for: .touchUpInside)
        return button
    }()
    
    private lazy var fullscreenButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_fullscreen"), for: .normal)
        button.setImage(UIImage(named: "icon_fullscreen_exit"), for: .selected)
        button.addTarget(self, action: #selector(fullscreenButtonTapped), for: .touchUpInside)
        return button
    }()
    
    // MARK: - Initialization
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupUI()
    }
    
    // MARK: - Setup
    private func setupUI() {
        addSubview(dimView)
        addSubview(topBar)
        addSubview(bottomBar)
        
        topBar.addSubview(backButton)
        topBar.addSubview(titleLabel)
        
        bottomBar.addSubview(playButton)
        bottomBar.addSubview(progressSlider)
        bottomBar.addSubview(timeLabel)
        bottomBar.addSubview(qualityButton)
        bottomBar.addSubview(fullscreenButton)
        
        setupConstraints()
    }
    
    private func setupConstraints() {
        dimView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        topBar.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(44)
        }
        
        backButton.snp.makeConstraints { make in
            make.left.equalTo(topBar).offset(16)
            make.centerY.equalTo(topBar)
            make.size.equalTo(CGSize(width: 44, height: 44))
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(backButton.snp.right).offset(8)
            make.right.equalTo(topBar).offset(-16)
            make.centerY.equalTo(topBar)
        }
        
        bottomBar.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(44)
        }
        
        playButton.snp.makeConstraints { make in
            make.left.equalTo(bottomBar).offset(16)
            make.centerY.equalTo(bottomBar)
            make.size.equalTo(CGSize(width: 44, height: 44))
        }
        
        progressSlider.snp.makeConstraints { make in
            make.left.equalTo(playButton.snp.right).offset(8)
            make.right.equalTo(timeLabel.snp.left).offset(-8)
            make.centerY.equalTo(bottomBar)
        }
        
        timeLabel.snp.makeConstraints { make in
            make.right.equalTo(qualityButton.snp.left).offset(-8)
            make.centerY.equalTo(bottomBar)
            make.width.equalTo(100)
        }
        
        qualityButton.snp.makeConstraints { make in
            make.right.equalTo(fullscreenButton.snp.left).offset(-8)
            make.centerY.equalTo(bottomBar)
        }
        
        fullscreenButton.snp.makeConstraints { make in
            make.right.equalTo(bottomBar).offset(-16)
            make.centerY.equalTo(bottomBar)
            make.size.equalTo(CGSize(width: 44, height: 44))
        }
    }
    
    // MARK: - Actions
    @objc private func backButtonTapped() {
        delegate?.playerControlView(self, didTapBack: backButton)
    }
    
    @objc private func playButtonTapped() {
        playButton.isSelected.toggle()
        delegate?.playerControlView(self, didTapPlay: playButton)
    }
    
    @objc private func sliderValueChanged(_ slider: UISlider) {
        delegate?.playerControlView(self, didSeekTo: slider.value)
        timeLabel.text = "\(formatTime(slider.value)) / \(timeLabel.text?.components(separatedBy: " / ").last ?? "00:00")"
    }
    
    @objc private func sliderTouchBegan(_ slider: UISlider) {
        // 可以在这里暂停播放
    }
    
    @objc private func sliderTouchEnded(_ slider: UISlider) {
        // 可以在这里恢复播放
    }
    
    @objc private func qualityButtonTapped() {
        showQualitySelector()
    }
    
    @objc private func fullscreenButtonTapped() {
        fullscreenButton.isSelected.toggle()
        delegate?.playerControlView(self, didTapFullscreen: fullscreenButton)
    }
    
    private func showQualitySelector() {
        let alert = UIAlertController(title: "选择清晰度", message: nil, preferredStyle: .actionSheet)
        
        YHVideoQuality.allCases.forEach { quality in
            let action = UIAlertAction(title: quality.rawValue, style: .default) { [weak self] _ in
                guard let self = self else { return }
                self.delegate?.playerControlView(self, didChangeQuality: quality)
            }
            alert.addAction(action)
        }
        
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        
        if let viewController = self.window?.rootViewController {
            viewController.present(alert, animated: true)
        }
    }
    
    // MARK: - Public Methods
    func updatePlayButton(isPlaying: Bool) {
        // playButton.isSelected = isPlaying
    }
    
    func updateProgress(_ progress: Float, currentTime: String, totalTime: String) {
        progressSlider.value = progress
        timeLabel.text = "\(currentTime) / \(totalTime)"
    }
    
    func setTitle(_ title: String) {
        titleLabel.text = title
    }
    
    func showControls(_ show: Bool) {
        UIView.animate(withDuration: 0.3) {
            self.alpha = show ? 1.0 : 0.0
        }
    }
    
    func updateFullscreenButton(isFullscreen: Bool) {
        fullscreenButton.isSelected = isFullscreen
    }
    
    // MARK: - Helper Methods
    private func formatTime(_ progress: Float) -> String {
        let duration = timeLabel.text?.components(separatedBy: " / ").last ?? "00:00"
        let components = duration.components(separatedBy: ":")
        guard let minuteString = components.first,
              let secondString = components.last,
              let minutes = Int(minuteString),
              let seconds = Int(secondString) else {
            return "00:00"
        }
        
        let totalSeconds = minutes * 60 + seconds
        let currentSeconds = Int(Float(totalSeconds) * progress)
        return String(format: "%02d:%02d", currentSeconds / 60, currentSeconds % 60)
    }
}
