package com.example.tabbuy.ui.authentication

import android.os.Bundle
import android.util.Patterns
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.tabbuy.data.local.entity.PelangganEntity
import com.example.tabbuy.databinding.FragmentRegisterBinding
import com.example.tabbuy.ui.MainViewModel
import com.google.android.material.snackbar.Snackbar

class RegisterFragment : Fragment() {
    private var _binding: FragmentRegisterBinding? = null
    private val binding get() = _binding!!
    private val viewModel: MainViewModel by viewModels()

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

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

        binding.btnRegister.setOnClickListener {
            val nama = binding.etNama.text.toString()
            val email = binding.etEmail.text.toString()
            val password = binding.etPassword.text.toString()

            if (validateInput(nama, email, password)) {
                val pelanggan = PelangganEntity(nama = nama, email = email, password = password)
                viewModel.register(pelanggan)
                // UPGRADE: Ganti Toast ke Snackbar untuk feedback yang lebih premium
                Snackbar.make(binding.root, "Registrasi Berhasil! Silakan Login", Snackbar.LENGTH_LONG).show()
                findNavController().popBackStack()
            }
        }

        binding.tvBackToLogin.setOnClickListener {
            findNavController().popBackStack()
        }
    }

    private fun validateInput(nama: String, email: String, password: String): Boolean {
        var isValid = true
        if (nama.isEmpty()) {
            binding.tilNama.error = "Nama tidak boleh kosong"
            isValid = false
        } else {
            binding.tilNama.error = null
        }

        if (email.isEmpty() || !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            binding.tilEmail.error = "Email tidak valid"
            isValid = false
        } else {
            binding.tilEmail.error = null
        }

        if (password.length < 6) {
            binding.tilPassword.error = "Password minimal 6 karakter"
            isValid = false
        } else {
            binding.tilPassword.error = null
        }
        return isValid
    }

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