package com.rugvedsarika.toolbox.calculators

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 androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.toolbox.R
import com.rugvedsarika.toolbox.databinding.FragmentAutoTotalCalculatorBinding
import java.text.DecimalFormat

class AutoTotalCalculatorFragment : Fragment() {

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

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentAutoTotalCalculatorBinding.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 "auto_total_calculator")
                    )
                    true
                }
                else -> false
            }
        }

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

        binding.etQuantity.addTextChangedListener(textWatcher)
        binding.etValue.addTextChangedListener(textWatcher)

        binding.btnClear.setOnClickListener {
            binding.etQuantity.setText("")
            binding.etValue.setText("")
            binding.tvTotal.text = "0.00"
        }
    }

    private fun calculateTotal() {
        val qtyStr = binding.etQuantity.text.toString()
        val valStr = binding.etValue.text.toString()

        if (qtyStr.isNotEmpty() && valStr.isNotEmpty()) {
            try {
                val qty = qtyStr.toDouble()
                val value = valStr.toDouble()
                val total = qty * value
                binding.tvTotal.text = DecimalFormat("#,##,##0.00").format(total)
            } catch (e: Exception) {
                binding.tvTotal.text = "Error"
            }
        } else {
            binding.tvTotal.text = "0.00"
        }
    }

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