//
//  PlayDetailControlView.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/13.
//
import Foundation
import Kingfisher
import MarqueeLabel
import SJVideoPlayer
import TSVideoKit
import UIKit

class PlayDetailControlView: UIView {
    lazy var titleLabel: MarqueeLabel = {
        let title: MarqueeLabel = .init(frame: CGRect(x: 0, y: 0, width: 300, height: 30))
        title.trailingBuffer = 20
        title.animationDelay = 0
        title.speed = .duration(10)
        title.font = .boldSystemFont20
        title.textAlignment = .center
        title.textColor = .white
        return title
    }()

    lazy var detailLabel: UILabel = .simpleLabel(text: "--", font: .systemFont14, color: .white, align: .center)

    lazy var topHStack: UIStackView = .hStack

    lazy var favouriteButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic_like"), for: .normal)
        btn.setImage(UIImage(named: "ic_like_s"), for: .selected)
        return btn
    }()

    lazy var playlistButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic_detail_addPlaylist"), for: .normal)
        btn.isHidden = true
        return btn
    }()

    lazy var lastButton: UIButton = {
        let btn = UIButton()
        btn.setLocalizedImage(UIImage(named: "ic_play_last"), for: .normal)
        return btn
    }()

    lazy var playButton: PlayButtonView = PlayButtonView()

    lazy var nextButton: UIButton = {
        let btn = UIButton()
        btn.setLocalizedImage(UIImage(named: "ic_play_next"), for: .normal)
        return btn
    }()

    lazy var progressView: SJProgressSlider = {
        let progress = SJProgressSlider()
        progress.trackHeight = 4
        progress.thumbImageView.image = UIImage(named: "ic_image_thubnail")
        progress.trackImageView.backgroundColor = .white.withAlphaComponent(0.1)
        progress.traceImageView.backgroundColor = .hexColor("#12FFF7")
        progress.traceImageView.contentMode = .scaleAspectFill
        progress.isRound = true
        progress.animaMaxDuration = 0
        progress.tap.isEnabled = true
        return progress
    }()

    lazy var currentLabel: UILabel = .simpleLabel(text: "00:00", font: .systemFont12, color: .hexColor("#B8B9C1"))
    lazy var durationLabel: UILabel = .simpleLabel(text: "00:00", font: .systemFont12, color: .hexColor("#B8B9C1"))

    lazy var videoHStack: UIStackView = {
        let stack: UIStackView = .hStack
        stack.distribution = .fillEqually
        return stack
    }()

    lazy var downloadButton: DownloadButton = {
        let btn = DownloadButton()
        btn.downloadState = .idle(isAnimate: false)
        btn.isHidden = true
        return btn
    }()

    lazy var playModelButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic_cycle"), for: .normal)
        return btn
    }()

    lazy var listButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic_playdetail_list"), for: .normal)
        return btn
    }()

    lazy var hStackView: UIStackView = {
        let stack: UIStackView = .hStack
        stack.distribution = .equalSpacing
        return stack
    }()

    lazy var adTag: UIImageView = {
        let tag = UIImageView(image: UIImage(named: "detail_ad_tag"))
        tag.isHidden = false
        return tag
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        addChildren()
        makeConstraints()
    }

    public func updateTime(currentTime: TimeInterval, duration: TimeInterval) {
        let value = currentTime / duration
        progressView.value = value
        currentLabel.text = currentTime.mmsshh
        durationLabel.text = duration.mmsshh
    }

    public func updateVideoInfo(video: TSVideo) {
        titleLabel.text = video.title
        detailLabel.text = video.artist

        playlistButton.isHidden = video.videoStatus != .cached
        downloadButton.isHidden = video.videoStatus == .cached
        favouriteButton.isHidden = video.videoStatus != .cached
        setDownloadButtonStates(status: video.videoStatus.asChunkDownloadStatus)
        downloadButton.progressView.set(progress: Double(video.progress))
        favouriteButton.isSelected = video.isFavorite
    }

    public func resetVideoInfo() {
        titleLabel.text = "--"
        detailLabel.text = "--"
        playlistButton.isHidden = true
        downloadButton.isHidden = true
    }

    func resetProgress() {
        progressView.value = 0
        currentLabel.text = "00:00"
        durationLabel.text = "00:00"
    }

    public func updateProgress(_ progress: Float) {
        downloadButton.progressView.set(progress: Double(progress))
    }

    public func setDownloadButtonStates(status: ChunkDownloadStatus) {
        switch status {
        case .idle, .cancel:
            downloadButton.downloadState = .idle(isAnimate: false)
            playlistButton.isHidden = true
            downloadButton.isHidden = false
            downloadButton.adTag.isHidden = PurchaseManager.default.isVip
        case .prasing:
            downloadButton.downloadState = .loading
            playlistButton.isHidden = true
            downloadButton.isHidden = false
        case .praseSuccess:
            break
        case .downloading:
            downloadButton.downloadState = .downloading
            playlistButton.isHidden = true
            downloadButton.isHidden = false
        case .pause:
            downloadButton.downloadState = .pause
            playlistButton.isHidden = true
            downloadButton.isHidden = false
        case .failed:
            downloadButton.downloadState = .retry
            playlistButton.isHidden = true
            downloadButton.isHidden = false
        case .finished:
            /// 完成，隐藏进度条，展示下载按钮，按钮状态设置为更多
            downloadButton.downloadState = .idle(isAnimate: false)
            playlistButton.isHidden = false
            downloadButton.isHidden = true
            favouriteButton.isHidden = false
        }
    }

    public func setDefaultDownloadStatus() {
        downloadButton.downloadState = .idle(isAnimate: false)
        downloadButton.progressView.set(progress: 0)
    }

    private func addChildren() {
        titleLabel.textAlignment = .left
        detailLabel.textAlignment = .left
        addSubview(titleLabel)
        addSubview(detailLabel)
        detailLabel.text = ""

        addSubview(topHStack)
        topHStack.addArrangedSubview(downloadButton)
        topHStack.addArrangedSubview(playlistButton)
        topHStack.addArrangedSubview(favouriteButton)

        addSubview(progressView)
        addSubview(currentLabel)
        addSubview(durationLabel)

        addSubview(videoHStack)
        videoHStack.addArrangedSubview(playModelButton)
        videoHStack.addArrangedSubview(lastButton)
        videoHStack.addArrangedSubview(playButton)
        videoHStack.addArrangedSubview(nextButton)
        videoHStack.addArrangedSubview(listButton)
    }

    private func makeConstraints() {
        let vRadio = UIScreen.kScreenHeight / 896.0

        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().inset(16)
            make.trailing.equalTo(topHStack.snp.leading).offset(-12)
            make.top.equalToSuperview()
        }

        detailLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().inset(16)
            make.trailing.equalTo(topHStack.snp.leading).offset(-12)
            make.top.equalTo(titleLabel.snp.bottom).offset(12 * vRadio)
        }

        topHStack.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalTo(titleLabel.snp.bottom)
        }
        downloadButton.snp.makeConstraints { make in
            make.width.height.equalTo(44)
        }
        playlistButton.snp.makeConstraints { make in
            make.width.height.equalTo(44)
        }
        favouriteButton.snp.makeConstraints { make in
            make.width.height.equalTo(44)
        }

        progressView.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.trailing.equalToSuperview().offset(-16)
            make.top.equalTo(detailLabel.snp.bottom).offset(44 * vRadio)
            make.height.equalTo(50)
        }

        currentLabel.snp.makeConstraints { make in
            if FitManager.isAr {
                make.trailing.equalTo(progressView)
            } else {
                make.leading.equalTo(progressView)
            }

            make.bottom.equalTo(progressView.snp.top).offset(14)
        }

        durationLabel.snp.makeConstraints { make in
            if FitManager.isAr {
                make.leading.equalTo(progressView)
            } else {
                make.trailing.equalTo(progressView)
            }
            make.bottom.equalTo(progressView.snp.top).offset(14 * vRadio)
        }

        videoHStack.snp.makeConstraints { make in
            make.top.equalTo(progressView.snp.bottom).offset(20 * vRadio)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }

        lastButton.snp.makeConstraints { make in
            make.width.height.equalTo(70)
        }

        playButton.snp.makeConstraints { make in
            make.width.height.equalTo(70)
        }

        nextButton.snp.makeConstraints { make in
            make.width.height.equalTo(70)
        }

        playModelButton.snp.makeConstraints { make in
            make.width.height.equalTo(64)
        }

        listButton.snp.makeConstraints { make in
            make.width.height.equalTo(64)
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
