package com.newloanapp.instantloanapp.loancash.loanguide.loanapp.personalloanapply.loan.star.loanapply.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.applovin.mediation.MaxAd;
import com.applovin.mediation.MaxAdListener;
import com.applovin.mediation.MaxError;
import com.applovin.mediation.ads.MaxAdView;
import com.applovin.mediation.ads.MaxInterstitialAd;
import com.applovin.sdk.AppLovinSdk;
import com.facebook.ads.AudienceNetworkAds;
import com.newloanapp.instantloanapp.loancash.loanguide.loanapp.personalloanapply.loan.star.loanapply.CirclePageIndicator;
import com.newloanapp.instantloanapp.loancash.loanguide.loanapp.personalloanapply.loan.star.loanapply.Constant;
import com.newloanapp.instantloanapp.loancash.loanguide.loanapp.personalloanapply.loan.star.loanapply.R;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

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

public class LoanListActivity extends AppCompatActivity {

    public static MainActivity.Category category;
    public ViewPager viewPager;
    private ProgressBar progress;
    public List<String> thumbList;
    private RecyclerView recyclerView;
    public List<Loan> loanList;
    private CirclePageIndicator pageIndicator;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_loan_list);
        AudienceNetworkAds.initialize(this);
        AppLovinSdk.getInstance( this ).setMediationProvider("max");
        AppLovinSdk.initializeSdk( this, configuration -> {
            MaxAdView maxAdView = new MaxAdView(getString(R.string.banner_id),this);
            ((LinearLayout)findViewById(R.id.adView)).addView(maxAdView);
            maxAdView.loadAd();
        });
        progress = findViewById(R.id.progress);
        viewPager = findViewById(R.id.pager);
        pageIndicator = findViewById(R.id.indicator);
        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        recyclerView.setHasFixedSize(true);
        Volley.newRequestQueue(this).add(new JsonArrayRequest(Constant.LOANLIST_URL + category.getName(), response -> {
            if (response.length() > 0) {
                loanList = new ArrayList<>();
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject jSONObject = response.getJSONObject(i);
                        String id = jSONObject.getString("id");
                        String type = jSONObject.getString("CategoryName");
                        String name = jSONObject.getString("CompanyName");
                        String interest = jSONObject.getString("InterestRate");
                        String terms = jSONObject.getString("TermsOfLoan");
                        String url = jSONObject.getString("URL");
                        String amount = jSONObject.getString("LoanAmount");
                        String image = jSONObject.getString("AppImageURL");
                        String time = jSONObject.getString("TimePeriod");
                        String process = jSONObject.getString("LoanProcessingTime");
                        String address = jSONObject.getString("ProofOfAddress");
                        String identity = jSONObject.getString("ProofOfIdentity");
                        String income = jSONObject.getString("IncomeProof");
                        String bank = jSONObject.getString("BankAccount");
                        String loanterm = jSONObject.getString("LoanTerms");
                        loanList.add(new Loan(id, type, name, interest, terms, url, amount, image, time, process, address, identity, income, bank, loanterm));
                    } catch (JSONException e) {
                        Toast.makeText(LoanListActivity.this,"Error While Fatching Data",Toast.LENGTH_SHORT).show();
                    }
                }
                recyclerView.setAdapter(new LoanAdapter(LoanListActivity.this,loanList));
                progress.setVisibility(View.GONE);
            } else {
                progress.setVisibility(View.GONE);
                Toast.makeText(LoanListActivity.this,"No Loan Company Found",Toast.LENGTH_SHORT).show();
            }
        }, error -> {
            progress.setVisibility(View.GONE);
            Toast.makeText(LoanListActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();
        }));
        Volley.newRequestQueue(this).add(new JsonArrayRequest(Constant.SLIDER_URL, response -> {
            if (response.length() > 0) {
                thumbList = new ArrayList<>();
                for (int i = 0; i < response.length(); i++) {
                    try {
                        JSONObject data = response.getJSONObject(i);
                        thumbList.add(data.getString("thumb"));
                    } catch (JSONException e) {
                        Toast.makeText(LoanListActivity.this,"Error While Fatching Data",Toast.LENGTH_SHORT).show();
                    }
                }
                viewPager.setAdapter(new SlideShowAdapter(LoanListActivity.this,thumbList));
                pageIndicator.setViewPager(viewPager);
                pageIndicator.setRadius(getResources().getDisplayMetrics().density * 5.0f);
                viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {

                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
                progress.setVisibility(View.GONE);
            } else {
                progress.setVisibility(View.GONE);
                Toast.makeText(LoanListActivity.this,"No Slider Found",Toast.LENGTH_SHORT).show();
            }
        }, error -> {
            progress.setVisibility(View.GONE);
            Toast.makeText(LoanListActivity.this,error.getMessage(),Toast.LENGTH_SHORT).show();
        }));
    }

    private static class LoanAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

        private final Context ctx;
        private final List<Loan> itemList;
        private MaxInterstitialAd interstitialAd;

        private LoanAdapter(Context ctx, List<Loan> itemList) {
            this.ctx = ctx;
            this.itemList = itemList;
            loadInterstitiaAd();
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(ctx).inflate(R.layout.item_layout,parent,false);
            return new LoanView(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            LoanView loanView = (LoanView) holder;
            loanView.company.setText(itemList.get(position).getName());
            loanView.amount.setText(itemList.get(position).getAmount());
            loanView.rate.setText("Interest rate " + itemList.get(position).getInterest());
            loanView.apply.setOnClickListener(view -> {
                LoanDetailsActivity.loan = itemList.get(position);
                if(interstitialAd.isReady()) {
                    interstitialAd.showAd();
                } else {
                    ctx.startActivity(new Intent(ctx,LoanDetailsActivity.class));
                }
            });
        }

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

        private static class LoanView extends RecyclerView.ViewHolder{
            private final TextView company;
            private final TextView amount;
            private final TextView rate;
            private final Button apply;
            public LoanView(@NonNull View itemView) {
                super(itemView);
                company = itemView.findViewById(R.id.companyName);
                amount = itemView.findViewById(R.id.loanAmount);
                rate = itemView.findViewById(R.id.interestRate);
                apply = itemView.findViewById(R.id.getDetailsBtn);
            }
        }

        private void loadInterstitiaAd() {
            interstitialAd = new MaxInterstitialAd(ctx.getString(R.string.interstitial_id),(Activity) ctx);
            interstitialAd.setListener(new MaxAdListener() {
                @Override
                public void onAdLoaded(MaxAd ad) {

                }

                @Override
                public void onAdDisplayed(MaxAd ad) {

                }

                @Override
                public void onAdHidden(MaxAd ad) {
                    loadInterstitiaAd();
                    ctx.startActivity(new Intent(ctx,LoanDetailsActivity.class));
                }

                @Override
                public void onAdClicked(MaxAd ad) {

                }

                @Override
                public void onAdLoadFailed(String adUnitId, MaxError error) {
                    loadInterstitiaAd();
                }

                @Override
                public void onAdDisplayFailed(MaxAd ad, MaxError error) {
                    ctx.startActivity(new Intent(ctx,LoanDetailsActivity.class));
                }
            });
            interstitialAd.loadAd();
        }

    }

    private static class SlideShowAdapter extends PagerAdapter {

        private final Context ctx;
        private final List<String> itemList;
        public SlideShowAdapter(Context ctx,List<String> itemList) {
            this.ctx = ctx;
            this.itemList = itemList;
        }

        @Override
        public int getCount() {
            return itemList.size();
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, final int position) {
            View view = LayoutInflater.from(ctx).inflate(R.layout.sliding,container,false);
            ImageView img = view.findViewById(R.id.image);
            Picasso.get().load(itemList.get(position)).fit().into(img);
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, @NonNull Object object) {
            container.removeView((FrameLayout) object);
        }
    }

    public static class Loan {
        private final String id;
        private final String type;
        private final String name;
        private final String interest;
        private final String terms;
        private final String url;
        private final String amount;
        private final String image;
        private final String time;
        private final String process;
        private final String address;
        private final String identity;
        private final String income;
        private final String bank;
        private final String loanterm;

        private Loan(String id, String type, String name, String interest, String terms, String url, String amount, String image, String time, String process, String address, String identity, String income, String bank, String loanterm) {
            this.id = id;
            this.type = type;
            this.name = name;
            this.interest = interest;
            this.terms = terms;
            this.url = url;
            this.amount = amount;
            this.image = image;
            this.time = time;
            this.process = process;
            this.address = address;
            this.identity = identity;
            this.income = income;
            this.bank = bank;
            this.loanterm = loanterm;
        }

        public String getId() {
            return id;
        }

        public String getType() {
            return type;
        }

        public String getName() {
            return name;
        }

        public String getInterest() {
            return interest;
        }

        public String getTerms() {
            return terms;
        }

        public String getUrl() {
            return url;
        }

        public String getAmount() {
            return amount;
        }

        public String getImage() {
            return image;
        }

        public String getTime() {
            return time;
        }

        public String getProcess() {
            return process;
        }

        public String getAddress() {
            return address;
        }

        public String getIdentity() {
            return identity;
        }

        public String getIncome() {
            return income;
        }

        public String getBank() {
            return bank;
        }

        public String getLoanterm() {
            return loanterm;
        }
    }
}
