package com.example.orderly.ui.profile

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.orderly.ui.OrderLyApplication
import com.example.orderly.R
import com.example.orderly.databinding.FragmentProfileBinding
import com.example.orderly.ui.OrderLyViewModel
import com.example.orderly.ui.OrderLyViewModelFactory

class ProfileFragment : Fragment() {
    private var _binding: FragmentProfileBinding? = null
    private val binding get() = _binding!!

    private val viewModel: OrderLyViewModel by viewModels {
        OrderLyViewModelFactory((requireActivity().application as OrderLyApplication).repository)
    }

    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)

        binding.btnBack.setOnClickListener {
            findNavController().navigateUp()
        }

        viewModel.allUsers.observe(viewLifecycleOwner) { users ->
            if (users.isNotEmpty()) {
                val user = users.last()
                binding.tvProfileName.text = user.username
                binding.tvProfileEmail.text = user.email
            }
        }

        binding.btnEditProfile.setOnClickListener {
            Toast.makeText(requireContext(), "Fitur Edit Profil segera hadir!", Toast.LENGTH_SHORT).show()
        }

        binding.btnOrderHistory.setOnClickListener {
            Toast.makeText(requireContext(), "Riwayat pesanan Anda masih kosong", Toast.LENGTH_SHORT).show()
        }

        binding.btnLogout.setOnClickListener {
            showLogoutDialog()
        }
    }

    private fun showLogoutDialog() {
        AlertDialog.Builder(requireContext())
            .setTitle("Logout")
            .setMessage("Apakah Anda yakin ingin keluar?")
            .setPositiveButton("Ya") { _, _ ->
                logout()
            }
            .setNegativeButton("Tidak", null)
            .show()
    }

    private fun logout() {
        val pref = requireContext().getSharedPreferences("session", Context.MODE_PRIVATE)
        pref.edit().clear().apply()
        findNavController().navigate(R.id.action_global_welcomeFragment)
    }

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