package com.example.orderly.ui.auth

import android.os.Bundle
import android.util.Patterns
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.example.orderly.R
import com.example.orderly.databinding.FragmentLoginBinding
import com.example.orderly.ui.OrderLyApplication
import com.example.orderly.ui.OrderLyViewModel
import com.example.orderly.ui.OrderLyViewModelFactory

class LoginFragment : Fragment() {
    private var _binding: FragmentLoginBinding? = 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 = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root
    }

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

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

        binding.tvRegisterLink.setOnClickListener {
            findNavController().navigate(R.id.action_loginFragment_to_registerFragment)
        }

        binding.btnLogin.setOnClickListener {
            if (validateInput()) {
                val email = binding.etUsername.text.toString()
                viewModel.login(email)
            }
        }

        viewModel.loginStatus.observe(viewLifecycleOwner) { user ->
            if (user != null) {
                val pref = requireContext().getSharedPreferences("session", 0)
                pref.edit()
                    .putBoolean("isLogin", true)
                    .apply()

                Toast.makeText(requireContext(), "Login Berhasil", Toast.LENGTH_SHORT).show()
                findNavController().navigate(R.id.action_loginFragment_to_splashFragment)
            } else {
                Toast.makeText(requireContext(), "Email tidak terdaftar", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun validateInput(): Boolean {
        val email = binding.etUsername.text.toString().trim()
        val password = binding.etPassword.text.toString().trim()

        var isValid = true

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

        if (password.isEmpty()) {
            binding.tlPassword.error = "Password tidak boleh kosong"
            isValid = false
        } else if (password.length < 6) {
            binding.tlPassword.error = "Password minimal 6 karakter"
            isValid = false
        } else {
            binding.tlPassword.error = null
        }

        return isValid
    }

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