package com.rugvedsarika.privatelog.ui.editor

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.privatelog.PrivateLogApp
import com.rugvedsarika.privatelog.R
import com.rugvedsarika.privatelog.databinding.FragmentEditorBinding
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class EditorFragment : Fragment(R.layout.fragment_editor) {

    private var _binding: FragmentEditorBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: EditorViewModel
    private var noteId: Long = 0L

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentEditorBinding.bind(view)

        val repository = (requireActivity().application as PrivateLogApp).repository
        val factory = EditorViewModelFactory(repository)
        viewModel = ViewModelProvider(this, factory)[EditorViewModel::class.java]

        arguments?.let {
            noteId = it.getLong("noteId", 0L)
        }

        if (noteId != 0L) {
            viewModel.loadNote(noteId)
        }

        viewModel.currentNote.observe(viewLifecycleOwner) { note ->
            note?.let {
                if (binding.etTitle.text.isEmpty()) binding.etTitle.setText(it.title)
                if (binding.etContent.text.isEmpty()) binding.etContent.setText(it.content)
            }
        }

        binding.btnSave.setOnClickListener {
            val title = binding.etTitle.text.toString()
            val content = binding.etContent.text.toString()
            if (title.isNotEmpty() || content.isNotEmpty()) {
                viewModel.saveNote(title, content, noteId)
                findNavController().popBackStack()
            } else {
                Toast.makeText(context, "Empty note discarded", Toast.LENGTH_SHORT).show()
                findNavController().popBackStack()
            }
        }
        
        binding.btnDelete.setOnClickListener {
            if (noteId != 0L) {
                android.app.AlertDialog.Builder(requireContext())
                    .setTitle("Delete Note")
                    .setMessage("Are you sure you want to delete this note?")
                    .setPositiveButton("Delete") { _, _ ->
                        lifecycleScope.launch {
                            viewModel.deleteNote(noteId)
                            findNavController().popBackStack()
                        }
                    }
                    .setNegativeButton("Cancel", null)
                    .show()
            } else {
                // New note being discarded
                findNavController().popBackStack()
            }
        }
    }

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