package com.rugvedsarika.privatelog.ui.auth

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import com.rugvedsarika.privatelog.R
import com.rugvedsarika.privatelog.databinding.FragmentAuthBinding

class AuthFragment : Fragment(R.layout.fragment_auth) {

    private var _binding: FragmentAuthBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: AuthViewModel

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        _binding = FragmentAuthBinding.bind(view)
        viewModel = ViewModelProvider(this)[AuthViewModel::class.java]

        setupObservers()
        setupListeners()
    }

    private fun setupListeners() {
        binding.btnAction.setOnClickListener {
            val pin = binding.etPin.text.toString()
            if (pin.length == 4) {
                if (viewModel.isPinSet.value == true) {
                    viewModel.verifyPin(pin)
                } else {
                    viewModel.setPin(pin)
                }
            } else {
                Toast.makeText(requireContext(), "Enter 4 digits", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun setupObservers() {
        viewModel.isPinSet.observe(viewLifecycleOwner) { isSet ->
            if (isSet) {
                binding.tvTitle.text = "Enter PIN"
                binding.btnAction.text = "Unlock"
            } else {
                binding.tvTitle.text = "Create PIN"
                binding.btnAction.text = "Set PIN"
            }
        }

        viewModel.authState.observe(viewLifecycleOwner) { state ->
            when (state) {
                is AuthState.Authenticated -> {
                    findNavController().navigate(R.id.action_authFragment_to_homeFragment)
                }
                is AuthState.InvalidPin -> {
                    binding.etPin.error = "Incorrect PIN"
                }
                else -> {}
            }
        }
    }



    private fun checkBiometric() {
        if (viewModel.isPinSet.value == true) {
            // Only prompt if pin is set
            val biometricManager = androidx.biometric.BiometricManager.from(requireContext())
            if (biometricManager.canAuthenticate(androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG) == androidx.biometric.BiometricManager.BIOMETRIC_SUCCESS) {
                showBiometricPrompt()
            }
        }
    }

    private fun showBiometricPrompt() {
        val executor = androidx.core.content.ContextCompat.getMainExecutor(requireContext())
        val biometricPrompt = androidx.biometric.BiometricPrompt(this, executor,
            object : androidx.biometric.BiometricPrompt.AuthenticationCallback() {
                override fun onAuthenticationSucceeded(result: androidx.biometric.BiometricPrompt.AuthenticationResult) {
                    super.onAuthenticationSucceeded(result)
                    viewModel.biometricAuthSuccess()
                }
            })

        val promptInfo = androidx.biometric.BiometricPrompt.PromptInfo.Builder()
            .setTitle("Unlock PrivateLog")
            .setSubtitle("Log in using your biometric credential")
            .setNegativeButtonText("Use PIN")
            .build()

        biometricPrompt.authenticate(promptInfo)
    }

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

    override fun onResume() {
        super.onResume()
        // Optional: Auto-prompt on resume if convenient, but can be annoying. 
        // Let's call it from onViewCreated or allow a button for it.
        // For now, let's call it once in onViewCreated via observing isPinSet?
        // Or better, add a button "Biometric Unlock" if available.
    }
}
