package com.cygnusa.hyperm.fragments;

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.ImageButton;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.fancyshowcase.DismissListener;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.DepthPageTransformerNew;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.wrappers.FragmentItem;

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


public class LeaderboardSalesSectionFragment extends Fragment implements DismissListener {

    View mainView;

    ViewPager leaderBoardPager;
    SmartTabLayout leaderBoardPagerTab;
    TransparentProgressDialog progressDialog;
    ApiService restService;
    ArrayList<String> MY_LEADER_BOARD = new ArrayList<>();
    ArrayList<FragmentItem> fragments = new ArrayList<>();
    private int SHOWCASE_POSITION = 0;
    private ImageButton previous,next;
    ArrayList<String> MONTH_YEAR;
    int monthIndex=0;
    TextView monthText;
    public static Handler.Callback callback;

    public LeaderboardSalesSectionFragment() {

    }

    public void onResumeFragment() {
        try {
            if (leaderBoardPager != null) {
                LeaderboardSalesSectionFragment fragment = (LeaderboardSalesSectionFragment) fragments.get(leaderBoardPager.getCurrentItem())
                        .getFragment();
                fragment.onResumeFragment();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_my_sub_leaderboard, container, false);
    }
    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;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mainView = view;
        restService = ((MainApplication) getActivity().getApplication()).getClient();
        leaderBoardPager = mainView.findViewById(R.id.myTrainingPager);
        leaderBoardPagerTab = mainView.findViewById(R.id.myTrainingPagerTab);
        previous = mainView.findViewById(R.id.previous);
        next = mainView.findViewById(R.id.next);
        monthText = mainView.findViewById(R.id.MonthText);
        next.setEnabled(false);

        MONTH_YEAR = generateMonthAndYear(10);
        monthIndex=MONTH_YEAR.size()-1;
        monthText.setText(MONTH_YEAR.get(MONTH_YEAR.size()-1));
        Calendar calendar = Calendar.getInstance();
        LeaderBoardSalesFragment.yearValue=calendar.get(Calendar.YEAR);
        LeaderBoardSalesFragment.monthValue=calendar.get(Calendar.MONTH) + 1;
        previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                monthIndex= monthIndex-1;
                next.setEnabled(true);
                monthText.setText(MONTH_YEAR.get(monthIndex));
                splitMonth(MONTH_YEAR.get(monthIndex));
                if(monthIndex==0){
                    previous.setEnabled(false);
                }

            }
        });
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                monthIndex=monthIndex+1;
                previous.setEnabled(true);
                monthText.setText(MONTH_YEAR.get(monthIndex));
                splitMonth(MONTH_YEAR.get(monthIndex));
                if (monthIndex == MONTH_YEAR.size() - 1) {
                    next.setEnabled(false);
                }
            }
        });
        MY_LEADER_BOARD.clear();
        MY_LEADER_BOARD.add("Area");
        MY_LEADER_BOARD.add("Region");
        MY_LEADER_BOARD.add("Zone");
        MY_LEADER_BOARD.add("National");
        setLeaderBoardCategory();
        callback = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                // getLeaderBoard();
                return false;
            }
        };
    }

    private void splitMonth(String myear) {
        String[] str = myear.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);
            LeaderBoardSalesFragment.monthValue = calendar.get(Calendar.MONTH) + 1;
            LeaderBoardSalesFragment.yearValue = calendar.get(Calendar.YEAR);
            new Handler(LeaderBoardSalesFragment.callback).sendEmptyMessage(0);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void setLeaderBoardCategory() {
        leaderBoardPager.setPageTransformer(true, new DepthPageTransformerNew());
        leaderBoardPager.setAdapter(new LeaderBoardAdapter(getChildFragmentManager(),
                new ArrayList<String>()));
        leaderBoardPager.setAdapter(new LeaderBoardAdapter(getChildFragmentManager(),
                MY_LEADER_BOARD));
        leaderBoardPagerTab.setViewPager(leaderBoardPager);

    }



    public class LeaderBoardAdapter extends FragmentStatePagerAdapter {

        ArrayList<String> categories;


        private LeaderBoardAdapter(FragmentManager fm, ArrayList<String> list) {
            super(fm);
            categories = list;
            fragments = new ArrayList<>();
        }

        @Override
        public Fragment getItem(int position) {

            LeaderBoardSalesFragment fragment = new LeaderBoardSalesFragment();
            fragment.setIsSales(position);
            FragmentItem item = new FragmentItem();
            item.setFragment(fragment);
            item.setTitle(categories.get(position));
            fragments.add(item);
            return fragment;




        }

        @Override
        public int getCount() {
            return categories.size();
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return categories.get(position);
        }
    }

    public void showHelpScreen() {
        try {
            SHOWCASE_POSITION = 0;
            new FancyShowCaseView.Builder(getActivity())
                    .title("Tap here to select the category")
                    .titleSize(22, 1)
                    .closeOnTouch(true)
                    .focusShape(FocusShape.ROUNDED_RECTANGLE)
                    .dismissListener(this)
                    .backgroundColor(Color.parseColor("#99000000"))
                    .build()
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDismiss(String id) {
        try {
            if (SHOWCASE_POSITION == 0) {
                new FancyShowCaseView.Builder(getActivity())
                        .focusOn(leaderBoardPagerTab)
                        .title("Tap or swipe to navigate to next page")
                        .titleSize(22, 1)
                        .closeOnTouch(true)
                        .focusShape(FocusShape.ROUNDED_RECTANGLE)
                        .dismissListener(this)
                        .backgroundColor(Color.parseColor("#99000000"))
                        .build()
                        .show();
            }
            SHOWCASE_POSITION++;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSkipped(String id) {

    }
}