package com.rugvedsarika.toolbox.calculators

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
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.FragmentDiscountCalculatorBinding

class DiscountCalculatorFragment : Fragment() {

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

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

        binding.btnCalculate.setOnClickListener {
            calculateDiscount()
        }
    }

    private fun calculateDiscount() {
        val priceStr = binding.etPrice.text.toString()
        val discountStr = binding.etDiscount.text.toString()

        if (priceStr.isEmpty() || discountStr.isEmpty()) {
            Toast.makeText(requireContext(), "Please fill all fields", Toast.LENGTH_SHORT).show()
            return
        }

        val price = priceStr.toDouble()
        val discountPercent = discountStr.toDouble()

        val savings = price * (discountPercent / 100)
        val finalPrice = price - savings

        binding.tvFinalPrice.text = "₹ ${String.format("%.2f", finalPrice)}"
        binding.tvSavings.text = "You save ₹ ${String.format("%.2f", savings)} ($discountPercent%)"
        
        binding.cardResult.visibility = View.VISIBLE
    }

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