package com.cpm.lorealbaMabeline.dailyactivity;

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

import androidx.annotation.NonNull;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

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.LinearLayout;
import android.widget.TextView;

import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.CommonFunctions;
import com.cpm.lorealbaMabeline.constant.CommonString;
import com.cpm.lorealbaMabeline.delegates.PrefHelper;
import com.cpm.lorealbaMabeline.gsonGetterSetter.TCounterInvoice;

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

public class InWardStockActivity extends AppCompatActivity implements View.OnClickListener {
    Lorealba_Database db;
    Context context;
    SharedPreferences preferences;
    String counter_id, visit_date, username;
    ArrayList<TCounterInvoice> counterInvoiceList = new ArrayList<>();
    RecyclerView invoiceListView;
    ValueAdapter adapter;
    FloatingActionButton addBtn;
    public ArrayList<TCounterInvoice> manualInwardStockList = new ArrayList<>();

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_ward_stock);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        validateUIData();
        db.open();
        addBtn.setVisibility(db.getHideManualInwordCount()? View.GONE : View.VISIBLE);
        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 validateUIData() {
       preferences = PrefHelper.getPrefs(context);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        invoiceListView = (RecyclerView) findViewById(R.id.invoice_list);
        addBtn = (FloatingActionButton) findViewById(R.id.add_btn);
        addBtn.setOnClickListener(this::onClick);
        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("InWard Stock - " + visit_date);
        invoiceListView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();
        manualInwardStockList = db.getManualInwardStockData(counter_id, visit_date);
        counterInvoiceList = db.getInwardStockData(counter_id, visit_date);
        if (!counterInvoiceList.isEmpty()) {
            if (!manualInwardStockList.isEmpty()) {
                if (!manualInwardStockList.get(0).getNo_ofLine().equals("0")) {
                    counterInvoiceList.addAll(manualInwardStockList);
                }
            }
            adapter = new ValueAdapter(counterInvoiceList, context);
            invoiceListView.setAdapter(adapter);
            invoiceListView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            adapter = new ValueAdapter(manualInwardStockList, context);
            invoiceListView.setAdapter(adapter);
            invoiceListView.setLayoutManager(new LinearLayoutManager(context));
        }
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.add_btn) {
            Intent intent = new Intent(context, ManualInWardStockActivity.class);
            intent.putExtra(CommonString.KEY_VALUE, "add");
            startActivity(intent);
        }
    }

    private class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.ViewHolder> {
        ArrayList<TCounterInvoice> counterInvoiceList;
        LayoutInflater inflator;
        Context context;

        public ValueAdapter(ArrayList<TCounterInvoice> counterInvoiceList, Context context) {
            this.counterInvoiceList = counterInvoiceList;
            inflator = LayoutInflater.from(context);
            this.context = context;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.invoice_detail_layout, parent, false);
            return new ViewHolder(view);
        }
        @Override
        public void onBindViewHolder(@NonNull final ViewHolder viewHolder, final int pos) {
            TCounterInvoice object = counterInvoiceList.get(pos);
            viewHolder.invoiceNumber.setText(object.getInvoiceNo());
            viewHolder.invoiceNumber.setId(pos);
            viewHolder.invoiceDate.setText(object.getInvoiceDate());
            viewHolder.invoiceDate.setId(pos);
            viewHolder.invoiceType.setText(object.getInvoiceType());
            viewHolder.invoiceType.setId(pos);
            viewHolder.noOfLine.setText(object.getNo_ofLine());
            viewHolder.noOfLine.setId(pos);
            viewHolder.approvedLine.setText(object.getApproved_line());
            viewHolder.approvedLine.setId(pos);
            viewHolder.invoiceAmount.setText(object.getFinalAmount());
            viewHolder.invoiceAmount.setId(pos);
            if (object.getSource().isEmpty()) {
                viewHolder.inwardStockView.setCardBackgroundColor(getResources().getColor(R.color.light_blue));
                viewHolder.inwardStockView.setId(pos);
            } else {
                viewHolder.inwardStockView.setCardBackgroundColor(getResources().getColor(R.color.light_green));
                viewHolder.inwardStockView.setId(pos);
            }

            if (object.getSource().isEmpty() || object.getSource().equalsIgnoreCase("DMS")) {
                viewHolder.layout_background.setBackgroundColor(getResources().getColor(R.color.grey_dark_background));
                viewHolder.layout_background.setId(pos);
            } else {
                viewHolder.layout_background.setBackgroundColor(getResources().getColor(R.color.dark_light_gray));
                viewHolder.layout_background.setId(pos);
            }

            ///for DMS Approved or not
            if (!object.getNo_ofLine().equalsIgnoreCase(object.getApproved_line()) && (object.getSource().equalsIgnoreCase("DMS")
                    || object.getSource().isEmpty())) {
                viewHolder.draftImg.setVisibility(View.VISIBLE);
                viewHolder.draftImg.setBackgroundResource(R.drawable.incomplete_icon);
                viewHolder.draftImg.setId(pos);
            } else {
                viewHolder.draftImg.setVisibility(View.VISIBLE);
                viewHolder.draftImg.setBackgroundResource(R.drawable.complete_icon);
                viewHolder.draftImg.setId(pos);
            }

            ////for Manual Draft and compelete....
            if (object.getInvoiceStatus() && object.getSource().equalsIgnoreCase("Manual")) {
                viewHolder.draftImg.setVisibility(View.VISIBLE);
                viewHolder.draftImg.setBackgroundResource(R.drawable.complete_icon);
                viewHolder.draftImg.setId(pos);
            } else {
                if (counterInvoiceList.get(pos).getSource().equalsIgnoreCase("Manual")) {
                    viewHolder.draftImg.setVisibility(View.VISIBLE);
                    viewHolder.draftImg.setBackgroundResource(R.mipmap.saved_draft);
                    viewHolder.draftImg.setId(pos);
                }
            }

            viewHolder.inwardStockView.setOnClickListener(view -> {
                Intent intent;
                if (object.getSource().isEmpty() || object.getSource().equalsIgnoreCase("DMS")) {
                    intent = new Intent(context, InwardStockDetailsActivity.class);
                    intent.putExtra(CommonString.TAG_OBJECT, object);
                } else {
                    intent = new Intent(context, ManualInWardStockActivity.class);
                    intent.putExtra(CommonString.TAG_OBJECT, object);
                    intent.putExtra(CommonString.KEY_VALUE, "edit");
                }
                startActivity(intent);
            });
        }

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

        public class ViewHolder extends RecyclerView.ViewHolder {
            TextView invoiceNumber, invoiceDate, invoiceType, noOfLine, approvedLine, invoiceAmount;
            LinearLayout layout_background;
            CardView inwardStockView;
            ImageView draftImg;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                invoiceDate = (TextView) itemView.findViewById(R.id.date_txt);
                draftImg = (ImageView) itemView.findViewById(R.id.draft_image);
                noOfLine = (TextView) itemView.findViewById(R.id.no_of_lines_txt);
                invoiceType = (TextView) itemView.findViewById(R.id.invoice_type_txt);
                approvedLine = (TextView) itemView.findViewById(R.id.approved_line_txt);
                invoiceAmount = (TextView) itemView.findViewById(R.id.invoice_amount_txt);
                inwardStockView = (CardView) itemView.findViewById(R.id.inward_stock_view);
                invoiceNumber = (TextView) itemView.findViewById(R.id.invoice_number_txt);
                layout_background = (LinearLayout) itemView.findViewById(R.id.layout_background);
            }
        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @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) {
            finish();
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
        }

        return super.onOptionsItemSelected(item);
    }

}
