package com.cpm.lorealbaautomation.reports;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
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.TextView;

import com.google.gson.Gson;
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.MasterProfileQuestionGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.ProductMaster;
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 SalesReportsActivity extends AppCompatActivity {
    String counter_Id, visit_date, username, report_name = "";
    ArrayList<ProductMaster> salereportList = new ArrayList<>();
    SharedPreferences preferences;
    RecyclerView recycle_reports, recSubAxe;
    String selectedSubAxe = "Axe";
    SubAxeValueAdapter subAxeValueAdapter;
    ArrayList<ProductMaster> listSubAxe;
    SaleReportsAdapter saleReportsAdapter;
    ProgressDialog loading = null;
    String userType = "";
    TextView product_name;
    Lorealba_Database db;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sales_reports);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        userType = getIntent().getStringExtra(CommonString.KEY_USER_TYPE);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        iduserinterface();
    }

    @SuppressLint("SetTextI18n")
    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);
        recSubAxe = (RecyclerView) findViewById(R.id.rec_subaxe);
        product_name = (TextView) findViewById(R.id.product_name);

        report_name = getIntent().getStringExtra(CommonString.Brand);
        setTitle("Sale Reports - " + visit_date);
        db = new Lorealba_Database(context);
        db.open();
        validatefilterui();
        if (CommonFunctions.checkNetIsAvailable(context)) {
            download_report(context);
        } else {
            call_adapter(context);
        }

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

    @SuppressLint("NotifyDataSetChanged")
    private void call_adapter(Context context) {
        db.open();
        salereportList = db.getsalesReports(selectedSubAxe, userType);
        if (!salereportList.isEmpty()) {
            saleReportsAdapter = new SaleReportsAdapter(context, salereportList);
            recycle_reports.setAdapter(saleReportsAdapter);
            recycle_reports.setLayoutManager(new LinearLayoutManager(context));
            saleReportsAdapter.notifyDataSetChanged();
        }
    }


    @SuppressLint("NotifyDataSetChanged")
    private void validatefilterui() {
        listSubAxe = new ArrayList<>();
        ProductMaster obj = new ProductMaster();
        obj.setSubAxeName("Axe");
        listSubAxe.add(obj);

        obj = new ProductMaster();
        obj.setSubAxeName("Sub Axe");
        listSubAxe.add(obj);

        obj = new ProductMaster();
        obj.setSubAxeName("Signature");
        listSubAxe.add(obj);

        obj = new ProductMaster();
        obj.setSubAxeName("Sub Brand");
        listSubAxe.add(obj);

        obj = new ProductMaster();
        obj.setSubAxeName("Brand");
        listSubAxe.add(obj);


        obj = new ProductMaster();
        obj.setSubAxeName("Product");
        listSubAxe.add(obj);

        recSubAxe.setLayoutManager(new GridLayoutManager(context, 3));
        subAxeValueAdapter = new SubAxeValueAdapter(context, listSubAxe);
        recSubAxe.setAdapter(subAxeValueAdapter);
        subAxeValueAdapter.notifyDataSetChanged();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // 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);
            SalesReportsActivity.this.finish();
        }

        return super.onOptionsItemSelected(item);
    }


    private class SubAxeValueAdapter extends RecyclerView.Adapter<SubAxeValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ProductMaster> data;

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

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


        @SuppressLint({"SetTextI18n", "NotifyDataSetChanged"})
        @Override
        public void onBindViewHolder(final SubAxeValueAdapter.MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);
            holder.tv_item.setText(current.getSubAxeName());
            holder.tv_item.setId(position);

            if (userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                holder.tv_item.setOnClickListener(v -> {
                    selectedSubAxe = current.getSubAxeName();
                    if (selectedSubAxe.equalsIgnoreCase("Product")) {
                        product_name.setText("Product Name");
                    } else if (selectedSubAxe.equalsIgnoreCase("Axe")) {
                        product_name.setText("Axe Name");
                    } else if (selectedSubAxe.equalsIgnoreCase("Sub Axe")) {
                        product_name.setText("Sub Axe Name");
                    } else if (selectedSubAxe.equalsIgnoreCase("Signature")) {
                        product_name.setText("Signature Name");
                    } else if (selectedSubAxe.equalsIgnoreCase("Sub Brand")) {
                        product_name.setText("Sub Brand Name");
                    } else if (selectedSubAxe.equalsIgnoreCase("Brand")) {
                        product_name.setText("Brand Name");
                    }
                    db.open();
                    saleReportsAdapter = new SaleReportsAdapter(context, db.getsalesReports(selectedSubAxe, userType));
                    recycle_reports.setAdapter(saleReportsAdapter);
                    recycle_reports.setLayoutManager(new LinearLayoutManager(context));
                    saleReportsAdapter.notifyDataSetChanged();
                    current.setSelected(true);
                    subAxeValueAdapter.notifyDataSetChanged();
                });
            }
            if (userType != null && !userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {
                holder.tv_item.setTextColor(inflator.getContext().getResources().getColor(R.color.white));
                holder.tv_item.setId(position);
                if (current.getSubAxeName().equalsIgnoreCase(selectedSubAxe)) {
                    holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.dashboard_ach));
                    holder.card.setId(position);
                } else {
                    holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.grey_dark_background));
                    holder.card.setId(position);
                }
            } else {
                holder.card.setCardBackgroundColor(inflator.getContext().getResources().getColor(R.color.circular_progress_default_background));
                holder.card.setId(position);

                holder.tv_item.setTextColor(inflator.getContext().getResources().getColor(R.color.disable_txt_color));
                holder.tv_item.setId(position);
            }
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tv_item;
            CardView card;

            public MyViewHolder(View itemView) {
                super(itemView);
                tv_item = (TextView) itemView.findViewById(R.id.tv_item);
                card = (CardView) itemView.findViewById(R.id.item_card);

            }
        }
    }


    private class SaleReportsAdapter extends RecyclerView.Adapter<SaleReportsAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ProductMaster> data;

        public SaleReportsAdapter(Context context, List<ProductMaster> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;

        }

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

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final SaleReportsAdapter.MyViewHolder holder, final int position) {
            final ProductMaster current = data.get(position);

            holder.txt_product_name.setText(current.getProductName());
            holder.txt_product_name.setId(position);

            holder.txtValue.setText(String.valueOf(current.getSaleValue()));
            holder.txtValue.setId(position);

            holder.txt_QTY.setText(current.getActualQty());
            holder.txt_QTY.setId(position);
        }

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


        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView txt_product_name, txt_QTY, txtValue;

            public MyViewHolder(View itemView) {
                super(itemView);
                txt_product_name = (TextView) itemView.findViewById(R.id.txt_product_name);
                txt_QTY = (TextView) itemView.findViewById(R.id.txt_QTY);
                txtValue = (TextView) itemView.findViewById(R.id.txtValue);
            }
        }
    }

    private void download_report(final Context context) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_Sales_DetailME" : "Report_Sales_Detail");
            jsonObject.put("Username", username);
            jsonObject.put("Param1", counter_Id);
            jsonObject.put("Param2", "");
            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);
                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.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    if (loading != null && loading.isShowing()) loading.dismiss();

                                    call_adapter(context);

                                } else if (!data.contains("No Data")) {
                                    if (loading != null && loading.isShowing()) loading.dismiss();

                                    MasterProfileQuestionGetterSetter reportSaleDetailsObject = new Gson().fromJson(data, MasterProfileQuestionGetterSetter.class);
                                    if (reportSaleDetailsObject != null) {
                                        db.open();
                                        db.insertReportSaleDetails(reportSaleDetailsObject, userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME));
                                    }
                                    call_adapter(context);


                                } else {
                                    if (loading != null && loading.isShowing()) loading.dismiss();

                                    db.open();
                                    db.delete_table_data(userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ? "Report_Sales_DetailME" : "Report_Sales_Detail");

                                    call_adapter(context);
                                }

                            } catch (Exception e) {
                                if (loading != null && loading.isShowing()) loading.dismiss();

                                call_adapter(context);
                            }
                        } else {
                            if (loading != null && loading.isShowing()) loading.dismiss();

                            call_adapter(context);

                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        if (loading != null && loading.isShowing()) loading.dismiss();

                        call_adapter(context);
                    }
                });

            } catch (Exception e) {
                if (loading != null && loading.isShowing()) loading.dismiss();

                call_adapter(context);

            }

        } catch (JSONException e) {
            if (loading != null && loading.isShowing()) loading.dismiss();

            call_adapter(context);
        }
    }


}
