package com.cpm.lorealbaautomation.fragements;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
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 androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bikomobile.donutprogress.DonutProgress;
import com.ekn.gruzer.gaugelibrary.HalfGauge;
import com.ekn.gruzer.gaugelibrary.Range;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.DealarBoardActivity;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.AppDashboardTVA;
import com.cpm.lorealbaautomation.reports.TargetAchievementActivity;

import java.util.ArrayList;

/**
 * A fragment representing a list of Items.
 * <p/>
 * <p>
 * interface.
 */
public class DashboardsFragment extends Fragment {
    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    ArrayList<AppDashboardTVA> dashReportList = new ArrayList<>();
    String CounterId, username, visit_date;
    Lorealba_Database db;
    Context context;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public DashboardsFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static DashboardsFragment newInstance(int columnCount) {
        DashboardsFragment fragment = new DashboardsFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = (getContext());
        db = new Lorealba_Database(context);
        db.open();
        SharedPreferences preferences = PrefHelper.getPrefs(context);
        CounterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        db.open();
        dashReportList = db.getDashboardInfo(CounterId, username);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_item_list, container, false);
        // Set the adapter
        ((DealarBoardActivity) requireActivity()).setDashboardRefreshListener(value -> {
            context = (getContext());
            db = new Lorealba_Database(context);
            db.open();
            dashReportList = db.getDashboardInfo(CounterId, username);
            if (view instanceof RecyclerView) {
                Context context = view.getContext();
                RecyclerView recyclerView = (RecyclerView) view;
                ///add data for temp
                if (dashReportList.isEmpty()) {
                    AppDashboardTVA sb = new AppDashboardTVA();
                    sb.setkPI("No Data");
                    sb.setTotalSale(0);
                    sb.setTarget(0.0);
                    sb.setPer(0.0);
                    sb.setGraph("");
                    dashReportList.add(sb);
                }
                recyclerView.setAdapter(new DashboardAdapter(context, dashReportList));
                recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
            }
        });

        return view;
    }

    private class DashboardAdapter extends RecyclerView.Adapter<DashboardAdapter.Viewholder> {
        ArrayList<AppDashboardTVA> dashboardList;
        Context context;

        DashboardAdapter(Context context, ArrayList<AppDashboardTVA> dashboardList) {
            this.dashboardList = dashboardList;
            this.context = context;
        }

        @NonNull
        @Override
        public Viewholder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
            View view = LayoutInflater.from(context).inflate(R.layout.dashboard_item_adapter, viewGroup, false);
            return new Viewholder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull Viewholder viewholder, int position) {
            final AppDashboardTVA current = dashboardList.get(position);
            if (current.getkPI().equalsIgnoreCase("No Data")) {
                LinearLayout.LayoutParams layout_description = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT);
                viewholder.parent_layout.setLayoutParams(layout_description);
                viewholder.no_data_card.setVisibility(View.VISIBLE);
                viewholder.no_data_card.setId(position);
                viewholder.no_dash_img.setImageResource(R.mipmap.no_dashboard);
                viewholder.no_dash_img.setId(position);
                viewholder.rlDashInfo.setVisibility(View.GONE);
                viewholder.rlDashInfo.setId(position);
            } else {
                switch (current.getkPI()) {
                    case "TVA":
                        if (current.getGraph().equals("HalfGauge")) {
                            viewholder.cardDonutProgress.setVisibility(View.GONE);
                            viewholder.cardLeaderBoard.setVisibility(View.GONE);
                            viewholder.dash_card.setVisibility(View.VISIBLE);
                            viewholder.rlDashInfo.setVisibility(View.VISIBLE);
                            viewholder.no_data_card.setVisibility(View.GONE);
                            viewholder.no_dash_img.setVisibility(View.GONE);

                            viewholder.cardDonutProgress.setId(position);
                            viewholder.cardLeaderBoard.setId(position);
                            viewholder.no_data_card.setId(position);
                            viewholder.rlDashInfo.setId(position);
                            viewholder.no_dash_img.setId(position);
                            viewholder.dash_card.setId(position);

                            Range range = new Range();
                            range.setColor(Color.parseColor("#e21c22"));
                            range.setFrom(0);
                            range.setTo(30);

                            Range range2 = new Range();
                            range2.setColor(Color.parseColor("#ffdd76"));
                            range2.setFrom(31);
                            range2.setTo(70);

                            Range range3 = new Range();
                            range3.setColor(Color.parseColor("#2bbf7d"));
                            range3.setFrom(71);
                            range3.setTo(100);
                            //add color ranges to gauge
                            viewholder.pieChartView.addRange(range);
                            viewholder.pieChartView.addRange(range2);
                            viewholder.pieChartView.addRange(range3);
                            //set min max and current value
                            viewholder.pieChartView.setMinValue(0);
                            viewholder.pieChartView.setMaxValue(100);
                            viewholder.pieChartView.setValue(current.getPer());
                            viewholder.pieChartView.setEnableNeedleShadow(true);
                            viewholder.tvAchievmentHalf.setText(getString(R.string.Rs) + " " + current.getTarget().intValue());
                            viewholder.tvAchievmentHalf.setId(position);
                            viewholder.tvTargetsHalf.setText(getString(R.string.Rs) + " " + (current.getTotalSale()));
                            viewholder.tvTargetsHalf.setId(position);
                            viewholder.dash_card.setBackgroundResource(R.drawable.round_corner_parent);
                            viewholder.dash_card.setId(position);
                        } else {
                            viewholder.cardDonutProgress.setBackgroundResource(R.drawable.round_corner_parent);
                            viewholder.cardDonutProgress.setVisibility(View.VISIBLE);
                            viewholder.cardLeaderBoard.setVisibility(View.GONE);
                            viewholder.dash_card.setVisibility(View.GONE);
                            viewholder.rlDashInfo.setVisibility(View.VISIBLE);
                            viewholder.no_data_card.setVisibility(View.GONE);
                            viewholder.no_dash_img.setVisibility(View.GONE);

                            viewholder.cardDonutProgress.setId(position);
                            viewholder.cardLeaderBoard.setId(position);
                            viewholder.no_data_card.setId(position);
                            viewholder.rlDashInfo.setId(position);
                            viewholder.no_dash_img.setId(position);
                            viewholder.dash_card.setId(position);

                            viewholder.tvTargets.setText(getString(R.string.Rs) + " " + (current.getTotalSale()));
                            viewholder.tvTargets.setId(position);
                            viewholder.tvAchievment.setText("of " + getString(R.string.Rs) + " " + current.getTarget().intValue());
                            viewholder.donutProgress.setProgress(current.getPer() != null ? current.getPer().intValue() : 0);
                            // or if you want animation progress
                            viewholder.donutProgress.setProgressWithAnimation(current.getPer() != null ? current.getPer().intValue() : 0, 20);
                            viewholder.donutProgress.setTextColor(getResources().getColor(R.color.black));
                            viewholder.donutProgress.setFinishedStrokeColor(getResources().getColor(R.color.achievement));
                            viewholder.donutProgress.setUnfinishedStrokeColor(getResources().getColor(R.color.target_color));
                            viewholder.donutProgress.setUnfinishedStrokeWidth(30f);
                            viewholder.donutProgress.setFinishedStrokeWidth(30f);
                            viewholder.donutProgress.setSuffix("%");
                        }
                        break;
                    case "LeaderBoard":
                        ///for Leader Board
                        viewholder.tvLeaderbKPI.setText("Leader Board");
                        viewholder.tvLeaderbKPI.setId(position);
                        viewholder.tvLeaderbAchPer.setText(current.getPer().toString() + "%");
                        viewholder.tvLeaderbAchPer.setId(position);
                        viewholder.tvLeaderbaName.setText(current.getGraph());
                        viewholder.tvLeaderbaName.setId(position);
                        viewholder.tvCounterName.setText(CommonFunctions.capitalizeFirstLetter(current.getCounter_name()));
                        viewholder.tvCounterName.setId(position);
                        viewholder.tvCounterId.setText(current.getCounter_code());
                        viewholder.tvCounterId.setId(position);
                        viewholder.rlDashInfo.setVisibility(View.VISIBLE);
                        viewholder.dash_card.setVisibility(View.GONE);
                        viewholder.dash_card.setId(position);
                        viewholder.rlDashInfo.setId(position);
                        viewholder.cardLeaderBoard.setVisibility(View.VISIBLE);
                        viewholder.cardDonutProgress.setVisibility(View.GONE);
                        viewholder.cardLeaderBoard.setBackgroundResource(R.drawable.round_corner_parent);
                        viewholder.cardDonutProgress.setId(position);
                        viewholder.cardLeaderBoard.setId(position);
                        break;
                    case "Incentive":
                        viewholder.cardDonutIncentive.setBackgroundResource(R.drawable.round_corner_parent);
                        viewholder.cardDonutIncentive.setVisibility(View.VISIBLE);
                        viewholder.cardDonutProgress.setVisibility(View.GONE);
                        viewholder.cardLeaderBoard.setVisibility(View.GONE);
                        viewholder.rlDashInfo.setVisibility(View.VISIBLE);
                        viewholder.no_data_card.setVisibility(View.GONE);
                        viewholder.no_dash_img.setVisibility(View.GONE);
                        viewholder.dash_card.setVisibility(View.GONE);

                        viewholder.cardDonutIncentive.setId(position);
                        viewholder.cardDonutProgress.setId(position);
                        viewholder.cardLeaderBoard.setId(position);
                        viewholder.no_data_card.setId(position);
                        viewholder.no_dash_img.setId(position);
                        viewholder.rlDashInfo.setId(position);
                        viewholder.dash_card.setId(position);

                        viewholder.tvMaximumIncentive.setText(getString(R.string.Rs) + " " + (current.getTarget().intValue()));
                        viewholder.tvMaximumIncentive.setId(position);
                        viewholder.tvAchIncentive.setText(getString(R.string.Rs) + " " + current.getTotalSale());
                        viewholder.tvAchIncentive.setId(position);
                        viewholder.donut_progress_incentive.setProgress(current.getPer() != null ? current.getPer().intValue() : 0);
                        // or if you want animation progress
                        viewholder.donut_progress_incentive.setProgressWithAnimation(current.getPer() != null ? current.getPer().intValue() : 0, 20);
                        viewholder.donut_progress_incentive.setTextColor(getResources().getColor(R.color.black));
                        viewholder.donut_progress_incentive.setFinishedStrokeColor(getResources().getColor(R.color.incentive_max));
                        viewholder.donut_progress_incentive.setUnfinishedStrokeColor(getResources().getColor(R.color.incentive_min));
                        viewholder.donut_progress_incentive.setUnfinishedStrokeWidth(30f);
                        viewholder.donut_progress_incentive.setFinishedStrokeWidth(30f);
                        viewholder.donut_progress_incentive.setSuffix("%");
                        break;
                }

                viewholder.rlDashInfo.setOnClickListener(view -> context.startActivity(new Intent(context, TargetAchievementActivity.class).putExtra("kpi", current.getkPI())));
            }
        }

        @Override
        public int getItemCount() {
            return dashboardList.size();
        }

        class Viewholder extends RecyclerView.ViewHolder {
            TextView tvTargetsHalf, tvAchievmentHalf,
                    tvLeaderbAchPer, tvLeaderbaName, tvCounterName, tvCounterId, tvLeaderbKPI, tvTargets,
                    tvAchievment, tvAchIncentive, tvMaximumIncentive;
            HalfGauge pieChartView;
            DonutProgress donutProgress, donut_progress_incentive;
            CardView dash_card, no_data_card, cardLeaderBoard, cardDonutProgress, cardDonutIncentive;
            LinearLayout parent_layout, rlDashInfo, rlViewReport;
            ImageView no_dash_img;

            public Viewholder(@NonNull View it) {
                super(it);
                pieChartView = it.findViewById(R.id.chart);
                dash_card = it.findViewById(R.id.dash_card);
                tvAchievmentHalf = it.findViewById(R.id.tvAchievmentHalf);
                tvTargetsHalf = it.findViewById(R.id.tvTargetsHalf);
                parent_layout = it.findViewById(R.id.parent_layout);
                no_data_card = it.findViewById(R.id.no_data_card);
                no_dash_img = it.findViewById(R.id.no_dash_img);
                rlDashInfo = it.findViewById(R.id.rlDashInfo);
                ////for leaderBoard
                cardLeaderBoard = it.findViewById(R.id.cardLeaderBoard);
                tvLeaderbAchPer = it.findViewById(R.id.tvLeaderbAchPer);
                tvLeaderbaName = it.findViewById(R.id.tvLeaderbaName);
                tvCounterName = it.findViewById(R.id.tvCounterName);
                tvLeaderbKPI = it.findViewById(R.id.tvLeaderbKPI);
                tvCounterId = it.findViewById(R.id.tvCounterId);
                /////for Dognut graph
                cardDonutProgress = it.findViewById(R.id.cardDonutProgress);
                donutProgress = it.findViewById(R.id.donut_progress);
                rlViewReport = it.findViewById(R.id.rlViewReport);
                tvAchievment = it.findViewById(R.id.tvAchievment);
                tvTargets = it.findViewById(R.id.tvTargets);
                ///for Incentive
                cardDonutIncentive = it.findViewById(R.id.cardDonutIncentive);
                donut_progress_incentive = it.findViewById(R.id.donut_progress_incentive);
                tvMaximumIncentive = it.findViewById(R.id.tvMaximumIncentive);
                tvAchIncentive = it.findViewById(R.id.tvAchIncentive);
            }
        }
    }
}
