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.FragmentUnitConverterBinding
import java.text.DecimalFormat

class LengthConverterFragment : Fragment() {

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

    private val units = listOf("Millimeter (mm)", "Centimeter (cm)", "Meter (m)", "Kilometer (km)", "Inch (in)", "Foot (ft)", "Yard (yd)", "Mile (mi)")
    
    private val factors = mapOf(
        "Millimeter (mm)" to 0.001,
        "Centimeter (cm)" to 0.01,
        "Meter (m)" to 1.0,
        "Kilometer (km)" to 1000.0,
        "Inch (in)" to 0.0254,
        "Foot (ft)" to 0.3048,
        "Yard (yd)" to 0.9144,
        "Mile (mi)" to 1609.34
    )

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

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

        binding.toolbar.title = "Length Converter"
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        binding.toolbar.setOnMenuItemClickListener { menuItem ->
            when (menuItem.itemId) {
                R.id.action_history -> {
                    findNavController().navigate(
                        R.id.historyFragment,
                        bundleOf("toolId" to "length_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(2) // Meter

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

        binding.spinnerFrom.onItemSelectedListener = listener
        binding.spinnerTo.onItemSelectedListener = listener

        binding.etInput.addTextChangedListener(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?) {}
        })
    }

    private fun convert() {
        val inputStr = binding.etInput.text.toString()
        if (inputStr.isNotEmpty()) {
            try {
                val input = inputStr.toDouble()
                val fromUnit = binding.spinnerFrom.selectedItem.toString()
                val toUnit = binding.spinnerTo.selectedItem.toString()
                
                val inBase = input * (factors[fromUnit] ?: 1.0)
                val result = inBase / (factors[toUnit] ?: 1.0)
                
                binding.tvOutput.text = DecimalFormat("#.#######").format(result)
            } catch (e: Exception) {
                binding.tvOutput.text = "Error"
            }
        } else {
            binding.tvOutput.text = "0.00"
        }
    }

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