package com.cpm.lorealbaautomation.reports;

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

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

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

import com.google.android.material.appbar.AppBarLayout;
import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.databinding.CounterGrowthDetailBinding;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
import com.cpm.lorealbaautomation.reports.offtakemodels.SalesGrowthSubAxe;
import com.cpm.lorealbaautomation.retrofit.PostApi;

import org.json.JSONException;
import org.json.JSONObject;

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

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class DashbordOffTakeReportActivity extends AppCompatActivity {
    ArrayList<SalesGrowthSubAxe> salesGrowthSubAxes = new ArrayList<>();
    RecyclerView recyclSalesGrowthCounter, recyclSalesGrowthDetails;
    String counter_Id, visit_date, username, default_type = "Axe";
    LinearLayout rlSalesGrowthCounter, rlSalesGSubAxe;
    TextView tvKPICounter, tvKPISubAxe, tvParamCode,
            tvParamName;
    AppBarLayout appBarLayout;
    private SharedPreferences preferences;
    Lorealba_Database db;
    Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dash_offtake);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        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);
        counterSalesGrowth();
        OffTakeTesterUsageDetails(default_type, null);
        validatefilterui();
    }

    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, "");
        ////////
        recyclSalesGrowthCounter = findViewById(R.id.recyclSalesGrowthCounter);
        rlSalesGrowthCounter = findViewById(R.id.rlSalesGrowthCounter);
        tvKPICounter = findViewById(R.id.tvKPICounter);
        recyclSalesGrowthDetails = findViewById(R.id.recyclSalesGSubAxe);
        rlSalesGSubAxe = findViewById(R.id.rlSalesGSubAxe);
        tvKPISubAxe = findViewById(R.id.tvKPISubAxe);
        tvParamCode = (TextView) findViewById(R.id.tvParamCode);
        tvParamName = (TextView) findViewById(R.id.tvParamName);
        appBarLayout = findViewById(R.id.appBarLayout);
        setTitle(getIntent().getStringExtra(CommonString.Brand) + " Report " + " - " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
    }

    private class OffTakeAdapter extends RecyclerView.Adapter<OffTakeAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<SalesGrowthSubAxe> data;
        String param;
        boolean details;

        public OffTakeAdapter(Context context, List<SalesGrowthSubAxe> data, String param, boolean details) {
            inflator = LayoutInflater.from(context);
            this.details = details;
            this.param = param;
            this.data = data;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.row_offtake, parent, false);
            return new MyViewHolder(view);
        }

        @SuppressLint({"SetTextI18n", "DefaultLocale"})
        @Override
        public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
            final SalesGrowthSubAxe current = data.get(position);
            if (details) {
                holder.tvParamName.setText(CommonFunctions.capitalizeFirstLetter(current.getParamName()));
                holder.tvParamCode.setText(current.getParamCode());
                holder.rlRowSalesGSubAxe.setVisibility(View.VISIBLE);
                holder.rlRSalesGrowthCounter.setVisibility(View.GONE);
                holder.rlRSalesGrowthCounter.setId(position);
                holder.rlRowSalesGSubAxe.setId(position);
                holder.tvParamName.setId(position);
                holder.tvParamCode.setId(position);
            } else {
                holder.rlRSalesGrowthCounter.setVisibility(View.VISIBLE);
                holder.rlRowSalesGSubAxe.setVisibility(View.GONE);
                holder.rlRSalesGrowthCounter.setId(position);
                holder.rlRowSalesGSubAxe.setId(position);
            }

            holder.rlParent.setOnLongClickListener(v -> {
                new DetailsDailog((AppCompatActivity) context, current, param, details).show();
                return false;
            });

            setText(details ? holder.tvLSTYSameMoSaleSubAxe : holder.tvLSTYSameMoSale, position, String.format("%.0f", current.getLastYearSameMonthSale()), false);
            setText(details ? holder.tvL3M_AvgSaleSubAxe : holder.tvL3M_AvgSale, position, String.format("%.0f", current.getL3MAvgSale()), false);
            setText(details ? holder.tvCurrentMonthSaleSubAxe : holder.tvCurrentMonthSale, position, String.format("%.0f", current.getCurrentMonthSale()), false);
            setText(details ? holder.tvGrowthoverLSTYearPerSubAxe : holder.tvGrowthoverLSTYearPer, position, current.getGrowthOverLastYearPer().toString() + "%", true);
            setText(details ? holder.tvGrowthoverL3MPerSubAxe : holder.tvGrowthoverL3MPer, position, current.getGrowthOverL3MPer().toString() + "%", true);
            setText(details ? holder.tvClsStkLSTMonthSubAxe : holder.tvClsStkLSTMonth, position, String.format("%.0f", current.getClosingStockLastMonth()), false);
            setText(details ? holder.tvNODSubAxe : holder.tvNOD, position, current.getNod().toString() + "%", false);
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            LinearLayout rlRSalesGrowthCounter, rlRowSalesGSubAxe, rlParent;
            TextView tvLSTYSameMoSale, tvL3M_AvgSale, tvCurrentMonthSale, tvGrowthoverLSTYearPer, tvGrowthoverL3MPer, tvClsStkLSTMonth, tvNOD,
                    tvLSTYSameMoSaleSubAxe, tvL3M_AvgSaleSubAxe, tvCurrentMonthSaleSubAxe,
                    tvGrowthoverLSTYearPerSubAxe, tvGrowthoverL3MPerSubAxe, tvClsStkLSTMonthSubAxe, tvNODSubAxe,
                    tvParamCode, tvParamName;

            public MyViewHolder(View itemView) {
                super(itemView);
                rlParent = (LinearLayout) itemView.findViewById(R.id.rlParent);
                rlRSalesGrowthCounter = (LinearLayout) itemView.findViewById(R.id.rlRSalesGrowthCounter);
                tvLSTYSameMoSale = (TextView) itemView.findViewById(R.id.tvLSTYSameMoSale);
                tvL3M_AvgSale = (TextView) itemView.findViewById(R.id.tvL3M_AvgSale);
                tvCurrentMonthSale = (TextView) itemView.findViewById(R.id.tvCurrentMonthSale);
                tvGrowthoverLSTYearPer = (TextView) itemView.findViewById(R.id.tvGrowthoverLSTYearPer);
                tvGrowthoverL3MPer = (TextView) itemView.findViewById(R.id.tvGrowthoverL3MPer);
                tvClsStkLSTMonth = (TextView) itemView.findViewById(R.id.tvClsStkLSTMonth);
                tvNOD = (TextView) itemView.findViewById(R.id.tvNOD);
                rlRowSalesGSubAxe = (LinearLayout) itemView.findViewById(R.id.rlRowSalesGSubAxe);
                tvParamCode = (TextView) itemView.findViewById(R.id.tvParamCode);
                tvParamName = (TextView) itemView.findViewById(R.id.tvParamName);
                tvLSTYSameMoSaleSubAxe = (TextView) itemView.findViewById(R.id.tvLSTYSameMoSaleSubAxe);
                tvL3M_AvgSaleSubAxe = (TextView) itemView.findViewById(R.id.tvL3M_AvgSaleSubAxe);
                tvCurrentMonthSaleSubAxe = (TextView) itemView.findViewById(R.id.tvCurrentMonthSaleSubAxe);
                tvGrowthoverLSTYearPerSubAxe = (TextView) itemView.findViewById(R.id.tvGrowthoverLSTYearPerSubAxe);
                tvGrowthoverL3MPerSubAxe = (TextView) itemView.findViewById(R.id.tvGrowthoverL3MPerSubAxe);
                tvClsStkLSTMonthSubAxe = (TextView) itemView.findViewById(R.id.tvClsStkLSTMonthSubAxe);
                tvNODSubAxe = (TextView) itemView.findViewById(R.id.tvNODSubAxe);
            }
        }
    }

    @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 counterSalesGrowth() {
        db.open();
        //Counter Growth
        salesGrowthSubAxes = db.getSalesGrowthReport(counter_Id, false);
        if (!salesGrowthSubAxes.isEmpty()) {
            recyclSalesGrowthCounter.setAdapter(new OffTakeAdapter(context, salesGrowthSubAxes, null, false));
            recyclSalesGrowthCounter.setLayoutManager(new LinearLayoutManager(context));
            rlSalesGrowthCounter.setVisibility(View.VISIBLE);
        }
    }

    @SuppressLint("DefaultLocale")
    private void setText(TextView tv, int pos, String value, boolean checkValue) {
        if (checkValue && (value.substring(0, 1).contains("-") || value.substring(0, 1).contains("0"))) {
            tv.setTextColor(ContextCompat.getColor(context, R.color.light_red));
        } else {
            tv.setTextColor(ContextCompat.getColor(context, R.color.black));
        }
        tv.setText(value);
        tv.setId(pos);
    }

    private class DetailsDailog extends Dialog {
        private final SalesGrowthSubAxe object;
        private final boolean detail;
        String param;

        public DetailsDailog(AppCompatActivity activity, SalesGrowthSubAxe object, String param, boolean details) {
            super(activity);
            this.param = param;
            this.detail = details;
            this.object = object;
        }

        @SuppressLint({"SetTextI18n", "DefaultLocale"})
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            com.cpm.lorealbaautomation.databinding.CounterGrowthDetailBinding binding = CounterGrowthDetailBinding.inflate(getLayoutInflater());
            setContentView(binding.getRoot());
            Objects.requireNonNull(getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            binding.imgClose.setOnClickListener(v -> dismiss());

            if (detail && param != null) {
                assert binding.rlParamCode != null;
                binding.rlParamCode.setVisibility(View.VISIBLE);
                assert binding.rlParamName != null;
                binding.rlParamName.setVisibility(View.VISIBLE);

                assert binding.tvParamCodePlaceHolder != null;
                binding.tvParamCodePlaceHolder.setText(param + " Code");
                assert binding.tvParamCode != null;
                binding.tvParamCode.setText(object.getParamCode());
                assert binding.tvParamNamePlaceHolder != null;
                binding.tvParamNamePlaceHolder.setText(param + " Name");
                assert binding.tvParamName != null;
                binding.tvParamName.setText(object.getParamName());
            }

            if ((object.getGrowthOverLastYearPer().toString().substring(0, 1).contains("-") || object.getGrowthOverLastYearPer().toString().substring(0, 1).contains("0"))) {
                binding.tvGrowthOverLastYearPer.setTextColor(ContextCompat.getColor(getContext(), R.color.light_red));
            } else
                binding.tvGrowthOverLastYearPer.setTextColor(ContextCompat.getColor(getContext(), R.color.black));
            if ((object.getGrowthOverL3MPer().toString().substring(0, 1).contains("-") || object.getGrowthOverL3MPer().toString().substring(0, 1).contains("0"))) {
                binding.TvGrowthOverL3MPer.setTextColor(ContextCompat.getColor(getContext(), R.color.light_red));
            } else
                binding.TvGrowthOverL3MPer.setTextColor(ContextCompat.getColor(getContext(), R.color.black));

            binding.tvLastYearSameMonthSale.setText(getString(R.string.Rs) + " " + String.format("%.0f", object.getLastYearSameMonthSale()));
            binding.tvL3MAvgSale.setText(getString(R.string.Rs) + " " + String.format("%.0f", object.getL3MAvgSale()));
            binding.tvCurrentMonthSale.setText(getString(R.string.Rs) + " " + String.format("%.0f", object.getCurrentMonthSale()));
            binding.tvGrowthOverLastYearPer.setText(object.getGrowthOverLastYearPer().toString() + "%");
            binding.TvGrowthOverL3MPer.setText(object.getGrowthOverL3MPer().toString() + "%");
            binding.tvClosingStockLastMonth.setText(String.format("%.0f", object.getClosingStockLastMonth()));
            binding.tvNOD.setText(object.getNod().toString() + "%");
        }

        @SuppressLint("SetTextI18n")
        @Override
        protected void onStart() {
            super.onStart();
            setCancelable(true);
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    private void validatefilterui() {
        RecyclerView rec_subaxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        rec_subaxe.setLayoutManager(new GridLayoutManager(context, 3));
        rec_subaxe.setAdapter(new SubAxeValueAdapter(context, getFilters(), default_type, false, true, (filterText, placeHolder) -> download_report(context, filterText)));
    }

    private void download_report(final Context context, String param) {
        ProgressDialog loading = null;
        try {
            String cParam = param;
            cParam = cParam.replaceAll(" ", "") + "Name";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", "Report_SalesGrowth_CounterDetail");
            jsonObject.put("Username", username);
            jsonObject.put("Param1", counter_Id);
            jsonObject.put("Param2", cParam);
            String jsonString = jsonObject.toString();
            try {
                loading = ProgressDialog.show(context, "Processing", "Please wait...", false, true);
                OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
                RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
                Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                PostApi api = adapter.create(PostApi.class);
                Call<ResponseBody> call = api.getTabjournePlan(jsonData);
                ProgressDialog finalLoading = loading;
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                        ResponseBody responseBody = response.body();
                        String data = null;
                        if (responseBody != null && response.isSuccessful()) {
                            try {
                                finalLoading.dismiss();
                                assert response.body() != null;
                                data = response.body().string();
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.contains("No Data") || data.equalsIgnoreCase(CommonString.KEY_FAILURE) || data.contains("Failure;Cannot find table 0.")) {
                                    OffTakeTesterUsageDetails(param, finalLoading);
                                } else {
                                    ResponseResult salesGrowthSubAxe = new Gson().fromJson(data, ResponseResult.class);
                                    if (salesGrowthSubAxe != null) {
                                        db.open();
                                        db.insertSalesGrowthCounterSubAxe(salesGrowthSubAxe);
                                        OffTakeTesterUsageDetails(param, finalLoading);
                                    }
                                }
                            } catch (Exception e) {
                                OffTakeTesterUsageDetails(param, finalLoading);
                            }
                        } else {
                            OffTakeTesterUsageDetails(param, finalLoading);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        OffTakeTesterUsageDetails(param, finalLoading);
                    }
                });
            } catch (Exception e) {
                OffTakeTesterUsageDetails(param, null);
            }

        } catch (JSONException e) {
            OffTakeTesterUsageDetails(param, null);
        }
    }

    @SuppressLint("SetTextI18n")
    private void OffTakeTesterUsageDetails(String param, ProgressDialog dialog) {
        salesGrowthSubAxes = db.getSalesGrowthReport(counter_Id, true);
        if (!salesGrowthSubAxes.isEmpty()) {
            tvParamCode.setText(param + " Code");
            tvParamName.setText(param + " Name");
            recyclSalesGrowthDetails.setAdapter(new OffTakeAdapter(context, salesGrowthSubAxes, param, true));
            recyclSalesGrowthDetails.setLayoutManager(new LinearLayoutManager(context));
            rlSalesGSubAxe.setVisibility(View.VISIBLE);
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }
}