package com.cpm.lorealbaautomation.reports.testerdetails;

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.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.CommonString;
import com.cpm.lorealbaautomation.databinding.CounterGrowthDetailBinding;
import com.cpm.lorealbaautomation.databinding.DetailTesterUsageBinding;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.ResponseResult;
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 TesterUsageReportActivity extends AppCompatActivity {
    ArrayList<ReportTesterCounterDetail> testerUsageCounter = new ArrayList<>();
    String counter_Id, visit_date, username, default_type = "Axe";
    RecyclerView recyclTesterCounter, recyclTesterUsageDetail;
    LinearLayout rlTesterUsage, rlTesterUsageDetails;
    TextView tvKPICounter, tvParamCode, tvParamName;
    private SharedPreferences preferences;
    Lorealba_Database db;
    Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tester_usage_report);
        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);
        validatefilterui();
        testerCounterUsageReport();
    }

    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, "");
        ////////
        recyclTesterCounter = findViewById(R.id.recyclTesterCounter);
        rlTesterUsage = findViewById(R.id.rlTesterUsage);
        tvKPICounter = findViewById(R.id.tvKPICounter);
        recyclTesterUsageDetail = findViewById(R.id.recyclTesterUsageDetail);
        rlTesterUsageDetails = findViewById(R.id.rlTesterUsageDetails);
        tvParamCode = findViewById(R.id.tvParamCode);
        tvParamName = findViewById(R.id.tvParamName);
        setTitle(getIntent().getStringExtra(CommonString.Brand) + " Report " + " - " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
    }

    private class TesterUsageAdapter extends RecyclerView.Adapter<TesterUsageAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ReportTesterCounterDetail> data;
        String param;
        boolean detail;

        public TesterUsageAdapter(Context context, List<ReportTesterCounterDetail> data, boolean detail, String param) {
            inflator = LayoutInflater.from(context);
            this.param = param;
            this.detail = detail;
            this.data = data;
        }

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

        @SuppressLint({"SetTextI18n", "DefaultLocale"})
        @Override
        public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
            final ReportTesterCounterDetail current = data.get(position);
            if (detail) {
                holder.tvRowParamName.setText(current.getParamName());
                holder.rlTesterUsageDetail.setVisibility(View.VISIBLE);
                holder.tvParamCode.setText(current.getParamCode());
                holder.rlTesterCounter.setVisibility(View.GONE);
                holder.rlTesterUsageDetail.setId(position);
                holder.rlTesterCounter.setId(position);
                holder.tvRowParamName.setId(position);
                holder.tvParamCode.setId(position);
            } else {
                holder.rlTesterCounter.setVisibility(View.VISIBLE);
                holder.rlTesterUsageDetail.setVisibility(View.GONE);
                holder.rlTesterUsageDetail.setId(position);
                holder.rlTesterCounter.setId(position);
            }

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

            setText(detail ? holder.tvOPSSTKDetail : holder.tvOPSSTK, position, current.getOpeningStock().toString());
            setText(detail ? holder.tvInvQTYDetail : holder.tvInvQTY, position, current.getInvoicedQty().toString());

            setText(detail ? holder.tvRCVDQTYDetail : holder.tvRCVDQTY, position, current.getReceivedQty().toString());
            setText(detail ? holder.tvTesterSTKAVAILDetail : holder.tvTesterSTKAVAIL, position, current.getTesterStockAvailable().toString());
            setText(detail ? holder.tvTesterUsedDetail : holder.tvTesterUsed, position, current.getTesterUsed().toString());
            setText(detail ? holder.tvTesterUsedPerDetail : holder.tvTesterUsedPer, position, current.getTesterUsedPer().toString() + "%");
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            LinearLayout rlTesterCounter, rlTesterUsageDetail, rlParent;
            TextView tvOPSSTK, tvInvQTY, tvRCVDQTY, tvTesterSTKAVAIL, tvTesterUsed, tvTesterUsedPer, tvParamCode, tvRowParamName, tvOPSSTKDetail, tvInvQTYDetail, tvRCVDQTYDetail, tvTesterSTKAVAILDetail, tvTesterUsedDetail, tvTesterUsedPerDetail;

            public MyViewHolder(View itemView) {
                super(itemView);
                rlParent = (LinearLayout) itemView.findViewById(R.id.rlParent);
                rlTesterCounter = (LinearLayout) itemView.findViewById(R.id.rlTesterCounter);
                tvOPSSTK = (TextView) itemView.findViewById(R.id.tvOPSSTK);
                tvInvQTY = (TextView) itemView.findViewById(R.id.tvInvQTY);
                tvRCVDQTY = (TextView) itemView.findViewById(R.id.tvRCVDQTY);
                tvTesterSTKAVAIL = (TextView) itemView.findViewById(R.id.tvTesterSTKAVAIL);
                tvTesterUsed = (TextView) itemView.findViewById(R.id.tvTesterUsed);
                tvTesterUsedPer = (TextView) itemView.findViewById(R.id.tvTesterUsedPer);
                ///details IDS
                rlTesterUsageDetail = (LinearLayout) itemView.findViewById(R.id.rlTesterUsageDetail);
                tvParamCode = (TextView) itemView.findViewById(R.id.tvParamCode);
                tvRowParamName = (TextView) itemView.findViewById(R.id.tvRowParamName);
                tvOPSSTKDetail = (TextView) itemView.findViewById(R.id.tvOPSSTKDetail);
                tvInvQTYDetail = (TextView) itemView.findViewById(R.id.tvInvQTYDetail);
                tvRCVDQTYDetail = (TextView) itemView.findViewById(R.id.tvRCVDQTYDetail);
                tvTesterSTKAVAILDetail = (TextView) itemView.findViewById(R.id.tvTesterSTKAVAILDetail);
                tvTesterUsedDetail = (TextView) itemView.findViewById(R.id.tvTesterUsedDetail);
                tvTesterUsedPerDetail = (TextView) itemView.findViewById(R.id.tvTesterUsedPerDetail);
            }
        }
    }

    @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();
    }

    @SuppressLint("SetTextI18n")
    private void testerCounterUsageReport() {
        db.open();
        //Counter Tester Usage
        testerUsageCounter = db.getTesterCounterUsageReport(counter_Id, false);
        if (!testerUsageCounter.isEmpty()) {
            recyclTesterCounter.setAdapter(new TesterUsageAdapter(context, testerUsageCounter, false, null));
            recyclTesterCounter.setLayoutManager(new LinearLayoutManager(context));
            rlTesterUsage.setVisibility(View.VISIBLE);
        }

        testerCounterUsageDetail(default_type, null);
    }

    @SuppressLint("SetTextI18n")
    private void testerCounterUsageDetail(String param, ProgressDialog dialog) {
        //details
        testerUsageCounter = db.getTesterCounterUsageReport(counter_Id, true);
        if (!testerUsageCounter.isEmpty()) {
            tvParamCode.setText(param + " Code");
            tvParamName.setText(param + " Name");
            recyclTesterUsageDetail.setAdapter(new TesterUsageAdapter(context, testerUsageCounter, true, param));
            recyclTesterUsageDetail.setLayoutManager(new LinearLayoutManager(context));
            rlTesterUsageDetails.setVisibility(View.VISIBLE);
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    @SuppressLint("DefaultLocale")
    private void setText(TextView tv, int pos, String value) {
        tv.setTextColor(ContextCompat.getColor(context, R.color.black));
        tv.setText(value);
        tv.setId(pos);
    }

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

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

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

            if (detail) {
                binding.rlParamCode.setVisibility(View.VISIBLE);
                binding.rlParamName.setVisibility(View.VISIBLE);
            }

            binding.tvParamCodePlaceHolder.setText(param + " Code");
            binding.tvParamCode.setText(object.getParamCode());
            binding.tvParamNamePlaceHolder.setText(param + " Name");
            binding.tvParamName.setText(object.getParamName());
            binding.tvOPSSTK.setText(object.getOpeningStock().toString());
            binding.tvInvQTY.setText(object.getInvoicedQty().toString());
            binding.tvTeserUsed.setText(object.getTesterUsed().toString());
            binding.tvRecievedqty.setText(object.getReceivedQty().toString());
            binding.tvTesterUsedPer.setText(object.getTesterUsedPer().toString() + "%");
            binding.tvTesterSTKAVAIL.setText(object.getTesterStockAvailable().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";
            String download_key = "Report_TesterCounterDetail";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", download_key);
            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 {
                                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.")) {
                                    testerCounterUsageDetail(param, finalLoading);
                                } else {
                                    ResponseResult testerCounterDetail = new Gson().fromJson(data, ResponseResult.class);
                                    db.open();
                                    if (testerCounterDetail != null) {
                                        db.insertTesterCounterDetail(testerCounterDetail);
                                        testerCounterUsageDetail(param, finalLoading);
                                    }
                                }
                            } catch (Exception e) {
                                testerCounterUsageDetail(param, finalLoading);
                            }
                        } else {
                            testerCounterUsageDetail(param, finalLoading);
                        }
                    }

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

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

}