package com.cpm.lorealbaautomation.reports;

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

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

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
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.R;
import com.cpm.lorealbaautomation.adapter.SubAxeValueAdapter;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.BADeviceLoginGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.ReportSalesConsumerWise;
import com.cpm.lorealbaautomation.retrofit.PostApi;

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

import java.io.Serializable;
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 retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ReportConsumerWiseActivity extends AppCompatActivity {
    public ArrayList<ReportSalesConsumerWise> reportsList = new ArrayList<>();
    String counter_Id, visit_date, username, report_name = "", userType;
    private SharedPreferences preferences;
    RecyclerView recycle_reports;
    ProgressDialog loading;
    Context context;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reports_consumerwise);
        context = this;
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        userType = getIntent().getStringExtra(CommonString.KEY_USER_TYPE);
        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);
    }

    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);
        report_name = getIntent().getStringExtra(CommonString.Brand);
        setTitle("Reports Consumer Wise - " + visit_date);
        if (getIntent().getSerializableExtra(CommonString.TAG_OBJECT) != null) {
            reportsList = (ArrayList<ReportSalesConsumerWise>) getIntent().getSerializableExtra(CommonString.TAG_OBJECT);
        }

        assert reportsList != null;
        if (!reportsList.isEmpty()) {
            validatefilterui();
            recycle_reports.setAdapter(new ReportsAdapter(context, reportsList));
            recycle_reports.setLayoutManager(new LinearLayoutManager(context));
        }
    }

    private class ReportsAdapter extends RecyclerView.Adapter<ReportsAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<ReportSalesConsumerWise> data;

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

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

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

            holder.datewith_day.setText(current.getVisitDate() + " - " + current.getWeekDays());
            holder.datewith_day.setId(position);

            holder.consumer_name.setText(current.getConsumerName());
            holder.consumer_name.setId(position);

            holder.mobile_no.setText(current.getMobileNumber());
            holder.mobile_no.setId(position);

            holder.txt_qty.setText(String.valueOf(current.getQty()));
            holder.txt_qty.setId(position);

            holder.txt_salevalue.setText(String.valueOf(current.getSalesValue()));
            holder.txt_salevalue.setId(position);

            holder.consumer_name.setOnClickListener(view -> downloadreportConsumerWise(current));
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView datewith_day, consumer_name, mobile_no, txt_qty, txt_salevalue;
            CardView sale_card;

            public MyViewHolder(View itemView) {
                super(itemView);
                datewith_day = (TextView) itemView.findViewById(R.id.datewith_day);
                consumer_name = (TextView) itemView.findViewById(R.id.consumer_name);
                mobile_no = (TextView) itemView.findViewById(R.id.mobile_no);
                txt_qty = (TextView) itemView.findViewById(R.id.txt_qty);
                txt_salevalue = (TextView) itemView.findViewById(R.id.txt_salevalue);
                sale_card = (CardView) itemView.findViewById(R.id.sale_card);
            }
        }
    }

    @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);
            ReportConsumerWiseActivity.this.finish();

        }


        return super.onOptionsItemSelected(item);
    }

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

    private void downloadreportConsumerWise(final ReportSalesConsumerWise current) {
        try {

            JSONObject obj = new JSONObject();
            obj.put("Downloadtype", userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME) ?
                    "Report_SalesConsumerProductwiseME" : "Report_SalesConsumerProductwise");
            obj.put("Username", username);
            obj.put("Param1", current.getCounterId());
            obj.put("Param2", current.getTId());
            loading = ProgressDialog.show(context, "Processing", "Please wait...", false, false);
            final 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"), obj.toString());
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<String> call_login_tym = api.getDownloadAll(jsonData);
            call_login_tym.enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data_consumer_wise = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            loading.dismiss();
                            data_consumer_wise = response.body();
                            assert data_consumer_wise != null;
                            if (!data_consumer_wise.equals("")) {
                                BADeviceLoginGetterSetter consumerwiseSaleObject = null;
                                if (!data_consumer_wise.contains("No Data")) {
                                    consumerwiseSaleObject = new Gson().fromJson(data_consumer_wise, BADeviceLoginGetterSetter.class);
                                    if (consumerwiseSaleObject != null) {
                                        startActivity(new Intent(context, ReportConsumerProductWiseActivity.class).
                                                putExtra(CommonString.TAG_OBJECT, userType != null && userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)
                                                        ? (Serializable) consumerwiseSaleObject.getReportSalesConsumerProductwiseMe()
                                                        : (Serializable) consumerwiseSaleObject.getReportSalesConsumerProductwise())
                                                .putExtra(CommonString.KEY_Consumer_Object, current));
                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                    }
                                } else {
                                    AlertandMessages.showToastMsg(context, "Consumer Wise Sale Report Not found");
                                }
                            }
                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();
                            AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + " - " + e.toString());
                        }
                    } else {
                        loading.dismiss();
                        AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    loading.dismiss();
                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION);
                }
            });

        } catch (JSONException e) {
            e.fillInStackTrace();
            loading.dismiss();
            AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INVALID_JSON);
        }
    }

    @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(), "Sub Axe", true,false, (filterText, placeHolder) -> {}));
    }
}
