package com.example.tabbuy.ui.profile

import android.app.AlertDialog
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.example.tabbuy.R
import com.example.tabbuy.data.local.entity.PelangganEntity
import com.example.tabbuy.databinding.FragmentProfileBinding
import com.example.tabbuy.ui.MainViewModel
import kotlinx.coroutines.launch

class ProfileFragment : Fragment() {
    private var _binding: FragmentProfileBinding? = null
    private val binding get() = _binding!!
    private val viewModel: MainViewModel by viewModels()
    
    private var currentUser: PelangganEntity? = null

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

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

        val prefs = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
        val userEmail = prefs.getString("user_email", null)
        
        if (userEmail != null) {
            loadUserData(userEmail)
        } else {
            findNavController().navigate(R.id.action_profileFragment_to_loginFragment)
        }

        // EDIT NAMA lewat Layout Click (Sekarang lebih jelas dengan Icon Edit)
        binding.layoutEditName.setOnClickListener {
            currentUser?.let { showEditNameDialog(it) }
        }

        binding.btnHapusAkun.setOnClickListener {
            currentUser?.let { showDeleteAccountDialog(it) }
        }

        binding.btnLogout.setOnClickListener {
            prefs.edit().remove("user_email").apply()
            findNavController().navigate(R.id.action_profileFragment_to_loginFragment)
        }
    }

    private fun loadUserData(email: String) {
        lifecycleScope.launch {
            val user = viewModel.login(email)
            if (user != null) {
                currentUser = user
                binding.tvProfileNama.text = user.nama
                binding.tvProfileEmail.text = user.email
            }
        }
    }

    private fun showDeleteAccountDialog(user: PelangganEntity) {
        AlertDialog.Builder(requireContext())
            .setTitle("Hapus Akun")
            .setMessage("Apakah Anda yakin ingin menghapus akun '${user.nama}' secara permanen?")
            .setPositiveButton("Hapus") { _, _ ->
                viewModel.deletePelanggan(user)
                val prefs = requireActivity().getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
                prefs.edit().remove("user_email").apply()
                Toast.makeText(context, "Akun berhasil dihapus", Toast.LENGTH_SHORT).show()
                findNavController().navigate(R.id.action_profileFragment_to_loginFragment)
            }
            .setNegativeButton("Batal", null)
            .show()
    }

    private fun showEditNameDialog(user: PelangganEntity) {
        val editText = EditText(context)
        editText.setText(user.nama)

        AlertDialog.Builder(context)
            .setTitle("Ubah Nama")
            .setView(editText)
            .setPositiveButton("Simpan") { _, _ ->
                val namaBaru = editText.text.toString()
                if (namaBaru.isNotEmpty()) {
                    val userUpdate = user.copy(nama = namaBaru)
                    viewModel.updatePelanggan(userUpdate)
                    binding.tvProfileNama.text = namaBaru
                    currentUser = userUpdate
                    Toast.makeText(context, "Nama berhasil diperbarui", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("Batal", null)
            .show()
    }

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