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.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.toolbox.R
import com.rugvedsarika.toolbox.database.AppDatabase
import com.rugvedsarika.toolbox.database.HistoryItem
import com.rugvedsarika.toolbox.databinding.FragmentEmiCalculatorBinding
import kotlinx.coroutines.launch
import kotlin.math.pow

class EmiCalculatorFragment : Fragment() {

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

    private val db by lazy { AppDatabase.getDatabase(requireContext()) }
    private val dao by lazy { db.toolDao() }

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

        binding.btnCalculate.setOnClickListener {
            calculateEMI()
        }
    }

    private fun calculateEMI() {
        val principalStr = binding.etPrincipal.text.toString()
        val interestStr = binding.etInterest.text.toString()
        val tenureStr = binding.etTenure.text.toString()

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

        val P = principalStr.toDouble()
        val annualRate = interestStr.toDouble()
        val n = tenureStr.toDouble()

        // Monthly interest rate
        val r = annualRate / (12 * 100)

        // EMI Formula: [P x r x (1+r)^n] / [(1+r)^n - 1]
        val emi = (P * r * (1 + r).pow(n)) / ((1 + r).pow(n) - 1)
        
        val totalPayment = emi * n
        val totalInterest = totalPayment - P

        binding.tvEmiResult.text = "₹ ${String.format("%.2f", emi)}"
        binding.tvTotalInterest.text = "₹ ${String.format("%.2f", totalInterest)}"
        binding.tvTotalPayment.text = "₹ ${String.format("%.2f", totalPayment)}"
        
        binding.cardResult.visibility = View.VISIBLE

        // Save to history
        lifecycleScope.launch {
            dao.insertHistory(
                HistoryItem(
                    toolId = "emi_calculator",
                    title = "EMI Calculation",
                    description = "₹${String.format("%.0f", P)} @ ${String.format("%.1f", annualRate)}% for ${n.toInt()} months = ₹${String.format("%.0f", emi)}/month"
                )
            )
        }
    }

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