package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.adapter.TargetSalesAdapter;
import com.cygnusa.hyperm.droppy.DroppyClickCallbackInterface;
import com.cygnusa.hyperm.droppy.DroppyMenuItem;
import com.cygnusa.hyperm.droppy.DroppyMenuPopup;
import com.cygnusa.hyperm.droppy.EasyDialog;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.Survey;
import com.cygnusa.hyperm.wrappers.TargetSales;
import com.cygnusa.hyperm.wrappers.TargetSalesResponse;
import com.tylersuehr.esr.EmptyStateRecyclerView;
import com.tylersuehr.esr.TextStateDisplay;

import java.io.File;
import java.util.ArrayList;
import java.util.Objects;

import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;
import retrofit2.Call;
import retrofit2.Response;


public class TargetSalesActivity extends AppCompatActivity {
    EmptyStateRecyclerView targetList;
    TransparentProgressDialog progressDialog;
    ApiService restService;
    ArrayList<TargetSales> My_Target_Sales = new ArrayList<>();
    ArrayList<Survey> SURVEY_LIST = new ArrayList<>();
    TargetSalesAdapter adapter;
    LinearLayoutManager linearLayoutManager;
    public static String YEAR;
    public static String MONTH;
    public static String Date;
    TextView mSalesDate;
    ImageView rightMenu;
    FrameLayout notificationButton;
    EasyDialog easyDialog;
    DroppyMenuPopup droppyMenu;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_target_sales);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));
        restService = ((MainApplication) getApplication()).getClient();
        mSalesDate=findViewById(R.id.salesDate);
        if(!Date.isEmpty()){
            mSalesDate.setText("Data as on : "+Date);
        }
        targetList = findViewById(R.id.learningPath);
        targetList.setHasFixedSize(true);
        targetList.setItemAnimator(new SlideInLeftAnimator());
        linearLayoutManager = new LinearLayoutManager(this);
        targetList.setLayoutManager(linearLayoutManager);
        targetList.setStateDisplay(EmptyStateRecyclerView.STATE_EMPTY,
                new TextStateDisplay(this, "No data available", ""));
        rightMenu = findViewById(R.id.rightMenu);
        notificationButton = findViewById(R.id.notificationButton);
        initDroppyMenu();
        rightMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    easyDialog = new EasyDialog(TargetSalesActivity.this, droppyMenu)
                            .setLayout(droppyMenu.show())
                            .setGravity(EasyDialog.GRAVITY_BOTTOM)
                            .setBackgroundColor(Color.TRANSPARENT, Color.WHITE)
                            .setLocationByAttachedView(rightMenu)
                            .setAnimationTranslationShow(EasyDialog.DIRECTION_X, 350,
                                    GlobalData.width, 0)
                            .setAnimationTranslationDismiss(EasyDialog.DIRECTION_X, 350, 0,
                                    GlobalData.width).setTouchOutsideDismiss(true)
                            .setMatchParent(false).setMarginLeftAndRight(0, 15)
                            .setOutsideColor(Color.parseColor("#80000000")).show();

            }
        });

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

                    goNotificationActivity();

            }
        });

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
        targetList.post(new Runnable() {
            @Override
            public void run() {
                getTargetedList();
            }
        });

    }
    private void goNotificationActivity() {
        startActivity(new Intent(getBaseContext(), NotificationActivity.class));

    }

    private void initDroppyMenu() {
        DroppyMenuPopup.Builder droppyBuilder = new DroppyMenuPopup.Builder(
                TargetSalesActivity.this, rightMenu);
        droppyBuilder.addMenuItem(new DroppyMenuItem("Change Password", R.mipmap.icon_change_password))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("Settings", R.mipmap.icon_settings))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("FAQs", R.mipmap.icon_faq))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("About", R.mipmap.icon_about))
                .addSeparator()
                .addMenuItem(new DroppyMenuItem("Logout", R.mipmap.icon_logout))
                .addSeparator()
                .triggerOnAnchorClick(false);
        droppyBuilder.setOnClick(new DroppyClickCallbackInterface() {
            @Override
            public void call(View v, int id) {
                easyDialog.dismiss();
                switch (id) {
                    case 0:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(new Intent(TargetSalesActivity.this, ChangePasswordActivity.class));
                            }
                        }, 300);
                        break;
                    case 1:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Intent i = new Intent(TargetSalesActivity.this, SettingsActivity.class);
                                i.putExtra("usertype", "dse");
                                startActivity(i);
                            }
                        }, 300);
                        break;
                    case 2:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(new Intent(TargetSalesActivity.this, FaqActivity.class));
                            }
                        }, 300);
                        break;
                    case 3:
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(new Intent(TargetSalesActivity.this, AboutActivity.class));
                            }
                        }, 300);
                        break;
                    case 4:

                        new AlertDialog.Builder(TargetSalesActivity.this)
                                .setMessage("Are you sure you want to logout?")
                                .setPositiveButton("Yes",
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int which) {
//                                                preferences = getSharedPreferences("UserDetails",
//                                                        Context.MODE_PRIVATE);
//                                                editor = preferences.edit();
//                                                editor.putString("inputUsername", null);
//                                                editor.putString("inputPassword", null);
//                                                editor.apply();
                                                getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                                        .edit().putString("FCM_TOKEN_ID", "").apply();
                                                GlobalData.sdb.delete("session", null, null);
                                                GlobalData.sdb.delete("topic", null, null);
                                                deleteLocalFiles();
                                                startActivity(new Intent(getBaseContext(), LoginActivity.class));
                                                finish();
                                            }
                                        }).setNegativeButton("No", null).show();
                        break;

                }


            }
        });
        droppyMenu = droppyBuilder.build();
    }
    public void deleteLocalFiles(){
        String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                + "/" + ".HYPERM/VIDEO";
        File dir = new File(fileName);

        if (dir.isDirectory())
        {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++)
            {
                new File(dir, children[i]).delete();
            }
        }
        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM", "PDF");
        if (f1.isDirectory())
        {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++)
            {
                new File(dir, children[i]).delete();
            }
        }
    }

    private void getTargetedList() {
        if (new UtilService().isNetworkAvailable(this)) {
            progressDialog = new TransparentProgressDialog(this);
            progressDialog.show();

            try {
                restService.getTargetedSales(YEAR, MONTH).enqueue(new MyCallback<TargetSalesResponse>() {
                    @Override
                    public void onResponse(Call<TargetSalesResponse> call, Response<TargetSalesResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            My_Target_Sales = response.body().getData();
                            if (SURVEY_LIST == null) {
                                SURVEY_LIST = new ArrayList<>();
                            }
                            if (My_Target_Sales.size() == 0) {
                                targetList.invokeState(EmptyStateRecyclerView.STATE_EMPTY);
                            } else {
                                targetList.invokeState(EmptyStateRecyclerView.STATE_OK);
                            }
                            adapter = new TargetSalesAdapter(TargetSalesActivity.this, My_Target_Sales);
                            targetList.setAdapter(adapter);
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(HomeActivity.callback).sendEmptyMessage(0);
                            finish();
                        } else if (response.body() != null) {
                            GlobalData.showToast(TargetSalesActivity.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(TargetSalesActivity.this, message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                finish();
                            }
                        }


                    }

                    @Override
                    public void onFailure(Call<TargetSalesResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(TargetSalesActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                GlobalData.showToast(TargetSalesActivity.this, "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
            }
        } else {
            GlobalData.showToast(TargetSalesActivity.this, "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }


    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(TargetSalesActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        if (GlobalData.canLogout) {
            finish();
        }
    }

    private void showHelpScreen() {
        try {
            View view;
            if (adapter != null && adapter.getItemCount() > 0) {
                view = targetList.findViewHolderForAdapterPosition(linearLayoutManager.findFirstVisibleItemPosition()).itemView;
            } else {
                view = targetList;
            }
            new FancyShowCaseView.Builder(this)
                    .focusOn(view)
                    .title("Tap here to view the PDF or Video")
                    .titleSize(22, 1)
                    .closeOnTouch(true)
                    .fitSystemWindows(false)
                    .focusShape(FocusShape.ROUNDED_RECTANGLE)
                    .backgroundColor(Color.parseColor("#99000000"))
                    .build()
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            confirmClose();
        }
        return super.onOptionsItemSelected(item);
    }

    private void confirmClose() {
        finish();
        TargetSalesActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }


}
