package com.github.libretube.ui.dialogs

import android.app.Dialog
import android.os.Bundle
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.lifecycleScope
import com.github.libretube.R
import com.github.libretube.api.PanelAuthHelper
import com.github.libretube.constants.IntentData
import com.github.libretube.databinding.DialogLoginBinding
import com.github.libretube.helpers.PreferenceHelper
import com.github.libretube.ui.preferences.InstanceSettings
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginDialogFragment : DialogFragment() {
    private lateinit var binding: DialogLoginBinding

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        binding = DialogLoginBinding.inflate(layoutInflater)

        return MaterialAlertDialogBuilder(requireContext())
            .setTitle(R.string.login_register)
            .setView(binding.root)
            .setPositiveButton(R.string.login) { _, _ ->
                // Button click handled in onResume to prevent dialog dismissal
            }
            .setNegativeButton(R.string.cancel, null)
            .show()
            .apply {
                // Override positive button to handle validation and prevent auto-dismiss
                getButton(android.app.AlertDialog.BUTTON_POSITIVE).setOnClickListener {
                    performLogin()
                }
            }
    }

    private fun performLogin() {
        val username = binding.username.text?.toString()?.trim().orEmpty()
        val password = binding.password.text?.toString().orEmpty()

        if (username.isEmpty() || password.isEmpty()) {
            Toast.makeText(requireContext(), R.string.empty, Toast.LENGTH_SHORT).show()
            return
        }

        binding.progressBar.visibility = android.view.View.VISIBLE
        binding.username.isEnabled = false
        binding.password.isEnabled = false

        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val result = PanelAuthHelper.realizarLogin(username, password)
                withContext(Dispatchers.Main) {
                    binding.progressBar.visibility = android.view.View.GONE
                    binding.username.isEnabled = true
                    binding.password.isEnabled = true

                    if (result.isSuccess) {
                        val loginResponse = result.getOrNull()
                        if (loginResponse?.status?.equals("success", ignoreCase = true) == true && !loginResponse.token.isNullOrEmpty()) {
                            // Store token and username
                            PreferenceHelper.setToken(loginResponse.token!!)
                            PreferenceHelper.setUsername(loginResponse.username ?: username)

                            Toast.makeText(requireContext(), R.string.loggedIn, Toast.LENGTH_SHORT).show()

                            // Notify InstanceSettings that login was successful
                            setFragmentResult(
                                InstanceSettings.INSTANCE_DIALOG_REQUEST_KEY,
                                bundleOf(IntentData.loginTask to true)
                            )

                            dismiss()
                        } else {
                            Toast.makeText(
                                requireContext(),
                                loginResponse?.status ?: getString(R.string.unknown_error),
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    } else {
                        Toast.makeText(
                            requireContext(),
                            R.string.unknown_error,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    binding.progressBar.visibility = android.view.View.GONE
                    binding.username.isEnabled = true
                    binding.password.isEnabled = true
                    Toast.makeText(requireContext(), R.string.server_error, Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}
