package com.utopiaindustries.qualitychecker.ui.activities;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.utopiaindustries.qualitychecker.R;
import com.utopiaindustries.qualitychecker.service.InspectionReportService;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;

import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginActivity extends AppCompatActivity {

    private TextInputEditText username,password;
    private ProgressBar progressBar;
    private Button loginButton;
    private InspectionReportService reportService;
    TextView txtVersion;

    @SuppressLint("SourceLockedOrientationActivity")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        if( ! isNetworkConnected() ){
            Toast.makeText( this, "No Internet Connection", Toast.LENGTH_LONG ).show();
        }
        reportService = InspectionReportService.getInstance();
        isUserAlreadyLoginAndAuthorize();
        setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        username = findViewById( R.id.username );
        password = findViewById( R.id.password );
        loginButton = findViewById( R.id.login_btn );
        progressBar = findViewById( R.id.progressBar );
        txtVersion = findViewById(R.id.txt_version);

        SharedPreferences sharedPreferences = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();

        setAppVersion();

        loginButton.setOnClickListener(v -> {
            try {
                progressBar.setVisibility( View.VISIBLE );
                String usernameStr = Objects.requireNonNull( username.getText() ).toString().trim();
                String passwordStr = Objects.requireNonNull( password.getText() ).toString().trim();
                // check both are valid
                if( ! usernameStr.isEmpty() && ! passwordStr.isEmpty() ) {
                    reportService.isUserAuthenticated(usernameStr, passwordStr, new String[]{"ROLE_UIM_QA_APP_ACCESS_YES"}, new Callback<Boolean>() {
                        @Override
                        public void onResponse(Call<Boolean> call, Response<Boolean> response) {
                            if( response.isSuccessful() && response.body() != null && response.body() ){
                                editor.putString("username", usernameStr );
                                editor.putString("password", passwordStr );
                                editor.apply();
                                progressBar.setVisibility( View.INVISIBLE );
                                Intent intent = new Intent( LoginActivity.this, HomeActivity.class );
                                startActivity( intent );
                                // close login screen
                                LoginActivity.this.finish();
                            } else {
                                progressBar.setVisibility( View.INVISIBLE );
                                Snackbar.make( v, "Invalid Credential or Access not Authorized", Snackbar.LENGTH_LONG ).show();
                            }
                        }
                        @Override
                        public void onFailure(Call<Boolean> call, Throwable t) {
                            progressBar.setVisibility( View.INVISIBLE );
                            System.out.println( t.getMessage() );
                            Snackbar.make( v, "Something went wrong", Snackbar.LENGTH_LONG ).show();
                        }
                    });
                }
                else {
                    Snackbar.make( v, "Please Enter Your Credentials!!", Snackbar.LENGTH_LONG ).show();
                    progressBar.setVisibility( View.INVISIBLE );
                }
            } catch ( NullPointerException exception ){
                Snackbar.make( v, Objects.requireNonNull( exception.getMessage() ), Snackbar.LENGTH_LONG ).show();
            }
        });
    }

    public void setAppVersion() {
        PackageManager packageManager = getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo( getPackageName(), 0 );
            txtVersion.setText(String.format("Version: %s", info.versionName));

        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    private void isUserAlreadyLoginAndAuthorize() {
        SharedPreferences sharedPreferences = getSharedPreferences("login_prefs", Context.MODE_PRIVATE);

        String username = sharedPreferences.getString("username", null);
        String password = sharedPreferences.getString("password", null);
        if( username != null && ! username.trim().isEmpty() && password != null && !password.trim().isEmpty() ){
            Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
            startActivity(intent);
            // close login screen
            LoginActivity.this.finish();
        }
//        reportService.isUserAuthenticated(username,
//                password,
//                new String[]{"ROLE_UIM_QA_APP_ACCESS_YES"},
//                new Callback<Boolean>() {
//                    @Override
//                    public void onResponse(Call<Boolean> call, Response<Boolean> response) {
//                        if (response.isSuccessful()) {
//                            boolean isAuthenticated = response.body();
//                            if (isAuthenticated) {
//                                Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
//                                startActivity(intent);
//                                // close login screen
//                                LoginActivity.this.finish();
//                            }
//                        }
//                    }
//                    @Override
//                    public void onFailure(Call<Boolean> call, Throwable t) {
//                        Log.d(t.getMessage(), "onFailure: ");
//                    }
//        });
    }

    private boolean isNetworkConnected() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }
}