package com.cygnusa.hyperm.fragments;


import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.cygnusa.hyperm.BlogActivity;
import com.cygnusa.hyperm.HomeActivity;
import com.cygnusa.hyperm.MyCertificationActivity;
import com.cygnusa.hyperm.MyEarnedPoints;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.SOSActivity;
import com.cygnusa.hyperm.adapter.DashboardMenuAdapter;
import com.cygnusa.hyperm.chatti.ChatMain;
import com.cygnusa.hyperm.slider.Animations.DescriptionAnimation;
import com.cygnusa.hyperm.slider.Indicators.PagerIndicator;
import com.cygnusa.hyperm.slider.SliderLayout;
import com.cygnusa.hyperm.slider.SliderTypes.BaseSliderView;
import com.cygnusa.hyperm.slider.SliderTypes.DefaultSliderView;
import com.cygnusa.hyperm.slider.Tricks.ViewPagerEx;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.DashboardResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.google.gson.Gson;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

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

public class HomeFragment extends Fragment implements BaseSliderView.OnSliderClickListener,
        ViewPagerEx.OnPageChangeListener, DashboardMenuAdapter.ItemClickListener {

    public static Handler.Callback callback;
    View mainView;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    TextView mSalesText;
    DashboardResponse data = new DashboardResponse();
    ArrayList<String> MONTH_YEAR;
    Handler PICKER_HANDLER = new Handler();
    private SliderLayout mDemoSlider;
    DashboardMenuAdapter adapter;
    private LinearLayout menuLayout;
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;
    int yearValue, monthValue;
    private ImageView myRewards;
    private LinearLayout llout_sos, askMe;


    public HomeFragment() {

    }

    public void onResumeFragment() {

    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        restService = ((MainApplication) getActivity().getApplication()).getClient();
        mDemoSlider = mainView.findViewById(R.id.slider);
        menuLayout = mainView.findViewById(R.id.menuLayout);
        mSalesText = mainView.findViewById(R.id.salesText1);
        llout_sos = mainView.findViewById(R.id.llout_sos);
        myRewards = mainView.findViewById(R.id.myRewards);
        askMe = mainView.findViewById(R.id.askMe);
        myRewards.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), MyEarnedPoints.class));
            }
        });

        askMe.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ChatMain.class));
            }
        });

        llout_sos.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), SOSActivity.class));
            }
        });


        ArrayList<Integer> viewColors = new ArrayList<>();
        viewColors.add(R.drawable.dash_my_learning);
        viewColors.add(R.drawable.dash_my_assessment);
        viewColors.add(R.drawable.dash_my_certi);
        viewColors.add(R.drawable.dash_my_dis);

        ArrayList<String> menuNames = new ArrayList<>();
        menuNames.add("My Learning");
        menuNames.add("My Assessment");
        menuNames.add("Certification");
        menuNames.add("Discussion");

        // set up the RecyclerView
        RecyclerView recyclerView = mainView.findViewById(R.id.rcvMenus);
        LinearLayoutManager horizontalLayoutManager
                = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
        recyclerView.setLayoutManager(horizontalLayoutManager);
        adapter = new DashboardMenuAdapter(getActivity(), viewColors, menuNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);

//        learningPathLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(getActivity(), LearningPathActivity.class));
//            }
//        });
//        targetSalesLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                TargetSalesActivity.YEAR = String.valueOf(yearValue);
//                TargetSalesActivity.MONTH = String.valueOf(monthValue);
//                TargetSalesActivity.Date = dateFormate(data.getData().getSales_last_update());
//                startActivity(new Intent(getActivity(), TargetSalesActivity.class));
//            }
//        });
//
//        earnedPointsLayout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                startActivity(new Intent(getActivity(), MyEarnedPoints.class));
//            }
//        });

        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                setBannerSlider();
                return false;
            }
        };


//        String header = "<b>ACHIEVEMENT</b> \n<font color='#ccffffff'>/20 ACHIEVEMENT</font>";
//        mainView.findViewById(R.id.myTraining).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(0);
//            }
//        });
//
//        mainView.findViewById(R.id.myAssessment).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(1);
//            }
//        });
//        mainView.findViewById(R.id.myLeaderBoard).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(4);
//            }
//        });
//
//        mainView.findViewById(R.id.myCompletedTraining).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(2);
//            }
//        });
//
//        mainView.findViewById(R.id.myFeedback).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(3);
//            }
//        });
        mViewCreated = true;
        onViewCreatedFirstSight();
        mDemoSlider.setPresetTransformer(SliderLayout.Transformer.Default);
        PagerIndicator indicators = mainView.findViewById(R.id.custom_indicator);
        mDemoSlider.setCustomIndicator(indicators);
        mDemoSlider.setCustomAnimation(new DescriptionAnimation());
        mDemoSlider.setDuration(4000);
        mDemoSlider.addOnPageChangeListener(this);
    }

    @Override
    public void onItemClick(View view, int position) {
        //  Toast.makeText(getActivity(), "You clicked " + adapter.getItem(position) + " on item position " + position, Toast.LENGTH_SHORT).show();
        if (position == 0) {
            new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(0);
        } else if (position == 1) {
            new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(1);
        } else if (position == 2) {
//            new Handler(HomeActivity.homeFragmentCallback).sendEmptyMessage(3);
            startActivity(new Intent(getActivity(), MyCertificationActivity.class));
        } else if (position == 3) {
            startActivity(new Intent(getActivity(), BlogActivity.class));
        }
    }

    @SuppressLint("CheckResult")
    private void setBannerSlider() {
        mDemoSlider.removeAllSliders();
        RequestOptions requestOptions = new RequestOptions();
        requestOptions
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .placeholder(R.drawable.placeholder);
        for (int i = 0; i < GlobalData.BANNERS.size(); i++) {
            DefaultSliderView sliderView = new DefaultSliderView(getActivity());
            sliderView
                    .image(GlobalData.BANNERS.get(i).getImage().trim())
                    .setRequestOption(requestOptions)
                    .setBackgroundColor(Color.TRANSPARENT)
                    .setProgressBarVisible(true)
                    .setOnSliderClickListener(this);
            sliderView.bundle(new Bundle());
            mDemoSlider.addSlider(sliderView);
        }
    }

    private ArrayList<String> generateMonthAndYear(int last) {
        ArrayList<String> yearList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int currentYear = calendar.get(Calendar.YEAR);
        int currentMonth = calendar.get(Calendar.MONTH) + 1;
        SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
        SimpleDateFormat format1 = new SimpleDateFormat("MMM yyyy");

        for (int i = currentYear; i > currentYear - last; i--) {
            if (i == currentYear) {
                for (int j = currentMonth; j > 0; j--) {
                    try {
                        Date date = format.parse("01-" + (j < 10 ? "0" : "") + j + "-" + i);
                        yearList.add(0, format1.format(date));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            } else {
                for (int j = 12; j > 0; j--) {
                    try {
                        Date date = format.parse("01-" + (j < 10 ? "0" : "") + j + "-" + i);
                        yearList.add(0, format1.format(date));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return yearList;
    }

    private void getDashBoardDetails(int year, int month) {
        if (new UtilService().isNetworkAvailable(getActivity())) {
            progressDialog = new TransparentProgressDialog(getActivity());
            progressDialog.show();
            try {
                restService.getDashboard(year, month).enqueue(new Callback<DashboardResponse>() {
                    @Override
                    public void onResponse(Call<DashboardResponse> call, Response<DashboardResponse> response) {
                        data = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (data != null && data.getStatus() == 200) {
                            SetDashboardData();
                        } else if (GlobalData.user != null) {
                            GlobalData.showToast(getActivity(), GlobalData.user.getMessage(), Toast.LENGTH_SHORT).show();

                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            new Handler(HomeActivity.callback).sendEmptyMessage(0);
                        } else if (response.body() != null) {
                            GlobalData.showToast(getActivity(), 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(getActivity(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(HomeActivity.callback).sendEmptyMessage(0);
                            }
                        }
                    }

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

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getActivity(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }

    }

    private void SetDashboardData() {
    }

    private void setBaseImage(ImageView view, String base) {

        if (base.equalsIgnoreCase("0")) {
            view.setImageResource(R.drawable.asset_four);
        } else if (base.equalsIgnoreCase("2")) {
            view.setImageResource(R.drawable.asset_three);
        } else if (base.equalsIgnoreCase("3")) {
            view.setImageResource(R.drawable.asset_two);
        } else {
            view.setImageResource(R.drawable.asset_four);
        }
    }


    private void setGoldImage(ImageView view, String gold) {
        if (gold.equalsIgnoreCase("0")) {
            view.setImageResource(R.drawable.asset_four);
        } else if (gold.equalsIgnoreCase("3")) {
            view.setImageResource(R.drawable.completed06);
        } else if (gold.equalsIgnoreCase("2")) {
            view.setImageResource(R.drawable.failed03);
        } else if (gold.equalsIgnoreCase("6")) {
            view.setImageResource(R.drawable.failed02);
        } else if (gold.equalsIgnoreCase("7")) {
            view.setImageResource(R.drawable.top_green_bottom_grey);
        } else if (gold.equalsIgnoreCase("4")) {
            view.setImageResource(R.drawable.top_green_bottom_grey);
        } else {
            view.setImageResource(R.drawable.asset_four);
        }

    }

    public String dateFormate(String dte) {
        String date = "";
        if (dte.equalsIgnoreCase("0000-00-00 00:00:00")) {
            date = "";
            return date;
        } else {

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date newDate = null;
            try {
                newDate = format.parse(dte);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            format = new SimpleDateFormat("dd-MMM-yyyy");
            date = format.format(newDate);

        }
        return date;
    }


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

    @Override
    public void onSliderClick(BaseSliderView baseSliderView) {

    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    public View getSlider() {
        return mDemoSlider;
    }

    public View getMenuLayout() {
        return menuLayout;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mViewCreated = false;
        mUserSeen = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!mUserSeen && isVisibleToUser) {
            mUserSeen = true;
            onViewCreatedFirstSight();
        }
    }


    @SuppressLint("StaticFieldLeak")
    private void onViewCreatedFirstSight() {
        if (mUserSeen && mViewCreated) {
            MONTH_YEAR = generateMonthAndYear(10);
            Calendar calendar = Calendar.getInstance();
            getDashBoardDetails(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1);
            monthValue = calendar.get(Calendar.MONTH) + 1;
            yearValue = calendar.get(Calendar.YEAR);
        }
    }


}
