package com.rugvedsarika.voicereader.ui.settings

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast

import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import com.rugvedsarika.voicereader.R
import com.rugvedsarika.voicereader.databinding.FragmentSettingsBinding
import com.rugvedsarika.voicereader.ui.MainViewModel

class SettingsFragment : Fragment() {

    private var _binding: FragmentSettingsBinding? = null
    private val binding get() = _binding!!

    private val viewModel: MainViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentSettingsBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // Speed Slider
        binding.sliderSpeed.addOnChangeListener { _, value, _ ->
            viewModel.speed.value = value
        }

        // Pitch Slider
        binding.sliderPitch.addOnChangeListener { _, value, _ ->
            viewModel.pitch.value = value
        }

        // Language Spinner
        viewModel.languageError.observe(viewLifecycleOwner) { error ->
            error?.let {
                Toast.makeText(requireContext(), it, Toast.LENGTH_LONG).show()
            }
        }

        viewModel.speed.observe(viewLifecycleOwner) {
            binding.sliderSpeed.value = it
            binding.tvSpeedLabel.text = getString(R.string.lbl_speech_rate, it)
        }

        viewModel.pitch.observe(viewLifecycleOwner) {
            binding.sliderPitch.value = it
            binding.tvPitchLabel.text = getString(R.string.lbl_pitch, it)
        }

        viewModel.textSize.observe(viewLifecycleOwner) {
            binding.sliderTextSize.value = it
            binding.tvTextSizeLabel.text = getString(R.string.lbl_text_size, it.toInt())
        }

        // Text Size Slider
        binding.sliderTextSize.value = viewModel.textSize.value ?: 18f
        binding.sliderTextSize.addOnChangeListener { _, value, _ ->
            viewModel.textSize.value = value
        }

        viewModel.currentEngine.observe(viewLifecycleOwner) { engine ->
            binding.tvEngineStatus.text = getString(R.string.lbl_tts_engine, engine)
        }

        viewModel.isGoogleEngine.observe(viewLifecycleOwner) { isGoogle ->
            binding.tvEngineRecommendation.visibility = if (isGoogle) View.GONE else View.VISIBLE
        }

        viewModel.isHighQualityVoice.observe(viewLifecycleOwner) { isHighQuality ->
            val qualityText = if (isHighQuality) getString(R.string.val_yes) else getString(R.string.val_no)
            binding.tvQualityStatus.text = getString(R.string.lbl_high_quality_voice, qualityText)
        }

        setupLanguageSpinner()
    }

    private fun setupLanguageSpinner() {
        val languages = viewModel.getAvailableLanguages()
        val adapter = ArrayAdapter(
            requireContext(),
            android.R.layout.simple_dropdown_item_1line,
            languages.map { it.displayName }
        )
        binding.spinnerLanguage.setAdapter(adapter)

        val currentLang = viewModel.selectedLanguage.value
        if (currentLang != null) {
            binding.spinnerLanguage.setText(currentLang.displayName, false)
            updateVoiceTip(currentLang.language)
        }

        binding.spinnerLanguage.setOnItemClickListener { _, _, position, _ ->
            val selected = languages[position]
            viewModel.setLanguage(selected)
            updateVoiceTip(selected.language)
        }
    }

    private fun updateVoiceTip(language: String) {
        binding.tvVoiceTip.visibility = if (language == "mr" || language == "hi") {
            View.VISIBLE
        } else {
            View.GONE
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
