package com.rugvedsarika.landarea.ui

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.fragment.app.Fragment
import com.rugvedsarika.landarea.databinding.FragmentCostBinding
import java.util.Locale

class CostFragment : Fragment() {

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

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

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

    private fun setupInputs() {
        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) {
                calculate()
            }
            override fun afterTextChanged(s: Editable?) {}
        }
        binding.etLandArea.addTextChangedListener(watcher)
        binding.etPricePerUnit.addTextChangedListener(watcher)
    }

    private fun calculate() {
        val area = binding.etLandArea.text.toString().toDoubleOrNull() ?: 0.0
        val price = binding.etPricePerUnit.text.toString().toDoubleOrNull() ?: 0.0
        val total = area * price
        binding.tvTotalCost.text = String.format(Locale.getDefault(), "₹ %.2f", total)
    }

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