package com.cpm.lorealbaautomation.reports;

import static com.cpm.lorealbaautomation.constant.CommonFunctions.capitalizeFirstLetter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
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.AppDashboardTVADrillDown;
import com.cpm.lorealbaautomation.reportGetterSetter.AppDashboardIncentive;
import com.cpm.lorealbaautomation.utils.BarChartCustomRenderer;
import com.cpm.lorealbaautomation.utils.RoundedBarChart;
import com.cpm.lorealbaautomation.utils.VerticalValueFormatter;

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

public class TargetAchievementActivity extends AppCompatActivity {
    private ArrayList<AppDashboardTVADrillDown> downs = new ArrayList<>();
    private LinearLayout rlIncentiveDetail, rlLeaderBInfo, rlTVADetails;
    private TextView tvEIncentive, tvMaxIncentive,
            tvSaleLinkedIncentive, tvFlatIncentive, tvTotalIncentive, tvNodata;
    String counter_Id, visit_date, username, kPI;
    private SharedPreferences preferences;
    RecyclerView recycle_reports;
    Lorealba_Database db;
    Context context;
    RoundedBarChart barChart;
    CombinedChart combinedChart;
    ArrayList barEntries, targetBarEntries;
    String[] productsgroupnames;
    long _totalsales = 0, totalTarget = 0;
    List<BarEntry> entries;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reports_sale_details);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        combinedChart = (CombinedChart) findViewById(R.id.combinedChart);
        barChart = findViewById(R.id.idBarChart);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        kPI = getIntent().getStringExtra("kpi");
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        iduserinterface();
        String couter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        TextView txt_counter_code = (TextView) findViewById(R.id.txt_counter_code);
        txt_counter_code.setText("Counter Code - " + couter_code + " / Id - " + counter_Id);
        calculateRequiredData();
    }


    private void calculateRequiredData() {
        if (kPI != null && kPI.equals("LeaderBoard")) {
            db.open();
            downs = db.getLeaderDashboards();
            if (!downs.isEmpty()) {
                rlLeaderBInfo.setVisibility(View.VISIBLE);
                rlIncentiveDetail.setVisibility(View.GONE);
                Adapter(findViewById(R.id.recycleLeaderb));
                rlTVADetails.setVisibility(View.GONE);
            } else tvNodata.setVisibility(View.GONE);
        } else if (kPI != null && kPI.equals("Incentive")) {
            incentiveDetail();
        } else
            TVAdeTail();
    }

    private void Adapter(RecyclerView recyclerView) {
        recyclerView.setAdapter(new DashTVADrillDownAdapter(context, downs));
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
    }

    private void barChart() {
        try {
            barChart.setVisibility(View.VISIBLE);
            combinedChart.setVisibility(View.GONE);
            barChart.setScaleEnabled(false);
            BarDataSet set = new BarDataSet(entries, "");
            set.setColors(ContextCompat.getColor(context, R.color.achievement), ContextCompat.getColor(context, R.color.target_color));
            set.setStackLabels(new String[]{getString(R.string.achievement), getString(R.string.targets)});
            set.setDrawIcons(false);
            set.setDrawValues(false); // Enable value drawing
            if (CommonFunctions.isTablet(context)) {
                set.setValueTextSize(15f); // Set the text size for the values
            } else {
                set.setValueTextSize(10f); // Set the text size for the values
            }
            set.setValueTextColor(Color.WHITE);
            BarData data = new BarData(set);
            barChart.setDrawValueAboveBar(false);
            barChart.setDrawBarShadow(false);
            barChart.setDrawGridBackground(false);
            ///decrease width for 3 column
            if (downs.size() == 1) {
                data.setBarWidth(0.2f);
            } else if (downs.size() > 1 && downs.size() <= 3) {
                data.setBarWidth(0.5f);
            }
            barChart.setData(data);

            XAxis xAxis = barChart.getXAxis();
            xAxis.setValueFormatter(new IndexAxisValueFormatter(productsgroupnames));
            barChart.setVisibleXRangeMaximum(productsgroupnames.length);
            xAxis.setGranularity(1f);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            /////YAxisLeft
            YAxis yAxisLeft = barChart.getAxisLeft();
            yAxisLeft.setAxisMinimum(5f);
            yAxisLeft.setDrawGridLines(false);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            // yAxisLeft.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
            yAxisLeft.setEnabled(true);
            yAxisLeft.setDrawZeroLine(true);
            //remove left border
            yAxisLeft.setDrawAxisLine(true);
            yAxisLeft.setTextColor(R.color.text_grey_color);

            YAxis yAxisRight = barChart.getAxisRight();
            //remove right border
            yAxisRight.setAxisMinimum(5f);
            yAxisRight.setDrawGridLines(false);
            //remove left border
            yAxisRight.setDrawAxisLine(false);
            yAxisRight.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
            yAxisRight.setEnabled(false);

            barChart.getXAxis().setDrawGridLines(false);
            barChart.getDescription().setEnabled(false);
            //remove top border
            barChart.getXAxis().setDrawAxisLine(false);
            BarChartCustomRenderer barChartCustomRenderer
                    = new BarChartCustomRenderer(barChart, barChart.getAnimator(), barChart.getViewPortHandler());
            barChart.setRenderer(barChartCustomRenderer);
            barChart.getLegend().setEnabled(false);
            barChart.invalidate();

        } catch (Resources.NotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    private void iduserinterface() {
       preferences = PrefHelper.getPrefs(context);
        counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        recycle_reports = (RecyclerView) findViewById(R.id.recycle_reports);
        rlIncentiveDetail = (LinearLayout) findViewById(R.id.rlIncentiveDetail);
        rlLeaderBInfo = (LinearLayout) findViewById(R.id.rlLeaderBInfo);
        rlTVADetails = (LinearLayout) findViewById(R.id.rlTVADetails);
        ///////////////////
        tvEIncentive = (TextView) findViewById(R.id.tvEIncentive);
        tvMaxIncentive = (TextView) findViewById(R.id.tvMaxIncentive);
        tvSaleLinkedIncentive = (TextView) findViewById(R.id.tvSaleLinkedIncentive);
        tvTotalIncentive = (TextView) findViewById(R.id.tvTotalIncentive);
        tvFlatIncentive = (TextView) findViewById(R.id.tvFlatIncentive);
        ////For no data view
        tvNodata = (TextView) findViewById(R.id.tvNodata);

        if (kPI != null && kPI.equals("Incentive")) {
            setTitle("Incentive Details  - " + visit_date);
        } else {
            setTitle((kPI != null && kPI.equals("LeaderBoard")) ? "Leader Board Details - " + visit_date : "Target vs Achievement  - " + visit_date);
        }
        db = new Lorealba_Database(context);
        db.open();
    }


    private class DashTVADrillDownAdapter extends RecyclerView.Adapter<DashTVADrillDownAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<AppDashboardTVADrillDown> data;

        public DashTVADrillDownAdapter(Context context, List<AppDashboardTVADrillDown> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;
        }

        @NonNull
        @Override
        public DashTVADrillDownAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate((kPI != null && kPI.equals("LeaderBoard")) ? R.layout.row_leaderboard_info : R.layout.row_tva_drill_down, parent, false);
            return new DashTVADrillDownAdapter.MyViewHolder(view);
        }

        @SuppressLint({"SetTextI18n", "DefaultLocale"})
        @Override
        public void onBindViewHolder(@NonNull final MyViewHolder viewholder, final int position) {
            final AppDashboardTVADrillDown current = data.get(position);
            if (kPI != null && kPI.equals("LeaderBoard")) {
                viewholder.tvProductGroup.setText(capitalizeFirstLetter(current.getProductGroupName()));
                viewholder.tvProductGroup.setId(position);

                viewholder.tvTotalSales.setText(current.getGraph());
                viewholder.tvTotalSales.setId(position);

                viewholder.tvAchPer.setText(current.getPer().toString() + "%");
                viewholder.tvAchPer.setId(position);

            } else {
                viewholder.tvProductGroup.setText(capitalizeFirstLetter(current.getProductGroupName()));
                viewholder.tvProductGroup.setId(position);
                viewholder.tvTargets.setText(String.format("%.0f", current.getTarget()));
                viewholder.tvTargets.setId(position);
                viewholder.tvTotalSales.setText(String.format("%.0f", current.getTotalSale()));
                viewholder.tvTotalSales.setId(position);
                viewholder.tvAchPer.setText(current.getPer().toString() + "%");
                viewholder.tvAchPer.setId(position);
                if (position == data.size() - 1) {
                    viewholder.cardtotalValues.setVisibility(View.VISIBLE);
                    viewholder.cardtotalValues.setId(position);
                    viewholder.tvCalculatedSales.setText(String.valueOf(_totalsales));
                    viewholder.tvCalculatedSales.setId(position);
                    viewholder.tvtotalTargets.setText(String.valueOf(totalTarget));
                    viewholder.tvtotalTargets.setId(position);
                } else {
                    viewholder.cardtotalValues.setVisibility(View.GONE);
                    viewholder.cardtotalValues.setId(position);
                }
            }
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvProductGroup, tvTargets, tvTotalSales, tvAchPer, tvtotalTargets, tvCalculatedSales;
            CardView cardtotalValues;

            public MyViewHolder(View itemView) {
                super(itemView);
                if (kPI != null && kPI.equals("LeaderBoard")) {
                    tvProductGroup = (TextView) itemView.findViewById(R.id.tvProductGroup);
                    tvTotalSales = (TextView) itemView.findViewById(R.id.tvTotalSales);
                    tvAchPer = (TextView) itemView.findViewById(R.id.tvAchPer);
                } else {
                    tvProductGroup = (TextView) itemView.findViewById(R.id.tvProductGroup);
                    tvTargets = (TextView) itemView.findViewById(R.id.tvTargets);
                    tvTotalSales = (TextView) itemView.findViewById(R.id.tvTotalSales);
                    tvAchPer = (TextView) itemView.findViewById(R.id.tvAchPer);

                    cardtotalValues = (CardView) itemView.findViewById(R.id.cardtotalValues);
                    tvtotalTargets = (TextView) itemView.findViewById(R.id.tvtotalTargets);
                    tvCalculatedSales = (TextView) itemView.findViewById(R.id.tvCalculatedSales);
                }
            }
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            this.finish();
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        this.finish();
    }

    private void combinedChart() {
        try {
            // initializing variable for bar chart.
            barChart.setVisibility(View.GONE);
            combinedChart.setVisibility(View.VISIBLE);
            combinedChart.getDescription().setEnabled(false);

            BarDataSet barDataSet = new BarDataSet(targetBarEntries, getString(R.string.targets));
            barDataSet.setColor(context.getResources().getColor(R.color.target_color));
            barDataSet.setDrawIcons(false);
            BarData barData = new BarData(barDataSet);
            barData.setDrawValues(false); // Enable value drawing

            if (CommonFunctions.isTablet(context)) {
                barData.setValueTextSize(15f); // Set the text size for the values
            } else {
                barData.setValueTextSize(10f); // Set the text size for the values
            }
            barData.setValueTextColor(Color.BLUE);
            // Use the custom VerticalValueFormatter
            barDataSet.setValueFormatter(new VerticalValueFormatter());

            LineDataSet lineDataSet = new LineDataSet(barEntries, getString(R.string.achievement));
            lineDataSet.setColor(context.getResources().getColor(R.color.achievement));
            lineDataSet.setLineWidth(2.5f);
            lineDataSet.setCircleColor(context.getResources().getColor(R.color.achievement));
            lineDataSet.setCircleRadius(4f);
            lineDataSet.setFillColor(context.getResources().getColor(R.color.achievement));
            lineDataSet.setDrawValues(false);
            lineDataSet.setDrawIcons(false);
            if (CommonFunctions.isTablet(context)) {
                lineDataSet.setValueTextSize(15f); // Set the text size for the values
            } else {
                lineDataSet.setValueTextSize(10f); // Set the text size for the values
            }

            lineDataSet.setValueTextColor(Color.GREEN);
            lineDataSet.setMode(LineDataSet.Mode.STEPPED);
            LineData lineData = new LineData(lineDataSet);
            // Combine the data sets
            CombinedData combinedData = new CombinedData();
            combinedData.setData(barData);
            combinedData.setData(lineData);
            // Set data to the chart
            combinedChart.setData(combinedData);
            // Customize X-axis
            XAxis xAxis = combinedChart.getXAxis();
            xAxis.setValueFormatter(new IndexAxisValueFormatter(productsgroupnames));
            combinedChart.setVisibleXRangeMaximum(productsgroupnames.length);
            xAxis.setGranularity(1f);
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            /////YAxisLeft
            YAxis yAxisLeft = combinedChart.getAxisLeft();
            yAxisLeft.setAxisMinimum(5f);
            yAxisLeft.setDrawGridLines(false);
            //remove left border
            yAxisLeft.setDrawAxisLine(false);
            yAxisLeft.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
            yAxisLeft.setEnabled(false);

            YAxis yAxisRight = combinedChart.getAxisRight();
            //remove right border
            yAxisRight.setAxisMinimum(1f);
            yAxisRight.setDrawGridLines(false);
            //remove left border
            yAxisRight.setDrawAxisLine(false);
            yAxisRight.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
            yAxisRight.setEnabled(false);

            combinedChart.getXAxis().setDrawGridLines(false);
            combinedChart.getDescription().setEnabled(false);
            //remove top border
            combinedChart.getXAxis().setDrawAxisLine(false);
            combinedChart.getLegend().setEnabled(false);
            combinedChart.setScaleEnabled(false);
            combinedChart.invalidate();
        } catch (Resources.NotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    @SuppressLint("SetTextI18n")
    private void incentiveDetail() {
        db.open();
        AppDashboardIncentive incentive = db.getDashboardIncentiveDetail(counter_Id, username);
        if (incentive != null) {
            rlLeaderBInfo.setVisibility(View.GONE);
            try {
                rlIncentiveDetail.setVisibility(View.VISIBLE);
                tvEIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getToatlIncentive().intValue());
                tvMaxIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getMaximumIncentive().intValue());
                tvSaleLinkedIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getSLIncentive().intValue());
                tvFlatIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getFlatIncentive().intValue());
                tvTotalIncentive.setText(context.getString(R.string.Rs) + " " + incentive.getToatlIncentive().intValue());
                rlTVADetails.setVisibility(View.GONE);
            } catch (Exception e) {
                e.fillInStackTrace();
            }
        } else tvNodata.setVisibility(View.VISIBLE);
    }

    private void TVAdeTail() {
        db.open();
        downs = db.getDashboardTVADrillDown(counter_Id);
        if (!downs.isEmpty()) {
            ArrayList<String> names = new ArrayList<>();
            rlIncentiveDetail.setVisibility(View.GONE);
            rlTVADetails.setVisibility(View.VISIBLE);
            rlLeaderBInfo.setVisibility(View.GONE);
            targetBarEntries = new ArrayList<>();
            barEntries = new ArrayList<>();
            entries = new ArrayList<>();

            for (int k = 0; k < downs.size(); k++) {
                _totalsales += downs.get(k).getTotalSale().intValue();
                totalTarget += downs.get(k).getTarget().intValue();
                names.add(capitalizeFirstLetter(downs.get(k).getProductGroupName()));
                entries.add(new BarEntry(k, new float[]{downs.get(k).getTotalSale().
                        intValue(), downs.get(k).getTarget().intValue()}));
                targetBarEntries.add(new BarEntry(k,
                        downs.get(k).getTarget().intValue()));
                barEntries.add(new BarEntry(k,
                        downs.get(k).getTotalSale().intValue()));
            }
            productsgroupnames = names.toArray(new String[0]);
                /*if (appDashboardTVADrillDowns.get(0).getGraph().equals("Bar Chart")) {
                    barChart();
                } else {
                    combinedChart();
                }*/
            barChart();
            Adapter(recycle_reports);
        } else tvNodata.setVisibility(View.VISIBLE);
    }
}
