package com.rugvedsarika.toolbox.utilities

import android.app.AlertDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import com.rugvedsarika.toolbox.R
import com.rugvedsarika.toolbox.database.AppDatabase
import com.rugvedsarika.toolbox.database.ChecklistItem
import com.rugvedsarika.toolbox.databinding.FragmentChecklistBinding
import kotlinx.coroutines.launch

class ChecklistFragment : Fragment() {

    private var _binding: FragmentChecklistBinding? = 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 = FragmentChecklistBinding.inflate(inflater, container, false)
        return binding.root
    }

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

        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }

        val adapter = ChecklistAdapter(
            onToggle = { item ->
                lifecycleScope.launch {
                    dao.updateChecklistItem(item)
                }
            },
            onDelete = { item ->
                lifecycleScope.launch {
                    dao.deleteChecklistItem(item)
                }
            }
        )
        binding.rvChecklist.adapter = adapter

        lifecycleScope.launch {
            dao.getAllChecklistItems().collect { items ->
                if (items.isEmpty()) {
                    dao.insertChecklistItem(ChecklistItem(text = "Try the EMI Calculator 💰"))
                    dao.insertChecklistItem(ChecklistItem(text = "Generate a strong password 🔐"))
                    dao.insertChecklistItem(ChecklistItem(text = "Check the GST rates 📈"))
                    dao.insertChecklistItem(ChecklistItem(text = "Convert some units 📐"))
                    dao.insertChecklistItem(ChecklistItem(text = "Explore the Age Calculator 🎂"))
                } else {
                    adapter.submitList(items)
                }
            }
        }

        binding.fabAddItem.setOnClickListener {
            showAddItemDialog()
        }
    }

    private fun showAddItemDialog() {
        val editText = EditText(requireContext())
        editText.hint = "Task name..."
        editText.setPadding(40, 40, 40, 40)

        AlertDialog.Builder(requireContext())
            .setTitle("Add Task")
            .setView(editText)
            .setPositiveButton("Add") { _, _ ->
                val text = editText.text.toString()
                if (text.isNotBlank()) {
                    lifecycleScope.launch {
                        dao.insertChecklistItem(ChecklistItem(text = text))
                    }
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

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

class ChecklistAdapter(
    private val onToggle: (ChecklistItem) -> Unit,
    private val onDelete: (ChecklistItem) -> Unit
) : RecyclerView.Adapter<ChecklistAdapter.ChecklistViewHolder>() {

    private var items = emptyList<ChecklistItem>()

    fun submitList(newList: List<ChecklistItem>) {
        items = newList
        notifyDataSetChanged()
    }

    class ChecklistViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val cbItem: CheckBox = view.findViewById(R.id.cb_item)
        val tvText: TextView = view.findViewById(R.id.tv_item_text)
        val btnDelete: ImageButton = view.findViewById(R.id.btn_delete)
    }

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

    override fun onBindViewHolder(holder: ChecklistViewHolder, position: Int) {
        val item = items[position]
        holder.tvText.text = item.text
        
        holder.cbItem.setOnCheckedChangeListener(null)
        holder.cbItem.isChecked = item.isChecked
        
        holder.cbItem.setOnCheckedChangeListener { _, isChecked ->
            onToggle(item.copy(isChecked = isChecked))
        }

        holder.btnDelete.setOnClickListener {
            onDelete(item)
        }
    }

    override fun getItemCount() = items.size
}
