package com.cpm.lorealbaMabeline.dailyactivity;

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 android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.download.Downloader;
import com.cpm.lorealbaMabeline.gsonGetterSetter.MasterRetailExcellence;

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

public class RetailExcellenceActivity extends AppCompatActivity implements View.OnClickListener {
    String error_msg = "", visit_date, username, counter_Id;
    HashMap<MasterRetailExcellence, ArrayList<MasterRetailExcellence>> listDataChild;
    ArrayList<MasterRetailExcellence> masterRetailExcellenceArrayList;
    List<Integer> checkHeaderArray = new ArrayList<>();
    List<Integer> checkGroupArray = new ArrayList<>();
    ArrayList<MasterRetailExcellence> listDataHeader;
    String[] retailSpinner = {"Select", "Yes", "No"};
    boolean checkflag = true, Singletouch = false, update_flag = false;
    SharedPreferences preferences;
    ExpandableListView expandableListView;
    ExpandableListAdapter adapter;
    FloatingActionButton fab;
    MasterRetailExcellence obj = null;
    Lorealba_Database db;
    Toolbar toolbar;
    Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retail_excellence);
        context = this;
        db = new Lorealba_Database(context);
        db.open();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       preferences = PrefHelper.getPrefs(context);
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        counter_Id = preferences.getString(CommonString.KEY_COUNTER_ID, "");

        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        setTitle("Retail Excellence" + " - " + username);

        expandableListView = (ExpandableListView) findViewById(R.id.list);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);
        validate_ui_data();
    }

    private void validate_ui_data() {
        db.open();
        listDataHeader = db.getRetailExcellenceData();
        masterRetailExcellenceArrayList = new ArrayList<>();
        listDataChild = new HashMap<>();
        for (int i = 0; i < listDataHeader.size(); i++) {
            db.open();
            masterRetailExcellenceArrayList = db.getRetailExcellencedata(listDataHeader.get(i).getItemCatId().toString(), username, visit_date, counter_Id);
            if (masterRetailExcellenceArrayList.size() == 0) {
                db.open();
                masterRetailExcellenceArrayList = db.getRetailCategoryWiseDataNew(listDataHeader.get(i).getItemCatId());
            } else {
                update_flag = true;
            }
            ArrayList<MasterRetailExcellence> list = new ArrayList<>();
            if (masterRetailExcellenceArrayList.size() > 0) {
                // Adding child data
                list.addAll(masterRetailExcellenceArrayList);
            }

            listDataChild.put(listDataHeader.get(i), list);
        }
        adapter = new ExpandableListAdapter(context, listDataHeader, listDataChild);
        expandableListView.setAdapter(adapter);

        for (int i = 0; i < adapter.getGroupCount(); i++) {
            expandableListView.expandGroup(i);
        }

        expandableListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                expandableListView.invalidate();
            }

            @Override
            public void onScrollStateChanged(AbsListView arg0, int arg1) {
                InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (getCurrentFocus() != null) {
                    inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
                    getCurrentFocus().clearFocus();
                }
                expandableListView.invalidateViews();
            }
        });

    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.fab) {
            expandableListView.clearFocus();
            if (validateData(listDataHeader, listDataChild)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.dialog_title).setMessage(R.string.title_activity_Want_save)
                        .setCancelable(false).setPositiveButton(R.string.yes, (dialog, id) -> {
                            db.open();
                            db.insertRetailExcellence_data(counter_Id, visit_date, username, listDataHeader, listDataChild, obj, CommonFunctions.getUUID(context));
                            //download service
                            Intent intent = new Intent(context, Downloader.class);
                            intent.putExtra(CommonString.KEY_RETAIL_EXCELLENCE, listDataHeader);
                            Downloader.enqueueWork(context, intent);
                            AlertandMessages.showToastMsg(context, "Data Uploaded Successfully");
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            RetailExcellenceActivity.this.finish();
                            dialog.dismiss();
                        }).setNegativeButton(R.string.no, (dialog, id) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                AlertandMessages.showToastMsg(context, error_msg);
            }
        }

    }

    private boolean validateData(ArrayList<MasterRetailExcellence> listDataHeader, HashMap<MasterRetailExcellence, ArrayList<MasterRetailExcellence>> listDataChild) {
        checkHeaderArray.clear();
        checkGroupArray.clear();
        checkflag = true;
        for (int j = 0; j < listDataHeader.size(); j++) {
            ArrayList<MasterRetailExcellence> data = listDataChild.get(listDataHeader.get(j));
            for (int i = 0; i < Objects.requireNonNull(data).size(); i++) {
                if (data.get(i).getAnswer().equalsIgnoreCase("Select") || data.get(i).getAnswer().equals("")) {
                    error_msg = "Please Select Yes or No";
                    checkflag = false;
                    break;
                }
            }

        }
        return checkflag;
    }

    public class ExpandableListAdapter extends BaseExpandableListAdapter {
        Context _context;
        ArrayList<MasterRetailExcellence> listDataHeader; // header titles
        HashMap<MasterRetailExcellence, ArrayList<MasterRetailExcellence>> listDataChild;

        public ExpandableListAdapter(Context context, ArrayList<MasterRetailExcellence> listDataHeader, HashMap<MasterRetailExcellence, ArrayList<MasterRetailExcellence>> listDataChild) {
            this._context = context;
            this.listDataHeader = listDataHeader;
            this.listDataChild = listDataChild;
        }

        @Override
        public Object getChild(int groupPosition, int childPosititon) {
            return this.listDataChild.get(this.listDataHeader.get(groupPosition)).get(childPosititon);
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @SuppressLint({"NewApi", "ClickableViewAccessibility"})
        @Override
        public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            final MasterRetailExcellence checkList = (MasterRetailExcellence) getChild(groupPosition, childPosition);
            ExpandableListAdapter.ViewHolder holder = null;
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.retail_excellence_child_item, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ExpandableListAdapter.ViewHolder) convertView.getTag();
            }

            holder.data = checkList;
            holder.txt_question.setText(holder.data.getItemName());
            holder.txt_question.setId(childPosition);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(context,
                    R.layout.spinner_text_view, R.id.txt_sp_text, retailSpinner);
            holder.sp_auditAnswer.setAdapter(adapter);

            holder.sp_auditAnswer.setOnTouchListener((view, motionEvent) -> {
                Singletouch = true;
                return false;
            });

            final ExpandableListAdapter.ViewHolder finalHolder = holder;
            holder.sp_auditAnswer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (position != 0) {
                        finalHolder.data.setAnswer(retailSpinner[position]);
                    } else {
                        finalHolder.data.setAnswer("");
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            for (int i = 0; i < retailSpinner.length; i++) {
                if (holder.data.getAnswer().equalsIgnoreCase(retailSpinner[i])) {
                    holder.sp_auditAnswer.setSelection(i);
                }
            }

            if (!checkflag) {
                if (checkGroupArray.contains(groupPosition) && checkHeaderArray.contains(childPosition)) {
                    holder.card_view.setBackgroundColor(getResources().getColor(R.color.red));
                    holder.card_view.setId(childPosition);
                } else {
                    holder.card_view.setBackgroundColor(getResources().getColor(R.color.white));
                    holder.card_view.setId(childPosition);
                }
            } else {
                holder.card_view.setBackgroundColor(getResources().getColor(R.color.white));
                holder.card_view.setId(childPosition);
            }

            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return this.listDataChild.get(this.listDataHeader.get(groupPosition)).size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return this.listDataHeader.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return this.listDataHeader.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater infalInflater = (LayoutInflater) this._context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = infalInflater.inflate(R.layout.item_header_retail_excellence, parent, false);
            }

            final MasterRetailExcellence headerTitle = (MasterRetailExcellence) getGroup(groupPosition);
            TextView lblListHeader = (TextView) convertView.findViewById(R.id.txt_header);
            CardView cardView = (CardView) convertView.findViewById(R.id.cardview_exists);
            lblListHeader.setText(headerTitle.getItemCatName());

            cardView.setOnClickListener(v -> {
                if (expandableListView.isGroupExpanded(groupPosition)) {
                    expandableListView.collapseGroup(groupPosition);
                } else {
                    expandableListView.expandGroup(groupPosition);
                }
            });

            if (!checkflag) {
                if (checkGroupArray.contains(groupPosition)) {
                    cardView.setBackgroundColor(getResources().getColor(R.color.red));
                } else {
                    cardView.setBackgroundColor(getResources().getColor(R.color.bright_red));
                }
            } else {
                cardView.setBackgroundColor(getResources().getColor(R.color.bright_red));
            }

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public final View mView;
            public final TextView txt_question;
            public final Spinner sp_auditAnswer;
            CardView card_view;
            MasterRetailExcellence data;

            public ViewHolder(View view) {
                super(view);
                mView = view;
                txt_question = (TextView) view.findViewById(R.id.txt_question);
                sp_auditAnswer = (Spinner) view.findViewById(R.id.sp_auditAnswer);
                card_view = (CardView) view.findViewById(R.id.card_view);
            }
        }
    }

    @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) {
            if (checkflag) {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                RetailExcellenceActivity.this.finish();
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                        .setPositiveButton(getString(R.string.ok), (dialog, id1) -> {
                            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                            RetailExcellenceActivity.this.finish();
                        }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
                AlertDialog alert = builder.create();
                alert.show();
            }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (checkflag) {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            RetailExcellenceActivity.this.finish();
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(getResources().getString(R.string.data_will_be_lost)).setCancelable(false)
                    .setPositiveButton(getString(R.string.ok), (dialog, id) -> {
                        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                        RetailExcellenceActivity.this.finish();
                    }).setNegativeButton(getString(R.string.cancel), (dialog, which) -> dialog.dismiss());
            AlertDialog alert = builder.create();
            alert.show();
        }
    }
}