//
//  SleepTimeViewController.swift
//  ColorfulWallpaper
//
//  Created by nkl on 2024/9/26.
//

import Combine
import Foundation
import KLExtension

let kSleepModelKey = "SleepModelKey"

class SleepTimeViewController: LWBaseViewController, UIPickerViewDataSource, UIPickerViewDelegate {
    lazy var bgView: UIView = .simpleView(color: .hexColor("#01143C"))
    lazy var titleLabel: UILabel = .simpleLabel(text: "Sleep Mode".localized(), font: .boldSystemFont18, color: .white)
    lazy var dismissControl: UIControl = {
        let control = UIControl()
        control.addTarget(self, action: #selector(dismissCurrentVc), for: .touchUpInside)
        return control
    }()

    lazy var switchButton: UISwitch = {
        let btn = UISwitch()
        btn.onTintColor = UIColor.hexColor("#56A4E9")
        btn.addTarget(self, action: #selector(startSleepCountDown(sender:)), for: .valueChanged)
        return btn
    }()

    lazy var customPickerView: UIPickerView = {
        let pick = UIPickerView()
        pick.dataSource = self
        pick.delegate = self
        return pick
    }()

    lazy var timeView: UIButton = {
        let btn = UIButton()
        btn.setTitle("00:00:00", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = .systemFont(ofSize: 18)
        btn.setImage(UIImage(named: "ic_clock_time_large"), for: .normal)
        let spacing: CGFloat = 10.0
        btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -spacing / 2, bottom: 0, right: spacing / 2)
        btn.titleEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: -spacing / 2)
        btn.contentEdgeInsets = UIEdgeInsets(top: 0, left: spacing / 2, bottom: 0, right: spacing / 2)
        return btn
    }()

    let hours = Array(0 ... 23)
    let minutes = Array(0 ... 59)

    private var cancellables: [AnyCancellable] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .black.withAlphaComponent(0.6)
        addNotifaction()

        /// 默认为1分钟
        if PlayerManager.shared.sleepModel.countTime == 0 {
            PlayerManager.shared.sleepModel.countTime = 0
        }
    }

    @objc func startSleepCountDown(sender: UISwitch) {
        if PlayerManager.shared.sleepModel.countTime == 0 {
            sender.isOn = false
            return
        }
        PlayerManager.shared.sleepModel.isOpen = sender.isOn
        if sender.isOn {
            PlayerManager.shared.player?.countDownTime()
        } else {
            PlayerManager.shared.player?.stopTimer()
        }
        dismissCurrentVc()
    }

    func selectTime(time: TimeInterval) {
        timeView.setTitle(time.hhmmss, for: .normal)
        let hour = Int(time) / 3600
        let minute = (Int(time) % 3600) / 60
        if let index = hours.firstIndex(of: hour) {
            customPickerView.selectRow(index, inComponent: 0, animated: false)
        } else {
            customPickerView.selectRow(0, inComponent: 0, animated: false)
        }
        if let minIndex = minutes.firstIndex(of: minute) {
            customPickerView.selectRow(minIndex, inComponent: 1, animated: false)
        } else {
            customPickerView.selectRow(0, inComponent: 1, animated: false)
        }
    }

    override func addNotifaction() {
        super.addNotifaction()
        PlayerManager.shared.$sleepModel.receive(on: DispatchQueue.main).sink { model in
            self.selectTime(time: model.countTime)
            self.switchButton.isOn = model.isOpen
        }.store(in: &cancellables)
    }

    override func addChildren() {
        super.addChildren()
        view.addSubview(bgView)
        view.addSubview(dismissControl)
        bgView.addSubview(titleLabel)
        bgView.addSubview(switchButton)
        bgView.addSubview(customPickerView)
        bgView.addSubview(timeView)
    }

    override func makeConstarints() {
        super.makeConstarints()

        dismissControl.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.bottom.equalTo(bgView.snp.top)
        }

        bgView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }

        titleLabel.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(16)
            make.bottom.equalTo(timeView.snp.top).offset(-30)
            make.top.equalToSuperview().offset(30)
        }

        switchButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalTo(titleLabel)
        }

        timeView.snp.makeConstraints { make in
            make.bottom.equalTo(customPickerView.snp.top).offset(-30)
            make.centerX.equalToSuperview()
        }

        customPickerView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview().offset(-(view.safeAreaInsets.bottom + 20))
        }
    }

    @objc func dismissCurrentVc() {
        dismiss(animated: true)
    }

    // MARK: - UIPickerViewDataSource

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2 // 两个组件：小时和分钟
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if component == 0 {
            return hours.count // 小时的行数
        } else {
            return minutes.count // 分钟的行数
        }
    }

    // MARK: - UIPickerViewDelegate

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        if component == 0 {
            return "\(hours[row]) hours" // 显示小时
        } else {
            return String(format: "%2d min", minutes[row]) // 显示分钟
        }
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        let selectedHour = pickerView.selectedRow(inComponent: 0)
        let selectedMinute = pickerView.selectedRow(inComponent: 1)

        let totalScends = hours[selectedHour] * 60 * 60 + minutes[selectedMinute] * 60
        PlayerManager.shared.sleepModel.countTime = TimeInterval(totalScends)
        print("Selected time: \(hours[selectedHour]):\(minutes[selectedMinute])")
    }

    func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
        40
    }

    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = (view as? UILabel) ?? UILabel()
        if component == 0 {
            label.text = "\(hours[row]) hours"
        } else {
            label.text = String(format: "%2d min", minutes[row])
        }
        label.textAlignment = .center
        label.font = .boldSystemFont(ofSize: 18)
        label.textColor = .white // 自定义文字颜色
        return label
    }

    deinit {
        cancellables.removeAll()
    }
}
