package com.cygnusa.hyperm.fragments;

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.util.ApiService;
import com.cygnusa.hyperm.util.DepthPageTransformerNew;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;

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

public class TeamRankingAssessmentFragment extends Fragment {

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

    public TeamRankingAssessmentFragment() {

    }

    @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() {
        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 - 10; 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) Objects.requireNonNull(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();
        monthIndex = MONTH_YEAR.size() - 1;
        monthText.setText(MONTH_YEAR.get(MONTH_YEAR.size() - 1));
        Calendar calendar = Calendar.getInstance();
        yearValue = calendar.get(Calendar.YEAR);
        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();

        if (GlobalData.user.getData().getRole().trim().equalsIgnoreCase("3")) {
            MY_LEADER_BOARD.add("TRAINER");
            MY_LEADER_BOARD.add("ZM");
            MY_LEADER_BOARD.add("RM");
            MY_LEADER_BOARD.add("AM");
            MY_LEADER_BOARD.add("DSE");
        } else if (GlobalData.user.getData().getRole().trim().equalsIgnoreCase("4") ||
                GlobalData.user.getData().getRole().trim().equalsIgnoreCase("5")) {
            MY_LEADER_BOARD.add("RM");
            MY_LEADER_BOARD.add("AM");
            MY_LEADER_BOARD.add("DSE");
        } else if (GlobalData.user.getData().getRole().trim().equalsIgnoreCase("6")) {
            MY_LEADER_BOARD.add("AM");
            MY_LEADER_BOARD.add("DSE");
        } else if (GlobalData.user.getData().getRole().trim().equalsIgnoreCase("14") ||
                GlobalData.user.getData().getRole().trim().equalsIgnoreCase("7")) {
            MY_LEADER_BOARD.add("DSE");
        }

        setLeaderBoardCategory();

        leaderBoardPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                onResumeFragment();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

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

    private void onResumeFragment() {
        if (MY_LEADER_BOARD.size() == 5) {
            if (leaderBoardPager.getCurrentItem() == 0) {
                new Handler(TRTrainerFragmentAssessment.callback).sendEmptyMessage(0);
            } else if (leaderBoardPager.getCurrentItem() == 1) {
                new Handler(TRZonalFragmentAssessment.callback).sendEmptyMessage(0);
            } else if (leaderBoardPager.getCurrentItem() == 2) {
                new Handler(TRRegionalFragmentAssessment.callback).sendEmptyMessage(0);
            } else if (leaderBoardPager.getCurrentItem() == 3) {
                new Handler(TRAreaFragmentAssessment.callback).sendEmptyMessage(0);
            } else {
                new Handler(TRDSEFragmentAssessment.callback).sendEmptyMessage(0);
            }
        } else if (MY_LEADER_BOARD.size() == 4) {
            if (leaderBoardPager.getCurrentItem() == 0) {
                new Handler(TRZonalFragmentAssessment.callback).sendEmptyMessage(0);
            } else if (leaderBoardPager.getCurrentItem() == 1) {
                new Handler(TRRegionalFragmentAssessment.callback).sendEmptyMessage(0);
            } else if (leaderBoardPager.getCurrentItem() == 2) {
                new Handler(TRAreaFragmentAssessment.callback).sendEmptyMessage(0);
            } else {
                new Handler(TRDSEFragmentAssessment.callback).sendEmptyMessage(0);
            }
        } else if (MY_LEADER_BOARD.size() == 3) {
            if (leaderBoardPager.getCurrentItem() == 0) {
                new Handler(TRRegionalFragmentAssessment.callback).sendEmptyMessage(0);
            } else if (leaderBoardPager.getCurrentItem() == 1) {
                new Handler(TRAreaFragmentAssessment.callback).sendEmptyMessage(0);
            } else {
                new Handler(TRDSEFragmentAssessment.callback).sendEmptyMessage(0);
            }
        } else if (MY_LEADER_BOARD.size() == 2) {
            if (leaderBoardPager.getCurrentItem() == 0) {
                new Handler(TRAreaFragmentAssessment.callback).sendEmptyMessage(0);
            } else {
                new Handler(TRDSEFragmentAssessment.callback).sendEmptyMessage(0);
            }
        } else {
            new Handler(TRDSEFragmentAssessment.callback).sendEmptyMessage(0);
        }
    }

    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);
            monthValue = calendar.get(Calendar.MONTH) + 1;
            yearValue = calendar.get(Calendar.YEAR);
            onResumeFragment();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private void setLeaderBoardCategory() {
        if (GlobalData.user.getData().getRole().trim().equalsIgnoreCase("14") ||
                GlobalData.user.getData().getRole().trim().equalsIgnoreCase("7")) {
            leaderBoardPagerTab.setVisibility(View.GONE);
        }
        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;
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            if (categories.size() == 5) {
                if (position == 0) {
                    return new TRTrainerFragmentAssessment();
                } else if (position == 1) {
                    return new TRZonalFragmentAssessment();
                } else if (position == 2) {
                    return new TRRegionalFragmentAssessment();
                } else if (position == 3) {
                    return new TRAreaFragmentAssessment();
                } else {
                    return new TRDSEFragmentAssessment();
                }
            } else if (categories.size() == 4) {
                if (position == 0) {
                    return new TRZonalFragmentAssessment();
                } else if (position == 1) {
                    return new TRRegionalFragmentAssessment();
                } else if (position == 2) {
                    return new TRAreaFragmentAssessment();
                } else {
                    return new TRDSEFragmentAssessment();
                }
            } else if (categories.size() == 3) {
                if (position == 0) {
                    return new TRRegionalFragmentAssessment();
                } else if (position == 1) {
                    return new TRAreaFragmentAssessment();
                } else {
                    return new TRDSEFragmentAssessment();
                }
            } else if (categories.size() == 2) {
                if (position == 0) {
                    return new TRAreaFragmentAssessment();
                } else {
                    return new TRDSEFragmentAssessment();
                }
            } else {
                return new TRDSEFragmentAssessment();
            }
        }

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


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