package com.app.rewardapp.ui.fragments;

import static com.app.rewardapp.util.Constant_Api.App;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import com.app.rewardapp.R;
import com.app.rewardapp.Responsemodel.CallbackResp;
import com.app.rewardapp.databinding.FragmentProfileBinding;
import com.app.rewardapp.restApi.ApiClient;
import com.app.rewardapp.restApi.ApiInterface;
import com.app.rewardapp.ui.activity.AboutusActivity;
import com.app.rewardapp.ui.activity.FrontLogin;
import com.app.rewardapp.ui.activity.WithdrawActivity;
import com.app.rewardapp.util.Fun;
import com.app.rewardapp.util.Session;

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

public class Profile extends Fragment {
    FragmentProfileBinding binding;
    Session session;
    Activity activity;
    private AlertDialog dialog_logout,loading;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding=FragmentProfileBinding.inflate(getLayoutInflater());
        session = new Session(getActivity());
        activity=getActivity();
        loading = Fun.loading(getActivity());

        dialog_logout = new AlertDialog.Builder(activity).setView(LayoutInflater.from(activity).inflate(R.layout.layout_dialog, null)).create();
        dialog_logout.getWindow().setBackgroundDrawableResource(R.color.transparent);
        dialog_logout.getWindow().setWindowAnimations(R.style.Dialoganimation);
        dialog_logout.setCanceledOnTouchOutside(false);

        binding.email.setText("   "+session.getData(session.EMAIL));
        binding.username.setText("   "+session.getData(session.NAME));
        binding.phone.setText("   "+session.getData(session.PHONE));

        binding.getRoot().setFocusableInTouchMode(true);
        binding.getRoot().requestFocus();
        binding.getRoot().setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                FragmentMain NameofFragment = new FragmentMain();
                FragmentTransaction transaction=getFragmentManager().beginTransaction();
                transaction.replace(R.id.container,NameofFragment);
                transaction.commit();
                return true;
            }
            return false;
        });
        binding.cvAbout.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), AboutusActivity.class));
        });

        binding.cvContact.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), AboutusActivity.class));
        });


        binding.cvFeedback.setOnClickListener(v -> {
            final String appName = getActivity().getPackageName();
            try {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
            } catch (ActivityNotFoundException anfe) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + appName)));
            }
        });

        binding.cvHistory.setOnClickListener(v -> {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, new Coins());
            transaction.addToBackStack(null);
            transaction.commit();
        });

        binding.cvLogout.setOnClickListener(v -> {
            Logout();
        });


        binding.cvReward.setOnClickListener(v -> {
            startActivity(new Intent(getActivity(), WithdrawActivity.class));
        });

        binding.cvPrivacy.setOnClickListener(v -> {
            launchCustomTabs(activity,App.getData().get(0).getPrivacyPolicy());
        });

        binding.cvDelete.setOnClickListener(v -> {
            dialog_logout.show();
            TextView title = dialog_logout.findViewById(R.id.congrts);
            TextView msg = dialog_logout.findViewById(R.id.txt);

            title.setText(getString(R.string.are_you_sure_you_want_to_delete));
            msg.setText(getString(R.string.delete_account_msg));
            int colorGreen = Color.parseColor("#2ABF88");
            int colorRed = Color.parseColor("#ff0000");
            title.setTextColor(colorRed);
            msg.setTextColor(colorRed);

            dialog_logout.findViewById(R.id.yes).setOnClickListener(v1-> {
                showDialog();
                deleteAccount();
            });

            dialog_logout.findViewById(R.id.no).setOnClickListener(v1 -> {
                dialog_logout.dismiss();
            });
        });

        return binding.getRoot();
    }

    private void deleteAccount() {
        ApiClient.getClient(activity).create(ApiInterface.class).ApiUser(Fun.data("","","","","","",16,0,session.Auth())).enqueue(new Callback<CallbackResp>() {
            @Override
            public void onResponse(Call<CallbackResp> call, Response<CallbackResp> response) {
                if(response.isSuccessful() && response.body().getCode()==201){
                    dismissDialog();
                    session.Logout();
                    session.setBoolean(session.LOGIN,false);
                    getActivity().finish();
                    startActivity(new Intent(getActivity(), FrontLogin.class));
                }else {
                    dismissDialog();
                    Toast.makeText(activity, "Something went wrong!!", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<CallbackResp> call, Throwable t) {
                dismissDialog();
            }
        });
    }

    private void Logout() {
        dialog_logout.show();
        TextView title = dialog_logout.findViewById(R.id.congrts);
        TextView msg = dialog_logout.findViewById(R.id.txt);

        title.setText(getString(R.string.logout));
        msg.setText(getString(R.string.are_you_sure_you_want_to_logout));
        title.setTextColor(getResources().getColor(R.color.colorAccent));
        msg.setTextColor(getResources().getColor(R.color.colorAccent));

        dialog_logout.findViewById(R.id.yes).setOnClickListener(v -> {
            dialog_logout.dismiss();
            session.Logout();
            session.setBoolean(session.LOGIN,false);
            startActivity(new Intent(getActivity(), FrontLogin.class));
            getActivity().finish();
        });

        dialog_logout.findViewById(R.id.no).setOnClickListener(v -> {
            dialog_logout.dismiss();
        });
    }


    @SuppressLint("SetTextI18n")
    @Override
    public void onResume() {
        binding.coin.setText(""+session.getIntData(session.WALLET));
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public static void launchCustomTabs(Activity activity, String url) {
        CustomTabsIntent.Builder customIntent = new CustomTabsIntent.Builder();
        customIntent.setToolbarColor(ContextCompat.getColor(activity, R.color.colorPrimary));
        customIntent.setExitAnimations(activity, R.anim.exit, R.anim.enter);
        customIntent.setStartAnimations(activity, R.anim.enter, R.anim.exit);
        customIntent.setUrlBarHidingEnabled(true);
        customIntent.build().launchUrl(activity, Uri.parse(url));

    }


    private void showDialog() {
        loading.show();
    }

    private void dismissDialog() {
        if (loading.isShowing()) {
            loading.dismiss();
        }
    }

}
