package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.cygnusa.hyperm.adapter.RedeemProductListAdapter;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.OrderStatus;
import com.cygnusa.hyperm.wrappers.ProductListDetails;
import com.cygnusa.hyperm.wrappers.RedeemProductDetails;
import com.cygnusa.hyperm.wrappers.RedeemProductDetailsResponse;

import java.util.ArrayList;
import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class RedeemProductDetailsActivity extends AppCompatActivity {
    private RecyclerView redeemList;
    RedeemProductListAdapter adapter;
    TransparentProgressDialog progressDialog;
    ApiService restService;
    private LinearLayoutManager linearLayoutManager;
    private ImageView productImage;
    private TextView productTitle, desc, productPrice, earnedPoints, header;
    RedeemProductDetails productDetailsResponse = new RedeemProductDetails();
    Button btnPurchase;
    public static ProductListDetails productList = new ProductListDetails();
    private LinearLayout priceListView;
    public String[] priceDenominations;
    public ArrayList<String> priceDenominationsFinal = new ArrayList<>();
    public ArrayList<MyViewHolderPrice> PRICE_HOLDER = new ArrayList<>();
    public String strPrice = "0";
    public EditText editPrice;
    public LinearLayout rangeLayout, slabLayout;
    int minAmount = 0, maxAmount = 0, enteredAmount = 0;
    public OrderStatus orderStatus = new OrderStatus();
    String typePrice = "";
    Integer iCurrentAmount = 0;
    private String strTermsnContions;
    AlertDialog.Builder alertDialogBuilder;
    AlertDialog alertDialog;
    private TextView txtTermsnConditions, title;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.redeem_product_details);
        setupUI(findViewById(R.id.bgLayout));

        restService = ((MainApplication) getApplication()).getClient();
        productImage = findViewById(R.id.product_image);
        header = findViewById(R.id.title);
        productTitle = findViewById(R.id.productTitle);
        editPrice = findViewById(R.id.edit_price);
        rangeLayout = findViewById(R.id.range);
        slabLayout = findViewById(R.id.slab);
        productPrice = findViewById(R.id.redeem_price);
        earnedPoints = findViewById(R.id.total_earned_points);
        desc = findViewById(R.id.productDesc);
        btnPurchase = findViewById(R.id.btn_purchase);
        getProductDetails(true);
        iCurrentAmount = Integer.parseInt(MyWallet.strCurrentAmount);
        //  Amount = findViewById(R.id.redeem_price);
        priceListView = (LinearLayout) findViewById(R.id.priceList);
        txtTermsnConditions = (TextView) findViewById(R.id.terms_link);
        SpannableString loginText = new SpannableString("Terms and Conditions");
        loginText.setSpan(new UnderlineSpan(), 0, loginText.length(), 0);
        txtTermsnConditions.setText(loginText);
        txtTermsnConditions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(RedeemProductDetailsActivity.this, TermsandConditions.class);
                i.putExtra("tnc", productDetailsResponse.getTnc_web() + "");
                startActivity(i);
            }
        });
        btnPurchase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!typePrice.equalsIgnoreCase("")) {
                    if (typePrice.equalsIgnoreCase("Range")) {
                        if (editPrice.getText().toString() == null || editPrice.getText().toString().equalsIgnoreCase("")) {
                            GlobalData.showToast(RedeemProductDetailsActivity.this, "Enter amount", Toast.LENGTH_SHORT).show();
                            return;
                        }


                        if (!editPrice.getText().toString().equalsIgnoreCase("")) {
                            enteredAmount = Integer.parseInt(editPrice.getText().toString());
                            if (enteredAmount <= maxAmount && enteredAmount >= minAmount) {

                                if (enteredAmount <= iCurrentAmount) {
                                    productOrder(true, editPrice.getText().toString());
                                } else {
                                    GlobalData.showToast(RedeemProductDetailsActivity.this, "Entered amount should be less than available balance", Toast.LENGTH_SHORT).show();
                                    return;
                                }

                            } else {
                                GlobalData.showToast(RedeemProductDetailsActivity.this, "Enter amount should be in limit", Toast.LENGTH_SHORT).show();
                                return;
                            }


                        }
                    } else {

                        if (strPrice == null || strPrice.equalsIgnoreCase("")) {
                            GlobalData.showToast(RedeemProductDetailsActivity.this, "Select slab amount", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        enteredAmount = Integer.parseInt(strPrice);
                        if (enteredAmount <= maxAmount && enteredAmount >= minAmount) {
                            productOrder(true, strPrice);
                        } else {
                            GlobalData.showToast(RedeemProductDetailsActivity.this, "Entered amount should be in limit", Toast.LENGTH_SHORT).show();
                        }
                    }

                }

            }
        });
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);


    }

    protected void onResume() {
        super.onResume();

        if (GlobalData.canLogout) {
            finish();
        }
    }

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(RedeemProductDetailsActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void productOrder(boolean canLoadProgress, String price) {
        if (new UtilService().isNetworkAvailable(RedeemProductDetailsActivity.this)) {
            if (canLoadProgress) {
                progressDialog = new TransparentProgressDialog(RedeemProductDetailsActivity.this);
                progressDialog.show();
                // progressBar.setVisibility(View.GONE);
            } else {
                // progressBar.setVisibility(View.VISIBLE);
            }

            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("product_id", productDetailsResponse.getId());
                map.put("product_price", price);

                restService.postProductOrder(map).enqueue(new Callback<OrderStatus>() {
                    @Override
                    public void onResponse(Call<OrderStatus> call, Response<OrderStatus> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        //   progressBar.setVisibility(View.GONE);
                        orderStatus = response.body();

                        if (response.body() != null && response.body().getStatus() == 200) {

                            showInstructions(orderStatus.getType() + "");

                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } else if (response.body() != null) {
                            GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            }
                        }

                    }

                    @Override
                    public void onFailure(Call<OrderStatus> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        // progressBar.setVisibility(View.GONE);
                        GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    public void arrayList(String s) {
        priceDenominations = s.split(",");

    }

    public void updateList() {

        priceListView.removeAllViews();
        int indexListSize = priceDenominationsFinal.size();
        if (indexListSize < 1) {
            return;
        }
        for (int i = 0; i < indexListSize; i++) {
            MyViewHolderPrice holder = new MyViewHolderPrice(this, LayoutInflater.from(this).inflate(R.layout.price_text_item, null, false));
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, 0, 0, 15);
            holder.getView().setId(i);
            holder.txtPrice.setText(priceDenominationsFinal.get(i));
            priceListView.addView(holder.getView(), params);
            PRICE_HOLDER.add(holder);
            holder.getView().setOnClickListener(new onDayClick());
            //  strPrice =priceDenominations[0];
        }

    }

    private void showInstructions(String type) {
        View view = LayoutInflater.from(RedeemProductDetailsActivity.this).inflate(
                R.layout.profile_success, null);
        TextView textHead = (TextView) view.findViewById(R.id.textHead);
        ImageView successImage = (ImageView) view.findViewById(R.id.success);
        TextView text1 = (TextView) view.findViewById(R.id.text1);
        TextView text2 = (TextView) view.findViewById(R.id.text2);
        TextView text3 = (TextView) view.findViewById(R.id.text3);
        text3.setVisibility(View.GONE);
        textHead.setVisibility(View.GONE);
        if (type.trim().equalsIgnoreCase("1")) {
            successImage.setImageDrawable(getResources().getDrawable(R.drawable.success));
            text1.setText("Your order has been");
            text2.setText("placed successfully");
        } else {
            successImage.setImageDrawable(getResources().getDrawable(R.drawable.success_orange));

            text1.setText("Your order placed");
            text2.setText("Status will be updated soon!");
        }

        view.findViewById(R.id.btn_ok).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(RedeemProductDetailsActivity.this, RedeemProductListActivity.class));
                        finish();
                    }
                });

        alertDialogBuilder = new AlertDialog.Builder(RedeemProductDetailsActivity.this);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setView(view);
        alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    public class onDayClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            for (int id = 0; id < priceListView.getChildCount(); id++) {
                LinearLayout child = (LinearLayout) priceListView.getChildAt(id);
                TextView txt = (TextView) child.getChildAt(0);
                txt.setTextColor(getResources().getColor(R.color.btn_bg_color));
                txt.setBackgroundResource(R.drawable.border_grey);
            }
            LinearLayout child = (LinearLayout) priceListView.getChildAt(v.getId());
            TextView txt = (TextView) child.getChildAt(0);
            txt.setBackgroundResource(R.drawable.fill_color);
            txt.setTextColor(getResources().getColor(R.color.material_white));
            strPrice = priceDenominationsFinal.get(v.getId());

        }
    }

    public class MyViewHolderPrice {

        TextView txtPrice;
        View convertView;

        MyViewHolderPrice(Context context, View view) {
            convertView = view;
            txtPrice = (TextView) view.findViewById(R.id.price_denominations);
            view.setTag(this);
        }

        public View getView() {
            return convertView;
        }
    }


    private void getProductDetails(boolean canLoadProgress) {
        if (new UtilService().isNetworkAvailable(RedeemProductDetailsActivity.this)) {
            if (canLoadProgress) {
                progressDialog = new TransparentProgressDialog(RedeemProductDetailsActivity.this);
                progressDialog.show();
                // progressBar.setVisibility(View.GONE);
            } else {
                // progressBar.setVisibility(View.VISIBLE);
            }

            restService.getProductDetails(productList.getId()).enqueue(new Callback<RedeemProductDetailsResponse>() {
                @Override
                public void onResponse(Call<RedeemProductDetailsResponse> call, Response<RedeemProductDetailsResponse> response) {

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

                    if (response.body() != null && response.body().getStatus() == 200) {
                        productDetailsResponse = response.body().getData();
                        setProductDetails();

                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    } else if (response.body() != null) {
                        GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        }
                    }


                }

                @Override
                public void onFailure(Call<RedeemProductDetailsResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    // progressBar.setVisibility(View.GONE);

                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("SetTextI18n")
    private void setProductDetails() {

        txtTermsnConditions.setVisibility(View.VISIBLE);
        minAmount = Integer.parseInt(productDetailsResponse.getMin_custom_price());
        maxAmount = Integer.parseInt(productDetailsResponse.getMax_custom_price());
        header.setText(productDetailsResponse.getName());
        if (productDetailsResponse.getPrice_type().equalsIgnoreCase("Range")) {

            slabLayout.setVisibility(View.GONE);
            rangeLayout.setVisibility(View.VISIBLE);
            if (iCurrentAmount < Integer.parseInt(productDetailsResponse.getMax_custom_price())) {
                editPrice.setHint(productDetailsResponse.getMin_custom_price() + " to " + MyWallet.strCurrentAmount);
            } else {
                editPrice.setHint(productDetailsResponse.getMin_custom_price() + " to " + productDetailsResponse.getMax_custom_price());
            }
            priceListView.setVisibility(View.GONE);

        } else if (productDetailsResponse.getPrice_type().equalsIgnoreCase("Slab")) {
            if (productDetailsResponse.getCustom_denominations() != null) {

                arrayList(productDetailsResponse.getCustom_denominations());
                for (int i = 0; i < priceDenominations.length; i++) {
                    int iAmount = Integer.parseInt(priceDenominations[i]);
                    if (iCurrentAmount > iAmount) {
                        priceDenominationsFinal.add(priceDenominations[i]);
                    }
                }
            }
            slabLayout.setVisibility(View.VISIBLE);
            rangeLayout.setVisibility(View.GONE);
            priceListView.setVisibility(View.VISIBLE);
            updateList();
        }

        if (productDetailsResponse.getPrice_type() != null) {
            typePrice = productDetailsResponse.getPrice_type();
        }

        productTitle.setText(productDetailsResponse.getName());
        productPrice.setText(productDetailsResponse.getMin_custom_price() + " to " + productDetailsResponse.getMax_custom_price());
        //  earnedPoints.setText("Available Points:"+"5000");
        desc.setText(productDetailsResponse.getDescription());
        Glide.with(this).load(productDetailsResponse.getImages())
                .thumbnail(Glide.with(this).load(R.drawable.gif_loader))
                .apply(new RequestOptions().fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL)
                        .placeholder(R.drawable.placeholder).error(R.drawable.placeholder)).into(productImage);

    }

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

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            confirmClose();
        }
        return super.onOptionsItemSelected(item);
    }

    private void confirmClose() {
        startActivity(new Intent(RedeemProductDetailsActivity.this, RedeemProductListActivity.class));
        finish();
        RedeemProductDetailsActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }
}
