package com.cpm.lorealbaMabeline.fragements;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

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

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 com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.DealarBoardActivity;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.reportGetterSetter.ReportAvgUnitsPerBill;
import com.cpm.lorealbaMabeline.reports.TargetAchievementActivity;

import java.util.ArrayList;
import java.util.List;

import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.view.PieChartView;

/**
 * A fragment representing a list of Items.
 * <p/>
 * <p>
 * interface.
 */
public class DashboardFragment extends Fragment {
    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    ArrayList<ReportAvgUnitsPerBill> 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 DashboardFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static DashboardFragment newInstance(int columnCount) {
        DashboardFragment fragment = new DashboardFragment();
        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.getDashboardReport(CounterId);
    }

    @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.getDashboardReport(CounterId);
            if (view instanceof RecyclerView) {
                Context context = view.getContext();
                RecyclerView recyclerView = (RecyclerView) view;
                ///add data for temp
                if (dashReportList.size() == 0) {
                    ReportAvgUnitsPerBill sb = new ReportAvgUnitsPerBill();
                    sb.setKPI("No Data");
                    sb.setMTDTg(0.0);
                    sb.setMTDAch(0.0);
                    sb.setAchPer(0.0);
                    sb.setPending(0.0);
                    sb.setRunRate(0);
                    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<ReportAvgUnitsPerBill> dashboardList;
        Context context;

        DashboardAdapter(Context context, ArrayList<ReportAvgUnitsPerBill> 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 ReportAvgUnitsPerBill 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.dash_card.setVisibility(View.GONE);
                viewholder.dash_card.setId(position);

            } else {
                viewholder.no_dash_img.setVisibility(View.GONE);
                viewholder.no_dash_img.setId(position);

                viewholder.no_data_card.setVisibility(View.GONE);
                viewholder.no_data_card.setId(position);

                viewholder.dash_card.setVisibility(View.VISIBLE);
                viewholder.dash_card.setId(position);

                List pieData = new ArrayList<>();
                pieData.add(new SliceValue(Float.parseFloat(current.getAchPer().toString()),
                        getResources().getColor(R.color.dashboard_ach)));
                if (current.getAchPer() > 100.0) {
                    pieData.add(new SliceValue(0, getResources().getColor(R.color.dashboard_less_ach)));
                } else {
                    pieData.add(new SliceValue(Float.parseFloat(current.getPending().toString()),
                            getResources().getColor(R.color.dashboard_less_ach)));

                }
                if (CommonFunctions.isTablet(context)) {
                    PieChartData pieChartData = new PieChartData(pieData);
                    pieChartData.setHasLabels(false).setValueLabelTextSize(14);
                    pieChartData.setHasCenterCircle(true).setCenterText1(current.getAchPer().toString() +
                            "%").setCenterText1FontSize(10).setCenterText1Color(getResources().getColor(R.color.black));
                    viewholder.pieChartView.setPieChartData(pieChartData);

                } else {
                    viewholder.pieChartView.setCircleFillRatio(0.7f);
                    PieChartData pieChartData = new PieChartData(pieData);
                    pieChartData.setHasLabels(false).setValueLabelTextSize(12);
                    pieChartData.setHasCenterCircle(true).setCenterText1(current.getAchPer().toString() +
                            "%").setCenterText1FontSize(8).setCenterText1Color(getResources().getColor(R.color.black));
                    viewholder.pieChartView.setPieChartData(pieChartData);
                }

                viewholder.target_text.setText("MTD TGT : " + current.getMTDTg().toString());
                viewholder.target_text.setId(position);
                viewholder.mtd_acheivement_text.setText("MTD ACH : " + current.getMTDAch().toString());
                viewholder.mtd_acheivement_text.setId(position);

                viewholder.txt_nameof_sale.setText(current.getKPI());
                viewholder.txt_nameof_sale.setId(position);

                if (current.getRunRate() != 0) {
                    viewholder.run_rate_value.setVisibility(View.VISIBLE);
                    viewholder.run_rate_value.setText("Run Rate : " + current.getRunRate());
                    viewholder.run_rate_value.setId(position);
                } else {
                    viewholder.run_rate_value.setVisibility(View.INVISIBLE);
                    viewholder.run_rate_value.setText("");
                    viewholder.run_rate_value.setId(position);
                }

                viewholder.dash_card.setOnClickListener(view -> {
                    if (current.getRunRate() != 0) {
                        context.startActivity(new Intent(context, TargetAchievementActivity.class));
                    }
                });

                viewholder.pieChartView.setOnClickListener(view -> {
                    if (current.getRunRate() != 0) {
                        context.startActivity(new Intent(context, TargetAchievementActivity.class));
                    }
                });

            }
        }

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

        class Viewholder extends RecyclerView.ViewHolder {
            TextView target_text, mtd_acheivement_text, txt_nameof_sale, run_rate_value;
            PieChartView pieChartView;
            CardView dash_card, no_data_card;
            LinearLayout parent_layout;
            ImageView no_dash_img;

            public Viewholder(@NonNull View itemView) {
                super(itemView);
                pieChartView = itemView.findViewById(R.id.chart);
                target_text = (TextView) itemView.findViewById(R.id.target_text);
                mtd_acheivement_text = (TextView) itemView.findViewById(R.id.mtd_acheivement_text);
                txt_nameof_sale = (TextView) itemView.findViewById(R.id.txt_nameof_sale);
                run_rate_value = (TextView) itemView.findViewById(R.id.run_rate_value);
                dash_card = (CardView) itemView.findViewById(R.id.dash_card);
                no_data_card = (CardView) itemView.findViewById(R.id.no_data_card);
                parent_layout = (LinearLayout) itemView.findViewById(R.id.parent_layout);
                no_dash_img = (ImageView) itemView.findViewById(R.id.no_dash_img);
            }
        }
    }
}
