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 android.widget.TextView
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.textfield.TextInputEditText
import com.rugvedsarika.toolbox.R
import com.rugvedsarika.toolbox.databinding.FragmentCashCounterBinding
import java.text.DecimalFormat

data class CashNote(val value: Int, var count: Int = 0)

class CashCounterFragment : Fragment() {

    private var _binding: FragmentCashCounterBinding? = null
    private val binding get() = _binding!!
    
    private lateinit var notes: List<CashNote>
    private lateinit var adapter: CashNoteAdapter

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

        notes = listOf(
            CashNote(2000),
            CashNote(500),
            CashNote(200),
            CashNote(100),
            CashNote(50),
            CashNote(20),
            CashNote(10)
        )

        adapter = CashNoteAdapter(notes) {
            updateGrandTotal()
        }
        binding.rvNotes.adapter = adapter

        binding.fabClear.setOnClickListener {
            notes.forEach { it.count = 0 }
            adapter.notifyDataSetChanged()
            updateGrandTotal()
        }
    }

    private fun updateGrandTotal() {
        var grandTotal = 0L
        notes.forEach {
            grandTotal += it.value.toLong() * it.count
        }
        binding.tvGrandTotal.text = "₹ " + DecimalFormat("#,##,##0").format(grandTotal)
    }

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

class CashNoteAdapter(
    private val notes: List<CashNote>,
    private val onAmountChanged: () -> Unit
) : RecyclerView.Adapter<CashNoteAdapter.NoteViewHolder>() {

    class NoteViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvValue: TextView = view.findViewById(R.id.tv_note_value)
        val etCount: TextInputEditText = view.findViewById(R.id.et_note_count)
        val tvTotal: TextView = view.findViewById(R.id.tv_note_total)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NoteViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_cash_note, parent, false)
        return NoteViewHolder(view)
    }

    override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
        val note = notes[position]
        holder.tvValue.text = "₹ ${note.value}"
        
        // Remove existing listener to avoid recursion or multiple triggers
        holder.etCount.removeTextChangedListener(holder.etCount.tag as? TextWatcher)
        
        holder.etCount.setText(if (note.count > 0) note.count.toString() else "")
        
        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) {
                val input = s.toString()
                note.count = if (input.isNotEmpty()) input.toIntOrNull() ?: 0 else 0
                val total = note.value.toLong() * note.count
                holder.tvTotal.text = DecimalFormat("#,##,##0").format(total)
                onAmountChanged()
            }
            override fun afterTextChanged(s: Editable?) {}
        }
        
        holder.etCount.addTextChangedListener(textWatcher)
        holder.etCount.tag = textWatcher
        
        val initialTotal = note.value.toLong() * note.count
        holder.tvTotal.text = DecimalFormat("#,##,##0").format(initialTotal)
    }

    override fun getItemCount() = notes.size
}
