package com.ElyStudio.leGaou.activities;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.viewpager2.widget.ViewPager2;


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.card.MaterialCardView;
import com.google.firebase.FirebaseApp;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.GoogleAuthProvider;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.adapter.OnboardingAdapter;
import com.ElyStudio.leGaou.databinding.ActivityOnboardingScreenBinding;
import com.ElyStudio.leGaou.models.ApiResponse;
import com.ElyStudio.leGaou.models.OnboardingItem;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.AppCompat;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
import com.ElyStudio.leGaou.utilities.Constants;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

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

public class OnboardingScreen extends AppCompat {

   ActivityOnboardingScreenBinding binding;
   OnboardingAdapter onboardingAdapter;
   private LinearLayout onboardingIndicatorLayout;
   BottomSheetDialog loginBottomSheet;

   private final String TAG = "ONBOARDING_SCREEN";

   private FirebaseAuth firebaseAuth;
   private GoogleSignInClient googleSignInClient;
   private final int REQ_SIGN_IN = 0;
   LottieAnimationView loader;
   MaterialCardView googleSignInButton;

   BottomSheetDialog noInternetBottomSheet,errorOccurredBottomSheet;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityOnboardingScreenBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        FirebaseApp.initializeApp(this);
        firebaseAuth = FirebaseAuth.getInstance();

        onboardingIndicatorLayout = binding.onboardingIndicator;

        setOnboardingData();
        binding.onboardingViewPager.setAdapter(onboardingAdapter);

        setupOnboardingIndicators();
        setCurrentOnboardingIndicator(0);

        binding.onboardingViewPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                setCurrentOnboardingIndicator(position);
            }
        });

        binding.nextBtn.setOnClickListener(v -> {
            if(binding.onboardingViewPager.getCurrentItem()+1 < onboardingAdapter.getItemCount())
            {
                binding.onboardingViewPager.setCurrentItem(binding.onboardingViewPager.getCurrentItem() + 1);
            }
            else
            {
                if(CheckInternetConnection.isInternetConnected(OnboardingScreen.this))
                {
                    showLoginBottomSheet();
                }
                else
                {
                    showNoInternetBottomSheet();
                }

            }
        });

        binding.skipBtn.setOnClickListener(v -> showLoginBottomSheet());

        GoogleSignInOptions googleSignInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)  // Ajout du DEFAULT_SIGN_IN
                .requestIdToken(Constants.DEFAULT_WEB_CLIENT_ID)
                .requestEmail()
                .requestProfile()  // Ajout de requestProfile
                .build();


        googleSignInClient = GoogleSignIn.getClient(this,googleSignInOptions);

    }

    private void signIn() {
        Intent signInIntent = googleSignInClient.getSignInIntent();
        Toast.makeText(this, "avant!", Toast.LENGTH_SHORT).show();
        startActivityForResult(signInIntent, REQ_SIGN_IN);
        Toast.makeText(this, "après!", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQ_SIGN_IN)
        {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
    }

    private void handleSignInResult(Task<GoogleSignInAccount> task) {
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            if (account != null) {
                firebaseAuthWithGoogle(account);
                Log.d(TAG, "firebaseAuthWithGoogle:" + account.getId());
            } else {
                Log.w(TAG, "Google sign in failed: account is null");
                showSignInError();
            }
        } catch (ApiException e) {
            Log.w(TAG, "Google sign in failed", e);
            String errorMessage;
            switch (e.getStatusCode()) {
                case GoogleSignInStatusCodes.SIGN_IN_CANCELLED:
                    errorMessage = "Connexion annulée";
                    break;
                case GoogleSignInStatusCodes.NETWORK_ERROR:
                    errorMessage = "Erreur réseau";
                    break;
                default:
                    errorMessage = "Erreur de connexion: " + e.getStatusCode();
            }
            Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
            loader.setVisibility(View.GONE);
            googleSignInButton.setVisibility(View.VISIBLE);
        }
    }


    private void showSignInError() {
        loader.setVisibility(View.GONE);
        googleSignInButton.setVisibility(View.VISIBLE);
        Toast.makeText(this, "Échec de la connexion Google", Toast.LENGTH_SHORT).show();
    }



    private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
        AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
        firebaseAuth.signInWithCredential(credential)
                .addOnSuccessListener(authResult -> {
                    Log.d(TAG, "Firebase auth successful");
                    String uid = firebaseAuth.getUid();
                    if (uid != null) {
                        proceedSignIn(uid,
                                account.getDisplayName(),
                                account.getEmail(),
                                uid.substring(0, Math.min(uid.length(), 4)));
                    } else {
                        Log.e(TAG, "Firebase UID is null");
                        showSignInError();
                    }
                })
                .addOnFailureListener(e -> {
                    Log.e(TAG, "Firebase auth failed", e);
                    Toast.makeText(this, "Échec de l'authentification Firebase: " + e.getMessage(),
                            Toast.LENGTH_SHORT).show();
                    loader.setVisibility(View.GONE);
                    googleSignInButton.setVisibility(View.VISIBLE);
                });
    }

    //Adding User in Database
    private void proceedSignIn(String uId,String name,String email,String inviteCode){

        if(name == null || name.equals("")){
            name = getResources().getString(R.string.guest)+ Objects.requireNonNull(firebaseAuth.getUid()).substring(0,4);
        }

        Call<ApiResponse> proceedSignInCall = ApiController.getInstance().getApi().registerUser(uId, name, email, inviteCode);

        proceedSignInCall.enqueue(new Callback<ApiResponse>() {
            @Override
            public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
                assert response.body() != null;
                if(response.body().getStatusCode() == 0)
                {
                    loginBottomSheet.cancel();
                    startActivity(new Intent(OnboardingScreen.this,AvatarSelectionScreen.class));
                    finish();
                }
                else if(response.body().getStatusCode() == 1)
                {
                    loginBottomSheet.cancel();
                    startActivity(new Intent(OnboardingScreen.this,MainActivity.class));
                    finish();
                }
                else
                {
                    loginBottomSheet.cancel();
                    showErrorOccurredBottomSheet();
                }
            }

            @Override
            public void onFailure(Call<ApiResponse> call, Throwable t) {
                loginBottomSheet.cancel();
                showErrorOccurredBottomSheet();
                Log.d(TAG,"proceedSignInCall Api Failure = "+t.getLocalizedMessage());
            }
        });

    }

    void setOnboardingData(){
        List<OnboardingItem> onboardingItemList = new ArrayList<>();

        OnboardingItem firstSlide = new OnboardingItem();
        firstSlide.setImage(R.drawable.onboarding_one_illustration);
        firstSlide.setTitle(getString(R.string.onboardingOneTitle));
        firstSlide.setDescription(getString(R.string.onboardingOneDescription));

        OnboardingItem secondSlide = new OnboardingItem();
        secondSlide.setImage(R.drawable.onboarding_two_illustration);
        secondSlide.setTitle(getString(R.string.onboardingTwoTitle));
        secondSlide.setDescription(getString(R.string.onboardingTwoDescription));

        OnboardingItem thirdSlide = new OnboardingItem();
        thirdSlide.setImage(R.drawable.onboarding_three_illustration);
        thirdSlide.setTitle(getString(R.string.onboardingThreeTitle));
        thirdSlide.setDescription(getString(R.string.onboardingThreeDescription));

        onboardingItemList.add(firstSlide);
        onboardingItemList.add(secondSlide);
        onboardingItemList.add(thirdSlide);

        onboardingAdapter = new OnboardingAdapter(onboardingItemList);
    }

    private void setupOnboardingIndicators(){

        ImageView[] indicators = new ImageView[onboardingAdapter.getItemCount()];

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);

        layoutParams.setMargins(8,0,8,0);

        for (int i = 0; i < indicators.length; i++)
        {
            indicators[i] = new ImageView(getApplicationContext());
            indicators[i].setImageDrawable(ContextCompat.
                    getDrawable(OnboardingScreen.this,R.drawable.onboarding_indicator_inactive));
            indicators[i].setLayoutParams(layoutParams);
            onboardingIndicatorLayout.addView(indicators[i]);
        }

    }

    private void setCurrentOnboardingIndicator(int index){
        int childCount = onboardingIndicatorLayout.getChildCount();

        for(int i = 0; i < childCount; i++)
        {
            ImageView imageView = (ImageView)onboardingIndicatorLayout.getChildAt(i);
            if(i == index)
            {
                imageView.setImageDrawable(ContextCompat.getDrawable(OnboardingScreen.this,R.drawable.onboarding_indicator_active));
            }
            else
            {
                imageView.setImageDrawable(ContextCompat.getDrawable(OnboardingScreen.this,R.drawable.onboarding_indicator_inactive));
            }
        }
        if(index == onboardingAdapter.getItemCount() - 1)
        {
            binding.nextBtn.setText(getString(R.string.getStarted));
        }
        else
        {
            binding.nextBtn.setText(getString(R.string.next));
        }
    }

    void showLoginBottomSheet(){

        loginBottomSheet = new BottomSheetDialog(OnboardingScreen.this,R.style.BottomSheetStyle);
        View view = LayoutInflater.from(OnboardingScreen.this).inflate(R.layout.login_bottomsheet,findViewById(R.id.loginSheet));
        loginBottomSheet.setContentView(view);

        googleSignInButton = view.findViewById(R.id.googleLoginButton);
        loader = view.findViewById(R.id.loadingAnimation);
        TextView loginGreetings = loginBottomSheet.findViewById(R.id.loginGreetings);
        TextView privacyPolicyText = loginBottomSheet.findViewById(R.id.privacyPolicyText);

        privacyPolicyText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(OnboardingScreen.this,PrivacyPolicyScreen.class));
            }
        });

        String greetings = String.format(getResources().getString(R.string.login_greetings),getResources().getString(R.string.app_name));

        loginGreetings.setText(greetings);

        googleSignInButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loader.setVisibility(View.VISIBLE);
                googleSignInButton.setVisibility(View.GONE);
                signIn();
            }
        });

        if(!OnboardingScreen.this.isFinishing())
        {
            loginBottomSheet.show();
        }
    }

    public void showNoInternetBottomSheet(){

        noInternetBottomSheet = new BottomSheetDialog(OnboardingScreen.this);
        View view = LayoutInflater.from(OnboardingScreen.this).inflate(R.layout.error_occurred_bottom_sheet,findViewById(R.id.errorOccurredBottomSheetLayout),false);
        noInternetBottomSheet.setContentView(view);

        Button contactSupportBtn = noInternetBottomSheet.findViewById(R.id.bottomSheetSecondaryButton);
        Button tryAgainBtn = noInternetBottomSheet.findViewById(R.id.bottomSheetPrimaryButton);
        ImageView bottomSheetIllustration = noInternetBottomSheet.findViewById(R.id.bottomSheetIllustraton);
        TextView bottomSheetTitle = noInternetBottomSheet.findViewById(R.id.bottomSheetTitle);
        noInternetBottomSheet.setCancelable(false);
        TextView bottomSheetSubText = noInternetBottomSheet.findViewById(R.id.bottomSheetSubText);
        contactSupportBtn.setVisibility(View.GONE);

        tryAgainBtn.setText(getResources().getString(R.string.try_again));

        tryAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CheckInternetConnection.isInternetConnected(OnboardingScreen.this))
                {
                    noInternetBottomSheet.cancel();
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(OnboardingScreen.this,view,getResources().getString(R.string.no_internet),getResources().getColor(R.color.error));
                }
            }
        });

        bottomSheetTitle.setText(getResources().getString(R.string.no_internet));
        bottomSheetSubText.setText(getResources().getString(R.string.no_internet_sub_text));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(OnboardingScreen.this,R.drawable.no_conection_illustration));

        if(!OnboardingScreen.this.isFinishing())
        {
            noInternetBottomSheet.show();
        }

    }

    public void showErrorOccurredBottomSheet(){

        errorOccurredBottomSheet = new BottomSheetDialog(OnboardingScreen.this);
        View view = LayoutInflater.from(OnboardingScreen.this).inflate(R.layout.error_occurred_bottom_sheet,findViewById(R.id.errorOccurredBottomSheetLayout),false);
        errorOccurredBottomSheet.setContentView(view);
        errorOccurredBottomSheet.setCancelable(false);
        Button contactSupportBtn = errorOccurredBottomSheet.findViewById(R.id.bottomSheetSecondaryButton);
        Button tryAgainBtn = errorOccurredBottomSheet.findViewById(R.id.bottomSheetPrimaryButton);
        ImageView bottomSheetIllustration = errorOccurredBottomSheet.findViewById(R.id.bottomSheetIllustraton);
        TextView bottomSheetTitle = errorOccurredBottomSheet.findViewById(R.id.bottomSheetTitle);
        TextView bottomSheetSubText = errorOccurredBottomSheet.findViewById(R.id.bottomSheetSubText);

        bottomSheetTitle.setText(getResources().getString(R.string.some_error_occurred));
        bottomSheetSubText.setText(getResources().getString(R.string.error_subtext));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(OnboardingScreen.this,R.drawable.error_illustration));
        contactSupportBtn.setText(getResources().getString(R.string.contact_support));
        tryAgainBtn.setText(getResources().getString(R.string.try_again));

        contactSupportBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(OnboardingScreen.this, SupportScreen.class));
            }
        });

        tryAgainBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                errorOccurredBottomSheet.cancel();
            }
        });

        if(!OnboardingScreen.this.isFinishing())
        {
            errorOccurredBottomSheet.show();
        }
    }
}