using System;
using DG.Tweening;
using SatorImaging.AppWindowUtility;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Serialization;
using UnityEngine.UI;

namespace View.UI {
	public class SettingsMenu : MonoBehaviour {
		[SerializeField] private CanvasGroup mainUIGroup;
		[SerializeField] private Button openSettingsButton;

		[Space]
		[SerializeField] private CanvasGroup settingsUIGroup;
		[SerializeField] private Button closeSettingsButton;

		[Space]
		[SerializeField] private float transitionDuration = .5f;

		[Space]
		[SerializeField] private Toggle musicToggle;
		[SerializeField] private Toggle sfxToggle;
		[SerializeField] private Toggle alwaysOnTopToggle;

		[Space]
		[SerializeField] private AudioMixer mainMixer;

		private void Awake() {
			openSettingsButton.onClick.AddListener(OpenSettings);
			closeSettingsButton.onClick.AddListener(CloseSettings);

			musicToggle.onValueChanged.AddListener(MusicStateChange);
			sfxToggle.onValueChanged.AddListener(SFXStateChange);
			alwaysOnTopToggle.onValueChanged.AddListener(AlwaysOnTopStateChange);
		}

		private void AlwaysOnTopStateChange(bool state) {
			AppWindowUtility.AlwaysOnTop = state;
		}

		private void SFXStateChange(bool state) {
			if (state)
				mainMixer.SetFloat("SFX", Mathf.Log10(1f) * 20);
			else
				mainMixer.SetFloat("SFX", Mathf.Log10(.0001f) * 20);
		}

		private void MusicStateChange(bool state) {
			if (state)
				mainMixer.SetFloat("Music", Mathf.Log10(1f) * 20);
			else
				mainMixer.SetFloat("Music", Mathf.Log10(.0001f) * 20);
		}

		private void OpenSettings() {
			mainUIGroup.interactable = mainUIGroup.blocksRaycasts = false;
			mainUIGroup.DOFade(0f, transitionDuration);

			settingsUIGroup.interactable = settingsUIGroup.blocksRaycasts = true;
			settingsUIGroup.DOFade(1f, transitionDuration);
		}

		private void CloseSettings() {
			settingsUIGroup.interactable = settingsUIGroup.blocksRaycasts = false;
			settingsUIGroup.DOFade(0f, transitionDuration);

			mainUIGroup.interactable = mainUIGroup.blocksRaycasts = true;
			mainUIGroup.DOFade(1f, transitionDuration);
		}
	}
}