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.EditText
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.Note
import com.rugvedsarika.toolbox.databinding.FragmentNotesBinding
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

class NotesFragment : Fragment() {

    private var _binding: FragmentNotesBinding? = 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 = FragmentNotesBinding.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 = NoteAdapter { note ->
            showDeleteDialog(note)
        }
        binding.rvNotes.adapter = adapter

        lifecycleScope.launch {
            dao.getAllNotes().collect { notes ->
                if (notes.isEmpty()) {
                    dao.insertNote(Note(content = "Welcome to ToolBox! 🛠️ This is your Quick Notes area."))
                    dao.insertNote(Note(content = "You can use this for shopping lists, reminders, or quick thoughts."))
                    dao.insertNote(Note(content = "Long press any note to delete it. 🗑️"))
                } else {
                    adapter.submitList(notes)
                }
            }
        }

        binding.fabAddNote.setOnClickListener {
            showAddNoteDialog()
        }
    }

    private fun showAddNoteDialog() {
        val editText = EditText(requireContext())
        editText.hint = "Type your note here..."
        editText.setPadding(40, 40, 40, 40)

        AlertDialog.Builder(requireContext())
            .setTitle("New Note")
            .setView(editText)
            .setPositiveButton("Save") { _, _ ->
                val content = editText.text.toString()
                if (content.isNotBlank()) {
                    lifecycleScope.launch {
                        dao.insertNote(Note(content = content))
                    }
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    private fun showDeleteDialog(note: Note) {
        AlertDialog.Builder(requireContext())
            .setTitle("Delete Note")
            .setMessage("Are you sure you want to delete this note?")
            .setPositiveButton("Delete") { _, _ ->
                lifecycleScope.launch {
                    dao.deleteNote(note)
                }
            }
            .setNegativeButton("No", null)
            .show()
    }

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

class NoteAdapter(private val onNoteLongClick: (Note) -> Unit) : RecyclerView.Adapter<NoteAdapter.NoteViewHolder>() {

    private var notes = emptyList<Note>()

    fun submitList(newList: List<Note>) {
        notes = newList
        notifyDataSetChanged()
    }

    class NoteViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val tvContent: TextView = view.findViewById(R.id.tv_content)
        val tvDate: TextView = view.findViewById(R.id.tv_date)
    }

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

    override fun onBindViewHolder(holder: NoteViewHolder, position: Int) {
        val note = notes[position]
        holder.tvContent.text = note.content
        holder.tvDate.text = SimpleDateFormat("MMM dd, yyyy HH:mm", Locale.getDefault()).format(Date(note.timestamp))
        
        holder.itemView.setOnLongClickListener {
            onNoteLongClick(note)
            true
        }
    }

    override fun getItemCount() = notes.size
}
