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.FragmentGstCalculatorBinding

class GstCalculatorFragment : Fragment() {

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

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

        binding.btnCalculate.setOnClickListener {
            calculateGST()
        }
    }

    private fun calculateGST() {
        val amountStr = binding.etAmount.text.toString()
        val rateStr = binding.etGstRate.text.toString()

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

        val amount = amountStr.toDouble()
        val rate = rateStr.toDouble()

        val isAddingGst = binding.rbAddGst.isChecked

        val gstAmount: Double
        val finalPrice: Double

        if (isAddingGst) {
            gstAmount = amount * (rate / 100)
            finalPrice = amount + gstAmount
        } else {
            // Formula to remove GST: Amount - (Amount * (100 / (100 + Rate)))
            val basePrice = amount / (1 + (rate / 100))
            gstAmount = amount - basePrice
            finalPrice = basePrice
        }

        val splitGst = gstAmount / 2

        binding.tvTotalPrice.text = "₹ ${String.format("%.2f", finalPrice)}"
        binding.tvGstAmount.text = "₹ ${String.format("%.2f", gstAmount)}"
        binding.tvSplitGst.text = "₹ ${String.format("%.2f", splitGst)} × 2"
        
        binding.cardResult.visibility = View.VISIBLE
    }

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