package com.yono.messeripos;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.service.controls.actions.ModeAction;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ethanhua.skeleton.RecyclerViewSkeletonScreen;
import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.yono.messeripos.adapter.CategoryAdapter;
import com.yono.messeripos.adapter.ProductAdapter;
import com.yono.messeripos.api.client.Client;
import com.yono.messeripos.api.service.CategoryServise;
import com.yono.messeripos.api.service.ProductService;
import com.yono.messeripos.databinding.ActivityMainBinding;
import com.yono.messeripos.models.CategoryModels;
import com.yono.messeripos.models.MainViewModels;
import com.yono.messeripos.models.MainViewModelsCart;
import com.yono.messeripos.models.ProductCartModels;
import com.yono.messeripos.models.ProductModels;
import com.yono.messeripos.response.DataResponse;
import com.yono.messeripos.utils.Utils;

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

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {
    MaterialToolbar toolbar;
    MainViewModels mainViewModels;
    ActivityMainBinding binding;
    CategoryAdapter categoryAdapter;
    ProductAdapter productAdapter;
    Utils utils = new Utils();
    SharedPreferences sharedPreferences, sharedPreferencesLogin;
    public static Boolean status_update = false;
    MainViewModelsCart mainViewModelsCart;
    public static Boolean cartIsEmpty;
    public static final String CHECKOUT = "checkout";
    public static Boolean checkout;
    public static Boolean selectCategory = false;
    public static String orderId;
    public static final String ORDER_ID = "orderId";
    Client client = new Client();
    public static ArrayList<ProductModels> productModelsArrayList = new ArrayList<>();
    public static ArrayList<CategoryModels> categoryModelsArrayList = new ArrayList<>();
    public static final String DATA_PRODUCT = "DATA_PRODUCT";
    public static final String MY_SHARED_PREFERENCES = "main_sahred";
    ProgressDialog progressDialog;
    MaterialButton btnAddCart;
    SkeletonScreen skeletonCategory;
    FormCategory formCategory;



    @SuppressLint("LongLogTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);


        ProductAdapter adapter = new ProductAdapter();
        binding.rvProduct.setAdapter(adapter);
        showLoading(true);

        btnAddCart = findViewById(R.id.materialBtnAddCart);
        binding.tvProduct.setVisibility(View.GONE);

        formCategory = new FormCategory();
        categoryAdapter = new CategoryAdapter();
        productAdapter = new ProductAdapter();
        mainViewModelsCart = new ViewModelProvider(MainActivity.this).get(MainViewModelsCart.class);
        sharedPreferences = getSharedPreferences(MY_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        sharedPreferencesLogin = getSharedPreferences(SplashScreen.MY_SHARED_PREFERENCES, Context.MODE_PRIVATE);
        checkout = sharedPreferences.getBoolean(CHECKOUT,false);
        orderId = sharedPreferences.getString(ORDER_ID,"");
        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Loading...");
        Log.i("ORDER ID", "onCreate: "+sharedPreferences.getString(ORDER_ID,"").toString());
        toolbar = findViewById(R.id.topAppBar);
        mainViewModels = ViewModelProviders.of(this).get(MainViewModels.class);

        if (sharedPreferences.getString(ORDER_ID,"").isEmpty())
        {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString(ORDER_ID,"MES-ORDER"+utils.timeStamp());
            if (editor.commit()){
                Log.i("ORDER ID", "onCreate: "+sharedPreferences.getString(ORDER_ID,"").toString());
//                Toast.makeText(MainActivity.this, sharedPreferences.getString(ORDER_ID,"").toString(), Toast.LENGTH_LONG).show();
            }
        }


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window w = getWindow();
            w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }

        functionSearch();
        toolbarSetOnItemClicked();
        mainViewModelsGettCategory();
        imageEmptyGetProducts();
        mainViewModelsGetProduct();
        productAdapterListener();
        categoryAdapterListener();
        formCategoryListener();
    }

    private void toolbarSetOnItemClicked() {
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int id = item.getItemId();
                if (id == R.id.menu_cart) {
                    if (checkout){
                        startActivity(new Intent(getApplicationContext(), MethodePayment.class));
                    }else{
                        startActivity(new Intent(getApplicationContext(), CartActivity.class));
                    }
                }else if (id == R.id.update){
                    status_update = true;
                    MaterialToolbar toolbars = findViewById(R.id.topAppBar);
                    setSupportActionBar(toolbars);
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    getSupportActionBar().setDisplayShowHomeEnabled(true);
                    getSupportActionBar().setTitle("Update Product");
                    toolbars.setNavigationOnClickListener(view -> updateFinish());

                    productAdapter.notifyDataSetChanged();
                    categoryAdapter.notifyDataSetChanged();
                }else if (id == R.id.create) {
                    startActivity(new Intent(getApplicationContext(), FormProductActivity.class));
                }else if (id == R.id.allTransaction){
                    startActivity(new Intent(getApplicationContext(), TransactionActivity.class));
                }else if (id == R.id.logout){
                    progressDialog.show();
                    SharedPreferences.Editor editor = sharedPreferencesLogin.edit();
                    editor.putBoolean(SplashScreen.SESSION, false);
                    if(editor.commit()){
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                                finish();
                            }
                        }, 700);
                    }
                }
                return true;
            }
        });
    }

    private void mainViewModelsGettCategory() {
        mainViewModels.getCategory().observe(this, new Observer<DataResponse<List<CategoryModels>>>() {
            @Override
            public void onChanged(DataResponse<List<CategoryModels>> listDataResponse) {
                if (listDataResponse != null) {
                    CategoryModels caModels = new CategoryModels();
                    caModels.setNameCategory("All");
                    caModels.setIdCategory(0);

                    List<CategoryModels> categoryModels = listDataResponse.getData();
                    categoryModelsArrayList = new ArrayList<>();

                    categoryModels.add(0,caModels);
                    categoryModelsArrayList.addAll(categoryModels);
                    binding.tvProduct.setVisibility(View.VISIBLE);
                    categoryAdapter.setCategoriAdapter(MainActivity.this, categoryModelsArrayList);
                    binding.rvCategory.setLayoutManager(new LinearLayoutManager(
                            MainActivity.this,
                            RecyclerView.HORIZONTAL,
                            false
                    ));
                    binding.rvCategory.setAdapter(categoryAdapter);

                }

                String js = new Gson().toJson(listDataResponse);
                Log.d("Get data from category", "Response " + js);
            }
        });
    }

    private void imageEmptyGetProducts() {
        binding.imgEmpty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLoading(true);
                mainViewModels.getProduct().observe(MainActivity.this, new Observer<DataResponse<List<ProductModels<CategoryModels>>>>() {
                    @Override
                    public void onChanged(DataResponse<List<ProductModels<CategoryModels>>> listDataResponse) {
                        if (listDataResponse != null) {
                            List<ProductModels<CategoryModels>> productModels = listDataResponse.getData();
                            ArrayList<ProductModels> productModelsArrayList = new ArrayList<>();

                            productModelsArrayList.addAll(productModels);
                            showLoading(false);
                            if (productModelsArrayList == null){
                                binding.rvProduct.setVisibility(View.GONE);
                                binding.imgEmpty.setVisibility(View.VISIBLE);
                                showLoading(false);
                            }else{
                                productAdapter.setProduct(MainActivity.this,productModelsArrayList );
                                binding.rvProduct.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
                                binding.rvProduct.setAdapter(productAdapter);
                                productAdapter.notifyDataSetChanged();
                                showLoading(false);
                            }

                        }

                        String js = new Gson().toJson(listDataResponse);
                        Log.d("Get data from products", "Response " + js);
                    }
                });
            }
        });
    }

    private void mainViewModelsGetProduct() {
        mainViewModels.getProduct().observe(this, new Observer<DataResponse<List<ProductModels<CategoryModels>>>>() {
            @Override
            public void onChanged(DataResponse<List<ProductModels<CategoryModels>>> listDataResponse) {
                if (listDataResponse.getData().size() != 0) {
                    List<ProductModels<CategoryModels>> productModels = listDataResponse.getData();
                    productModelsArrayList.clear();
                    productModelsArrayList.addAll(productModels);
                    showLoading(false);
                    if (productModelsArrayList.isEmpty()){
                        binding.rvProduct.setVisibility(View.GONE);
                        binding.imgEmpty.setVisibility(View.VISIBLE);
                        binding.imgEmpty.bringToFront();
                    }else{
                        productAdapter.setProduct(MainActivity.this,productModelsArrayList );
                        binding.rvProduct.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
                        binding.rvProduct.setAdapter(productAdapter);
                    }

                } else {
                    showLoading(false);
                    binding.imgEmpty.setVisibility(View.VISIBLE);
                    binding.imgEmpty.bringToFront();
                }
            }
        });
    }

    private void productAdapterListener() {
        productAdapter.setListener(new ProductAdapter.ProductListener() {
            @Override
            public void onUpdate(ProductModels product) {
                startActivity(new Intent(MainActivity.this,
                        FormProductActivity.class).putExtra(DATA_PRODUCT, product));
            }

            @Override
            public void onDelete(ProductModels product, int position) {
                progressDialog.show();
                ProductService productService = client.Client(ProductService.class);
                productService.deleteProducts(product.getIdProduct()).enqueue(new Callback<DataResponse<ProductModels>>() {
                    @Override
                    public void onResponse(Call<DataResponse<ProductModels>> call, Response<DataResponse<ProductModels>> response) {
                        progressDialog.dismiss();
                        productModelsArrayList.remove(position);
                        binding.rvProduct.removeViewAt(position);
                        productAdapter.notifyItemRemoved(position);
                        productAdapter.notifyItemRangeChanged(position, productModelsArrayList.size());
                    }

                    @Override
                    public void onFailure(Call<DataResponse<ProductModels>> call, Throwable t) {

                    }
                });
            }

            @Override
            public void onAddCart(ProductModels product) {
                mainViewModelsCart.checkOrderProduct(product.getIdProduct(), sharedPreferences.getString(ORDER_ID,"")).observe(MainActivity.this, new Observer<List<ProductCartModels>>() {
                    @RequiresApi(api = Build.VERSION_CODES.N)
                    @Override
                    public void onChanged(List<ProductCartModels> productCartModels) {
                        if (productCartModels.isEmpty() && cartIsEmpty){
                            mainViewModelsCart.insertCart(new ProductCartModels(
                                    sharedPreferences.getString(ORDER_ID,""),
                                    1,
                                    product.getIdProduct(),
                                    product.getProductName(),
                                    product.getPriceProduct(),
                                    product.getStockProduct()
                            ));

//                            Log.d("order_id_create", "onChanged: "+orderId);

                            cartIsEmpty = false;
//                            Log.i("Add data cart", "onChanged: Berhasil ditambahkan");
                        }else {
                            if (cartIsEmpty){
                                startActivity(new Intent(MainActivity.this, CartActivity.class));
                                cartIsEmpty = false;
                            }
                            cartIsEmpty = false;
                        }
                    }
                });
            }

            @Override
            public void redirect() {
                startActivity(new Intent(MainActivity.this, CartActivity.class));
            }
        });
    }

    private void formCategoryListener() {
        formCategory.setListener(new FormCategory.FormCategoryListener() {
            @Override
            public void onAddCategory(CategoryModels categoryModels) {

            }

            @Override
            public void onUpdateCategory(CategoryModels categoryModels) {
                progressDialog.show();
                CategoryServise categoryServise = client.Client(CategoryServise.class);
                categoryServise.updateCategory(categoryModels.getIdCategory(), categoryModels).enqueue(new Callback<DataResponse<CategoryModels>>() {
                    @Override
                    public void onResponse(Call<DataResponse<CategoryModels>> call, Response<DataResponse<CategoryModels>> response) {
                        progressDialog.dismiss();
                        Log.i("Update", "onResponse: "+utils.convertGson(response.body()));
                        if (response.body() != null && response.body().getMessageData() != "Parameter not found!"){
                            categoryAdapter.notifyDataSetChanged();
                            formCategory.dismiss();
                        }else{
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("Update Category failed!")
                                    .setMessage(response.body().getMessageData()).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<DataResponse<CategoryModels>> call, Throwable t) {
                        new AlertDialog.Builder(MainActivity.this)
                                .setTitle("Update Category failed!")
                                .setMessage("Update category failed, try again!").show();
                    }
                });
            }
        });
    }

    private void categoryAdapterListener() {
        categoryAdapter.setListener(new CategoryAdapter.CategoryListener() {
            @Override
            public void onGetProduct(CategoryModels categoryModels) {
                Log.i("diluar if", "onGetProduct: "+selectCategory);
                if (!selectCategory){
                    binding.rvProduct.setVisibility(View.GONE);
                    Log.i("if", "onGetProduct: "+selectCategory);
                }
                selectCategory = true;
                Log.i("setelah if", "onGetProduct: "+selectCategory);

                if (categoryModels.getIdCategory() == 0){
                    progressDialog.show();
                    if (mainViewModels.getProduct().getValue().getData().size() != 0){
                        selectCategory = false;
                        mainViewModels.getProduct().observe(MainActivity.this, new Observer<DataResponse<List<ProductModels<CategoryModels>>>>() {
                            @Override
                            public void onChanged(DataResponse<List<ProductModels<CategoryModels>>> listDataResponse) {

                                progressDialog.dismiss();
                                productModelsArrayList.clear();
                                productModelsArrayList.addAll(listDataResponse.getData());
                                binding.rvProduct.setVisibility(View.VISIBLE);
                                binding.imgEmpty.setVisibility(View.GONE);
                                productAdapter.setProduct(MainActivity.this, productModelsArrayList);
                                binding.rvProduct.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
                                binding.rvProduct.setAdapter(productAdapter);
                            }
                        });
                    }else{
                        selectCategory = false;
                        binding.rvProduct.setVisibility(View.GONE);
                        binding.imgEmpty.setVisibility(View.VISIBLE);
//                        binding.imgEmpty.bringToFront();
                    }
                }else{
                    progressDialog.show();
                    selectCategory = false;
                    mainViewModels.getProductByCategory(categoryModels.getIdCategory()).observe(MainActivity.this, new Observer<DataResponse<List<ProductModels>>>() {
                        @Override
                        public void onChanged(DataResponse<List<ProductModels>> listDataResponse) {

                            progressDialog.dismiss();
                            if (listDataResponse != null) {
                                productModelsArrayList.clear();
                                productModelsArrayList.addAll(listDataResponse.getData());
                                showLoading(false);
                                if (productModelsArrayList.isEmpty()) {
                                    binding.rvProduct.setVisibility(View.GONE);
                                    binding.imgEmpty.setVisibility(View.VISIBLE);
//                                    binding.imgEmpty.bringToFront();
                                } else {
                                    binding.rvProduct.setVisibility(View.VISIBLE);
                                    binding.imgEmpty.setVisibility(View.GONE);
                                    productAdapter.setProduct(MainActivity.this, productModelsArrayList);
                                    binding.rvProduct.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
                                    binding.rvProduct.setAdapter(productAdapter);
//                                    productAdapter.notifyDataSetChanged();
                                }
                            }
                        }
                    });
                }
            }

            @Override
            public void onUpdateCategory(CategoryModels categoryModels) {
                formCategory.EditFormCategory(categoryModels);
                formCategory.show(getSupportFragmentManager(),
                        "ModalFormCategory");
            }

            @Override
            public void onDeleteCategory(CategoryModels categoryModels, int position) {
                progressDialog.show();
                CategoryServise categoryServise = client.Client(CategoryServise.class);
                categoryServise.deleteCategory(categoryModels.getIdCategory()).enqueue(new Callback<DataResponse<CategoryModels>>() {
                    @Override
                    public void onResponse(Call<DataResponse<CategoryModels>> call, Response<DataResponse<CategoryModels>> response) {
                        progressDialog.dismiss();
                        categoryModelsArrayList.remove(position);
                        Log.i("KAAAA", "onResponse: "+utils.convertGson(categoryModelsArrayList));
//                        binding.rvCategory.removeViewAt(position);
                        categoryAdapter.notifyItemRemoved(position);
                        categoryAdapter.notifyItemRangeChanged(position, categoryModelsArrayList.size());
                    }

                    @Override
                    public void onFailure(Call<DataResponse<CategoryModels>> call, Throwable t) {

                    }
                });
            }
        });
    }

    private void functionSearch() {
        binding.etSearchProduct.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                productAdapter.getFilter().filter(charSequence);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    private void updateFinish() {
        status_update = false;
        binding.topAppBar.setVisibility(View.VISIBLE);
        binding.rvCategory.setVisibility(View.VISIBLE);
//        binding.appBarUpdate.setVisibility(View.GONE);
        productAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.update, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.menu_update){
            status_update = false;
            startActivity(new Intent(MainActivity.this, MainActivity.class));
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("ResourceAsColor")
    public void showLoading(boolean isLoading) {
        if (isLoading) {
            binding.pbLoading.setVisibility(View.VISIBLE);
        } else {
            binding.pbLoading.setVisibility(View.GONE);
        }
    }
}