package com.cpm.lorealbaautomation.consumeractivity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
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.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.ImageView;
import android.widget.TextView;

import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.InvoiceGetterSetter;

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

public class ConsumerIntractionDetailActivity extends AppCompatActivity implements View.OnClickListener {
    String counter_id, visit_date, username;
    private SharedPreferences preferences;
    ArrayList<InvoiceGetterSetter> invoice_List = new ArrayList<>();
    InvoiceGetterSetter totalsales = new InvoiceGetterSetter();
    ImageView btn_saletra_add_performa;
    TextView count_cst, total_sales, discount_value;
    Lorealba_Database db;
    Context context;
    RecyclerView sale_tracking_recycle;
    boolean clicked_flag = false;
    String from = CommonString.TAG_FROM_BA;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consumer_intraction_detail);
        from = getIntent().getStringExtra("from");
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        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);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        setTitle("Consumer Interaction - " + username);
    }

    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, "");
        btn_saletra_add_performa = (ImageView) findViewById(R.id.btn_saletra_add_performa);
        sale_tracking_recycle = (RecyclerView) findViewById(R.id.sale_tracking_recycle);
        count_cst = (TextView) findViewById(R.id.count_cst);
        total_sales = (TextView) findViewById(R.id.total_sales);
        discount_value = (TextView) findViewById(R.id.discount_value);
        btn_saletra_add_performa.setOnClickListener(this);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        db = new Lorealba_Database(context);
        db.open();
        invoice_List = db.getsalestrackingListusing_group(counter_id, visit_date, null,from);
        if (!invoice_List.isEmpty()) {
            sale_tracking_recycle.setAdapter(new ValueAdapter(context, invoice_List));
            sale_tracking_recycle.setLayoutManager(new LinearLayoutManager(context));
        }
        db.open();
        totalsales = db.getcst_countandtotal_sale_value(visit_date, counter_id, null,from);
        db.open();
        ArrayList<InvoiceGetterSetter> totaldiscount = db.getcst_totaldiscount(visit_date, counter_id, null,from);

        if (totalsales.getCst_count() != null && !totalsales.getCst_count().equals("0")) {
            count_cst.setText(totalsales.getCst_count());
            total_sales.setText(totalsales.getTotal_amount());
            if (!totaldiscount.isEmpty()) {
                int total_discount = 0;
                for (int k = 0; k < totaldiscount.size(); k++) {
                    total_discount = total_discount + totaldiscount.get(k).getAplyieddiscountedprice();
                }
                discount_value.setText(String.valueOf(total_discount));
            } else {
                discount_value.setText("0.0");
            }
        } else {
            count_cst.setText("0");
            total_sales.setText("0.0");
            discount_value.setText("0.0");
        }
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_saletra_add_performa) {
            startActivity(new Intent(context, ConsumerUserDetailsActivity.class).putExtra(CommonString.TAG_MODE, "1").putExtra("from",from));
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }
    }

    @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) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                        (dialog, id1) -> {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            ConsumerIntractionDetailActivity.this.finish();
                        }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ConsumerIntractionDetailActivity.this.finish();
            }
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (clicked_flag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok",
                    (dialog, id) -> {
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        ConsumerIntractionDetailActivity.this.finish();
                    }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ConsumerIntractionDetailActivity.this.finish();
        }
    }

    private class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
         LayoutInflater inflator;
        List<InvoiceGetterSetter> data;

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

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

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull final MyViewHolder holder, final int position) {
            final InvoiceGetterSetter current = data.get(position);
            if (current.isPos_sale_flag()) {
                if (!current.getStr_upload_status().isEmpty() && !current.getStr_upload_status().equalsIgnoreCase(CommonString.KEY_N)) {
                    holder.pos_icon.setImageResource(R.mipmap.upload_tick);
                } else {
                    holder.pos_icon.setImageResource(R.mipmap.not_upload);
                }
                holder.pos_icon.setVisibility(View.VISIBLE);
                holder.pos_icon.setId(position);
            } else {
                holder.pos_icon.setVisibility(View.VISIBLE);
                holder.pos_icon.setId(position);
            }

            if (checkdemovalidation(current) && current.getProduct_sold_str().equalsIgnoreCase("No")) {
                holder.demo_icon.setVisibility(View.VISIBLE);
                holder.demo_icon.setId(position);
                holder.sale_icon.setVisibility(View.INVISIBLE);
                holder.sale_icon.setId(position);
            } else if (!checkdemovalidation(current) && current.getProduct_sold_str().equalsIgnoreCase("Yes")) {
                holder.demo_icon.setVisibility(View.INVISIBLE);
                holder.demo_icon.setId(position);
                holder.sale_icon.setVisibility(View.VISIBLE);
                holder.sale_icon.setId(position);
            } else if (checkdemovalidation(current) && current.getProduct_sold_str().equalsIgnoreCase("Yes")) {
                holder.demo_icon.setVisibility(View.VISIBLE);
                holder.demo_icon.setId(position);
                holder.sale_icon.setVisibility(View.VISIBLE);
                holder.sale_icon.setId(position);
            } else {
                holder.demo_icon.setVisibility(View.INVISIBLE);
                holder.demo_icon.setId(position);
                holder.sale_icon.setVisibility(View.INVISIBLE);
                holder.sale_icon.setId(position);
            }

            holder.sale_trcking_name.setText(current.getCustomer_name() + "  - Mobile No. :  " + current.getMobile_no());
            holder.sale_trcking_name.setId(position);

            holder.sales_count.setText("Count :  " + current.getQuantity());
            holder.sales_count.setId(position);

            holder.sale_total_amount.setText("Total Amount :  " + current.getTotal_amount());
            holder.sale_total_amount.setId(position);

            holder.discountedRs.setText("Discounted Rs :  " + current.getAplyieddiscountedprice());
            holder.discountedRs.setId(position);

            holder.sale_card.setOnClickListener(v -> {
                if (!current.isPos_sale_flag()) {
                    db.open();
                    startActivity(new Intent(context, ConsumerUserDetailsActivity.class)
                            .putExtra(CommonString.TAG_OBJECT,
                                    db.getsalesTrackingByUserMobile(current.getReccept_count(), current.getMobile_no(),
                                            visit_date, counter_id, current.getUserName()))
                            .putExtra(CommonString.Key_For_Pos_Enable_With_Showing_Invoice, "1")
                            .putExtra(CommonString.Key_For_Consumer_Update, "1").putExtra("from",from));

                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                } else {
                    db.open();
                    if (current.getProduct_sold_str().equalsIgnoreCase("Yes")) {
                        startActivity(new Intent(context, InvoiceReportProformaActivity.class)
                                .putExtra(CommonString.TAG_OBJECT, db.getsalesTrackingByUserMobile(current.getReccept_count(),
                                        current.getMobile_no(), visit_date, counter_id, current.getUserName()))
                                .putExtra(CommonString.Key_For_Disable_POS_And_Save, "1")
                                .putExtra(CommonString.Key_For_Consumer_Update, "1").putExtra("from",from));

                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                    } else {
                        AlertandMessages.showToastMsg(context, "Sales Not Found");
                    }
                }
            });
        }

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

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView sale_trcking_name, sales_count, sale_total_amount, discountedRs;
            CardView sale_card;
            ImageView pos_icon, demo_icon, sale_icon;

            public MyViewHolder(View itemView) {
                super(itemView);
                sale_card = (CardView) itemView.findViewById(R.id.sale_card);
                sale_trcking_name = (TextView) itemView.findViewById(R.id.sale_trcking_name);
                sales_count = (TextView) itemView.findViewById(R.id.sales_count);
                sale_total_amount = (TextView) itemView.findViewById(R.id.sale_total_amount);
                discountedRs = (TextView) itemView.findViewById(R.id.discountedRs);
                pos_icon = (ImageView) itemView.findViewById(R.id.pos_icon);
                sale_icon = (ImageView) itemView.findViewById(R.id.sale_icon);
                demo_icon = (ImageView) itemView.findViewById(R.id.demo_icon);
            }
        }
    }

    private boolean checkdemovalidation(InvoiceGetterSetter current) {
        return current.getDemo_given_str().equalsIgnoreCase("Yes") || current.getSkin_genius_str().equalsIgnoreCase("Yes") || current.getMaybelline_vto_str().equalsIgnoreCase("Yes");
    }

}
