package com.rugvedsarika.easymath.ui.profile

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.easymath.EasyMathApp
import com.rugvedsarika.easymath.R
import com.rugvedsarika.easymath.data.db.UserEntity
import com.rugvedsarika.easymath.databinding.FragmentProfileSelectionBinding
import com.rugvedsarika.easymath.viewmodel.MathViewModel
import com.rugvedsarika.easymath.viewmodel.MathViewModelFactory

class ProfileSelectionFragment : Fragment() {

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

    private val viewModel: MathViewModel by activityViewModels {
        val app = requireActivity().application as EasyMathApp
        MathViewModelFactory(app.repository, app.audioManager)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentProfileSelectionBinding.inflate(inflater, container, false)
        return binding.root
    }

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

        val adapter = ProfileAdapter { user ->
            onUserSelected(user)
        }
        binding.recyclerProfiles.adapter = adapter

        viewModel.allUsers.observe(viewLifecycleOwner) { users ->
            adapter.submitList(users)
        }

        binding.fabAddUser.setOnClickListener {
            showAddUserDialog()
        }
    }

    private fun showAddUserDialog() {
        val dialogView = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_add_user, null)
        val editName = dialogView.findViewById<EditText>(R.id.editUserName)

        AlertDialog.Builder(requireContext())
            .setView(dialogView)
            .setPositiveButton("Add") { _, _ ->
                val name = editName.text.toString()
                if (name.isNotEmpty()) {
                    viewModel.addUser(name)
                }
            }
            .setNegativeButton("Cancel", null)
            .show()
    }

    private fun onUserSelected(user: UserEntity) {
        viewModel.setUserId(user.id)
        findNavController().navigate(R.id.action_profile_to_home)
    }

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