package com.ttiglobal.inttilectgpchat.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 androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;

import com.budiyev.android.circularprogressbar.CircularProgressBar;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.ttiglobal.inttilectgpchat.HomeActivity;
import com.ttiglobal.inttilectgpchat.LearningPathActivity;
import com.ttiglobal.inttilectgpchat.MyEarnedPoints;
import com.ttiglobal.inttilectgpchat.R;
import com.ttiglobal.inttilectgpchat.TargetSalesActivity;
import com.ttiglobal.inttilectgpchat.autofit.AutofitTextView;
import com.ttiglobal.inttilectgpchat.slider.Animations.DescriptionAnimation;
import com.ttiglobal.inttilectgpchat.slider.Indicators.PagerIndicator;
import com.ttiglobal.inttilectgpchat.slider.SliderLayout;
import com.ttiglobal.inttilectgpchat.slider.SliderTypes.BaseSliderView;
import com.ttiglobal.inttilectgpchat.slider.SliderTypes.DefaultSliderView;
import com.ttiglobal.inttilectgpchat.slider.Tricks.ViewPagerEx;
import com.ttiglobal.inttilectgpchat.util.ApiService;
import com.ttiglobal.inttilectgpchat.util.ExtendedNumberPicker;
import com.ttiglobal.inttilectgpchat.util.GlobalData;
import com.ttiglobal.inttilectgpchat.util.MainApplication;
import com.ttiglobal.inttilectgpchat.util.TransparentProgressDialog;
import com.ttiglobal.inttilectgpchat.util.UtilService;
import com.ttiglobal.inttilectgpchat.wrappers.DashboardResponse;
import com.ttiglobal.inttilectgpchat.wrappers.ErrorResponse;

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 {

    public static Handler.Callback callback;
    View mainView;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    TextView mSalesText;
    AutofitTextView mPrgressText, mEarnedPoints;
    DashboardResponse data = new DashboardResponse();
    CircularProgressBar progressBar;
    ExtendedNumberPicker datePicker;
    ImageView imgBasic, imgBronze, imgSilver, imgGold;
    ArrayList<String> MONTH_YEAR;
    Handler PICKER_HANDLER = new Handler();
    private SliderLayout mDemoSlider;
    private LinearLayout menuLayout;
    private boolean mUserSeen = false;
    private boolean mViewCreated = false;
    FrameLayout learningPathLayout;
    LinearLayout targetSalesLayout, earnedPointsLayout;
    int yearValue, monthValue;


    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);
        learningPathLayout = mainView.findViewById(R.id.learningPathLayout);
        targetSalesLayout = mainView.findViewById(R.id.targetSalesLayout);
        earnedPointsLayout = mainView.findViewById(R.id.earnedPointsLayout);
        menuLayout = mainView.findViewById(R.id.menuLayout);
        mEarnedPoints = mainView.findViewById(R.id.earnedPoints);
        progressBar = mainView.findViewById(R.id.progress_bar);
        mPrgressText = mainView.findViewById(R.id.progressText);
        datePicker = mainView.findViewById(R.id.extendedDate);
        mSalesText = mainView.findViewById(R.id.salesText1);

        imgBasic = mainView.findViewById(R.id.imageBasic);
        imgBronze = mainView.findViewById(R.id.imageBronze);
        imgSilver = mainView.findViewById(R.id.imageSilver);
        imgGold = mainView.findViewById(R.id.imageGold);

        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();
        datePicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        datePicker.setWrapSelectorWheel(false);


        datePicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker numberPicker, int oldvalue, final int newValue) {
                try {
                    PICKER_HANDLER.removeCallbacksAndMessages(null);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                PICKER_HANDLER.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        String[] str = MONTH_YEAR.get(newValue).trim().split(" ");
                        String month = str[0];
                        String year = str[1];
                        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
                        try {
                            Date date = dateFormat.parse("01-" + month + "-" + year);
                            Calendar calendar = Calendar.getInstance();
                            calendar.setTime(date);
                            monthValue = calendar.get(Calendar.MONTH) + 1;
                            yearValue = calendar.get(Calendar.YEAR);
                            getDashBoardDetails(yearValue, monthValue);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }, 500);
            }
        });

        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);
    }

    @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" : "") + String.valueOf(j) + "-" + String.valueOf(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" : "") + String.valueOf(j) + "-" + String.valueOf(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() {
        mEarnedPoints.setText(data.getData().getEarning());
        if (Float.parseFloat(data.getData().getSales().getTarget()) > 0) {
            progressBar.setMaximum(Float.parseFloat(data.getData().getSales().getTarget()));
            progressBar.setProgress(Float.parseFloat(data.getData().getSales().getAchieved()));
        } else {
            progressBar.setMaximum(1);
            progressBar.setProgress(0);
        }

        mPrgressText.setText(String.format("%s/%s", data.getData().getSales().getAchieved(), data.getData().getSales().getTarget()));

        setImage(imgBasic, data.getData().getLearning().getBasic());
        setImage(imgBronze, data.getData().getLearning().getBronze());
        setImage(imgGold, data.getData().getLearning().getGold());
        setImage(imgSilver, data.getData().getLearning().getSilver());
    }

    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;
    }

    public void setImage(ImageView view, String learning) {
        if (learning.equalsIgnoreCase("3")) {
            view.setImageResource(R.drawable.asset_one);
        } else if (learning.equalsIgnoreCase("2")) {
            view.setImageResource(R.drawable.asset_three);
        } else if (learning.equalsIgnoreCase("1")) {
            view.setImageResource(R.drawable.asset_two);
        } else {
            view.setImageResource(R.drawable.asset_four);
        }

    }

    @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);
            datePicker.setMinValue(0);
            datePicker.setMaxValue(MONTH_YEAR.size() - 1);
            datePicker.setDisplayedValues(MONTH_YEAR.toArray(new String[0]));
            datePicker.setValue(MONTH_YEAR.size() - 1);
            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);
        }
    }

}
