package com.rugvedsarika.toolbox.converters

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.toolbox.R
import com.rugvedsarika.toolbox.databinding.FragmentTemperatureConverterBinding

class TemperatureConverterFragment : Fragment() {

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

    private val units = arrayOf("Celsius (°C)", "Fahrenheit (°F)", "Kelvin (K)")

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

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

        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.toolbar.setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.action_history -> {
                    findNavController().navigate(
                        R.id.historyFragment,
                        bundleOf("toolId" to "temperature_converter")
                    )
                    true
                }
                else -> false
            }
        }

        val adapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, units)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        
        binding.spinnerFrom.adapter = adapter
        binding.spinnerTo.adapter = adapter
        binding.spinnerTo.setSelection(1)

        val watcher = object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                convert()
            }
            override fun afterTextChanged(s: Editable?) {}
        }

        binding.etInput.addTextChangedListener(watcher)

        val spinnerListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                convert()
            }
            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }

        binding.spinnerFrom.onItemSelectedListener = spinnerListener
        binding.spinnerTo.onItemSelectedListener = spinnerListener
    }

    private fun convert() {
        val inputStr = binding.etInput.text.toString()
        if (inputStr.isEmpty() || inputStr == "-") {
            binding.tvOutput.text = "0.0"
            return
        }

        val inputVal = inputStr.toDouble()
        val fromUnit = binding.spinnerFrom.selectedItem.toString()
        val toUnit = binding.spinnerTo.selectedItem.toString()

        // First convert everything to Celsius
        val celsius = when (fromUnit) {
            "Celsius (°C)" -> inputVal
            "Fahrenheit (°F)" -> (inputVal - 32) * 5 / 9
            "Kelvin (K)" -> inputVal - 273.15
            else -> inputVal
        }

        // Then convert Celsius to target
        val result = when (toUnit) {
            "Celsius (°C)" -> celsius
            "Fahrenheit (°F)" -> (celsius * 9 / 5) + 32
            "Kelvin (K)" -> celsius + 273.15
            else -> celsius
        }

        binding.tvOutput.text = String.format("%.2f", result)
    }

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