package com.ElyStudio.leGaou.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.messaging.FirebaseMessaging;
import com.ElyStudio.leGaou.R;
import com.ElyStudio.leGaou.activities.AboutUsScreen;
import com.ElyStudio.leGaou.activities.ChangeLanguageScreen;
import com.ElyStudio.leGaou.activities.OnboardingScreen;
import com.ElyStudio.leGaou.activities.PlayingHistoryScreen;
import com.ElyStudio.leGaou.activities.PrivacyPolicyScreen;
import com.ElyStudio.leGaou.activities.SupportScreen;
import com.ElyStudio.leGaou.activities.UserProfileScreen;
import com.ElyStudio.leGaou.activities.WalletScreen;
import com.ElyStudio.leGaou.databinding.FragmentAccountBinding;
import com.ElyStudio.leGaou.models.AppLanguage;
import com.ElyStudio.leGaou.models.UserData;
import com.ElyStudio.leGaou.utilities.ApiController;
import com.ElyStudio.leGaou.utilities.CheckInternetConnection;
import com.ElyStudio.leGaou.utilities.Constants;
import com.ElyStudio.leGaou.utilities.QuizzeSnackBar;
import com.squareup.picasso.Picasso;

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

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

public class AccountFragment extends Fragment {

    public AccountFragment() {
        // Required empty public constructor
    }

    FragmentAccountBinding binding;
    Context contextFragment;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    boolean appMode,isNotificationEnabled;
    BottomSheetDialog noInternetBottomSheet,errorOccurredBottomSheet,logoutBottomSheet;
    List<AppLanguage> appLanguageList;

    public static final String TAG = "ACCOUNT_FRAGMENT";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = FragmentAccountBinding.inflate(inflater,container,false);
        getUserData();

        appLanguageList = new ArrayList<>();

        sharedPreferences = getContextNullSafety().getSharedPreferences(Constants.appPrefs,Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        appMode = sharedPreferences.getBoolean(Constants.appColorMode,false);
        isNotificationEnabled = sharedPreferences.getBoolean(Constants.notificationsEnabled,false);

        binding.walledCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContextNullSafety(), WalletScreen.class));
            }
        });

        binding.historyCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContextNullSafety(), PlayingHistoryScreen.class));
            }
        });

        binding.privacyPolicyCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContextNullSafety(), PrivacyPolicyScreen.class));
            }
        });

        binding.aboutUsCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContextNullSafety(), AboutUsScreen.class));
            }
        });

        binding.editBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContextNullSafety(), UserProfileScreen.class));
            }
        });

        binding.supportCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getContextNullSafety(), SupportScreen.class));
            }
        });

        binding.appColorModeSwitch.setChecked(appMode);

        binding.appColorModeSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                editor.putBoolean(Constants.appColorMode,isChecked);
                editor.apply();
                if (isChecked)
                {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                }
                else
                {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                }


            }
        });

        binding.notificationSwitch.setChecked(isNotificationEnabled);



        binding.notificationSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(isNotificationEnabled)
                {
                    FirebaseMessaging.getInstance().unsubscribeFromTopic(Constants.NOTIFICATION_TOPIC)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if(task.isSuccessful())
                                    {
                                        editor.putBoolean(Constants.notificationsEnabled,false);
                                        editor.apply();
                                    }
                                }
                            });
                }
                else
                {
                    FirebaseMessaging.getInstance().subscribeToTopic(Constants.NOTIFICATION_TOPIC)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if(task.isSuccessful())
                                    {
                                        editor.putBoolean(Constants.notificationsEnabled,true);
                                        editor.apply();
                                    }
                                }
                            });
                }

            }
        });

        binding.changeLanguageCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivityNullSafety(), ChangeLanguageScreen.class));
            }
        });

        binding.logoutCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLogoutBottomSheet();
            }
        });

        return binding.getRoot();
    }
    private void getUserData(){

        if(CheckInternetConnection.isInternetConnected(getContextNullSafety()))
        {
            Call<UserData> getUserDataCall = ApiController.getInstance().getApi().getUserData(FirebaseAuth.getInstance().getUid());
            getUserDataCall.enqueue(new Callback<UserData>() {
                @Override
                public void onResponse(Call<UserData> call, Response<UserData> response) {
                    if(response.body().getStatusCode() == 0)
                    {
                        setUserData(response.body());
                    }
                    else
                    {
                        Log.d(TAG,response.body().getMessage());
                        showErrorOccurredBottomSheet();
                    }
                }

                @Override
                public void onFailure(Call<UserData> call, Throwable t) {
                    Log.d(TAG,"getUserDataCall Failure = "+t.getLocalizedMessage());
                    showErrorOccurredBottomSheet();
                }
            });
        }
        else
        {
            showNoInternetBottomSheet();
        }



    }

    private void setUserData(UserData userData){

        if(!userData.getAvatar().trim().equals(""))
        {
            Picasso.get().load(Constants.ADMIN_PANEL_URL+userData.getAvatar()).into(binding.userAccountAvatar);
        }
        else
        {
            binding.userAccountAvatar.setImageDrawable(ContextCompat.getDrawable(getContextNullSafety(),R.drawable.image_placeholder));
        }
        if (!userData.getUserLevelIcon().trim().equals(""))
        {
            Picasso.get().load(Constants.ADMIN_PANEL_URL+userData.getUserLevelIcon()).into(binding.userLevelIcon);
        }
        else
        {
            binding.userLevelIcon.setImageDrawable(ContextCompat.getDrawable(getContextNullSafety(),R.drawable.image_placeholder));
        }

        binding.accountUserName.setText(userData.getName());
        binding.userAccountEmail.setText(userData.getEmail());
        binding.accountUserLevel.setText(userData.getUserLevel());
        binding.accountUserCoins.setText(String.valueOf(userData.getCoins()));
        binding.accountUserTotalCoins.setText(String.valueOf(userData.getTotalCoins()));


    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        contextFragment = context;
    }

    /**CALL THIS IF YOU NEED CONTEXT*/
    public Context getContextNullSafety() {
        if (getContext() != null) return getContext();
        if (getActivity() != null) return getActivity();
        if (contextFragment != null) return contextFragment;
        if (getView() != null && getView().getContext() != null) return getView().getContext();
        if (requireContext() != null) return requireContext();
        if (requireActivity() != null) return requireActivity();
        if (requireView() != null && requireView().getContext() != null)
            return requireView().getContext();

        return null;
    }

    public FragmentActivity getActivityNullSafety() {
        if (getContextNullSafety() != null && getContextNullSafety() instanceof FragmentActivity) {
            return (FragmentActivity) getContextNullSafety();
        }
        return null;
    }

    public void showNoInternetBottomSheet(){

        noInternetBottomSheet = new BottomSheetDialog(getContextNullSafety());
        View view = LayoutInflater.from(getContextNullSafety()).inflate(R.layout.error_occurred_bottom_sheet,getActivityNullSafety().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(getContextNullSafety()))
                {
                    getUserData();
                    noInternetBottomSheet.cancel();
                }
                else
                {
                    QuizzeSnackBar.showSnackBar(getContextNullSafety(),view,getActivityNullSafety().getResources().getString(R.string.no_internet),getResources().getColor(R.color.error));
                }
            }
        });

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

        if(!getActivityNullSafety().isFinishing())
        {
            noInternetBottomSheet.show();
        }

    }

    public void showErrorOccurredBottomSheet(){

        errorOccurredBottomSheet = new BottomSheetDialog(getContextNullSafety());
        View view = LayoutInflater.from(getContextNullSafety()).inflate(R.layout.error_occurred_bottom_sheet,getActivityNullSafety().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(getActivityNullSafety().getResources().getString(R.string.some_error_occurred));
        bottomSheetSubText.setText(getActivityNullSafety().getResources().getString(R.string.error_subtext));
        bottomSheetIllustration.setImageDrawable(ContextCompat.getDrawable(getContextNullSafety(),R.drawable.error_illustration));
        contactSupportBtn.setText(getActivityNullSafety().getResources().getString(R.string.contact_support));
        tryAgainBtn.setText(getActivityNullSafety().getResources().getString(R.string.try_again));

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

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

        if(!getActivityNullSafety().isFinishing())
        {
            errorOccurredBottomSheet.show();
        }
    }

    public void showLogoutBottomSheet(){

        logoutBottomSheet = new BottomSheetDialog(getActivityNullSafety());
        View view = LayoutInflater.from(getContextNullSafety()).inflate(R.layout.logout_bottom_sheet,(ConstraintLayout) binding.getRoot().findViewById(R.id.logoutLayout),false);
        logoutBottomSheet.setContentView(view);
        Button cancelButton = logoutBottomSheet.findViewById(R.id.cancelLogoutBtn);
        Button logoutButton = logoutBottomSheet.findViewById(R.id.logoutBtn);

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

        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseAuth.getInstance().signOut();
                startActivity(new Intent(getActivityNullSafety(),OnboardingScreen.class));
                getActivityNullSafety().finish();
            }
        });

        if(!getActivityNullSafety().isFinishing())
        {
            logoutBottomSheet.show();
        }
    }
}