package com.makeeasy.dailyinterest;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.makeeasy.dailyinterest.Constant.HOST_NAME;
import static com.makeeasy.dailyinterest.MainActivity.interest;
import static com.makeeasy.dailyinterest.MainActivity.principle;
import static com.makeeasy.dailyinterest.MainActivity.total;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioGroup;

import androidx.annotation.Nullable;

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;

import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

public class WithdrawBox extends BottomSheetDialogFragment {
    private ProgressBar pb;
    private String withdraw = "1";
    private final Activity ctx;
    public WithdrawBox(Activity ctx) {
        this.ctx = ctx;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.withdraw,container,false);
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL,R.style.CustomSheet);
        pb = v.findViewById(R.id.load);
        RadioGroup grup = v.findViewById(R.id.grup);
        RadioGroup group = v.findViewById(R.id.group);
        EditText amount = v.findViewById(R.id.nn);
        EditText upiid = v.findViewById(R.id.tt);
        EditText ifsc = v.findViewById(R.id.ifsc);
        EditText holder = v.findViewById(R.id.holder);
        grup.setOnCheckedChangeListener((radioGroup, i) -> {
            int slectedID = radioGroup.getCheckedRadioButtonId();
            if(slectedID == R.id.principle) {
                withdraw = "0";
                v.findViewById(R.id.note).setVisibility(View.GONE);
            } else if(slectedID == R.id.interest) {
                withdraw = "1";
                v.findViewById(R.id.note).setVisibility(View.VISIBLE);
            }
        });
        group.setOnCheckedChangeListener((radioGroup, i) -> {
            int slectedID = radioGroup.getCheckedRadioButtonId();
            if(slectedID == R.id.paytm) {
                upiid.setHint(getString(R.string.paytmno));
                ifsc.setVisibility(View.GONE);
                holder.setVisibility(View.GONE);
                if(!Utils.getString(ctx,"paytminfo").equals("")) {
                    upiid.setText(Utils.getString(ctx,"paytminfo"));
                }
            } else if(slectedID == R.id.upi) {
                upiid.setHint(getString(R.string.upi));
                ifsc.setVisibility(View.GONE);
                holder.setVisibility(View.GONE);
                if(!Utils.getString(ctx,"upiinfo").equals("")) {
                    upiid.setText(Utils.getString(ctx,"upiinfo"));
                }
            } else if(slectedID == R.id.bank) {
                upiid.setHint(getString(R.string.bank));
                ifsc.setVisibility(View.VISIBLE);
                holder.setVisibility(View.VISIBLE);
                if(!Utils.getString(ctx,"bankinfo").equals("")) {
                    upiid.setText(Utils.getString(ctx,"bankinfo"));
                }
            }
        });
        v.findViewById(R.id.btn).setOnClickListener(view -> {
            String amnt = amount.getText().toString();
            String upi = upiid.getText().toString();
            String ifscode = ifsc.getText().toString();
            String hlder = holder.getText().toString();
            BigDecimal with = new BigDecimal(Utils.withdraw);
            BigDecimal depo = new BigDecimal(Utils.deposit);
            if(group.getCheckedRadioButtonId() == R.id.bank) {
                if(amnt.equals("")) {
                    makeText(ctx,"Fill Amount",LENGTH_SHORT).show();
                } else if(Integer.parseInt(amnt) < 10) {
                    makeText(ctx,"Min Amount Rs.10",LENGTH_SHORT).show();
                } else if(withdraw.equals("1") && with.compareTo(new BigDecimal(amnt)) < 0) {
                    makeText(ctx,"You have not enough interest balance",LENGTH_SHORT).show();
                } else if(withdraw.equals("0") && depo.compareTo(new BigDecimal(amnt)) < 0) {
                    makeText(ctx,"You have not enough principle balance",LENGTH_SHORT).show();
                } else if(upi.equals("")) {
                    makeText(ctx,"Fill bank account number",LENGTH_SHORT).show();
                } else if(ifscode.equals("")) {
                    makeText(ctx,"Fill ifsc code",LENGTH_SHORT).show();
                } else if(hlder.equals("")) {
                    makeText(ctx,"Fill account holder name",LENGTH_SHORT).show();
                } else {
                    pb.setVisibility(View.VISIBLE);Utils.saveTag(ctx,"bankinfo",upi);
                    if(withdraw.equals("0")) {
                        String data = "principle," + upi + ", " + ifscode + ", " + hlder;
                        BigDecimal rest = new BigDecimal(Utils.deposit).subtract(new BigDecimal(amnt));
                        addPointOnline(rest.toString(),Utils.withdraw); withdrawRequest(data,amnt);
                    } else if(withdraw.equals("1")) {
                        String data = "interest," + upi + ", " + ifscode + ", " + hlder;
                        BigDecimal rest = new BigDecimal(Utils.withdraw).subtract(new BigDecimal(amnt));
                        addPointOnline(rest.toString(),Utils.withdraw); withdrawRequest(data, amnt);
                    }
                }
            } else {
                if (amnt.equals("")) {
                    makeText(ctx, "Fill Amount", LENGTH_SHORT).show();
                } else if (Integer.parseInt(amnt) < 10) {
                    makeText(ctx, "Min Amount Rs.10", LENGTH_SHORT).show();
                } else if(withdraw.equals("1") && with.compareTo(new BigDecimal(amnt)) < 0) {
                    makeText(ctx,"You have not enough interest balance",LENGTH_SHORT).show();
                } else if(withdraw.equals("0") && depo.compareTo(new BigDecimal(amnt)) < 0) {
                    makeText(ctx,"You have not enough principle balance",LENGTH_SHORT).show();
                } else if (upi.equals("")) {
                    makeText(ctx, "Fill withdraw details", LENGTH_SHORT).show();
                } else {
                    if(group.getCheckedRadioButtonId() == R.id.paytm) {Utils.saveTag(ctx,"paytminfo",upi);}
                    if(group.getCheckedRadioButtonId() == R.id.upi) {Utils.saveTag(ctx,"upiinfo",upi);}
                    pb.setVisibility(View.VISIBLE);
                    if(withdraw.equals("0")) {
                        String data = "principle," + upi + ", " + ifscode + ", " + hlder;
                        BigDecimal rest = new BigDecimal(Utils.deposit).subtract(new BigDecimal(amnt));
                        addPointOnline(rest.toString(),Utils.withdraw); withdrawRequest(data,amnt);
                    } else if(withdraw.equals("1")) {
                        String data = "interest," + upi + ", " + ifscode + ", " + hlder;
                        BigDecimal rest = new BigDecimal(Utils.withdraw).subtract(new BigDecimal(amnt));
                        addPointOnline(rest.toString(),Utils.withdraw); withdrawRequest(data, amnt);
                    }
                }
            }
        });
        setCancelable(true);
        return v;
    }

    private void addPointOnline(String dm,String wm) {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
        String dt = df.format(Calendar.getInstance().getTime());
        String JSON_URL = HOST_NAME + "api.php?method=update_wallet&user_id=" + Utils.userID + "&deposit=" + dm + "&withdraw=" + wm + "&date=" + dt;
        Volley.newRequestQueue(ctx).add(new JsonObjectRequest(JSON_URL, response -> {
            try {
                JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject objJson = jsonArray.getJSONObject(i);
                    String msg = objJson.getString("msg");
                    getProfile(); makeText(ctx, msg, LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                makeText(ctx,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> makeText(ctx,error.getMessage(),LENGTH_SHORT).show()));
    }

    private void withdrawRequest(String p, String a) {
        String JSON_URL = HOST_NAME + "api.php?method=user_transaction&user_id=" + Utils.userID + "&name=" + Utils.userName + "&phone=" + p + "&amount=" + a;
        Volley.newRequestQueue(ctx).add(new JsonObjectRequest(JSON_URL, response -> {
            try {
                JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject objJson = jsonArray.getJSONObject(i);
                    String msg = objJson.getString("msg");
                    makeText(ctx, msg, LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                makeText(ctx,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> makeText(ctx,error.getMessage(),LENGTH_SHORT).show()));
    }

    @SuppressLint("SetTextI18n")
    private void getProfile(){
        String JSON_URL = HOST_NAME + "api.php?method=user_profile&id=" + Utils.userID;
        Volley.newRequestQueue(ctx).add(new JsonObjectRequest(JSON_URL, response -> {
            try {
                JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject objJson = jsonArray.getJSONObject(i);
                    Utils.userID = objJson.getString("user_id");
                    Utils.userName = objJson.getString("name");
                    Utils.userEmail = objJson.getString("email");
                    Utils.userDP = objJson.getString("user_pro_image");
                    Utils.userPhone = objJson.getString("phone");
                    Utils.deposit = objJson.getString("deposit");
                    Utils.withdraw = objJson.getString("withdraw");
                }
                principle.setText(Utils.deposit);interest.setText(Utils.withdraw);
                BigDecimal bal = new BigDecimal(Utils.deposit).add(new BigDecimal(Utils.withdraw));
                total.setText(bal.toString()); pb.setVisibility(View.GONE);dismiss();
            } catch (Exception e) {
                pb.setVisibility(View.GONE);
                makeText(ctx,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> {
            pb.setVisibility(View.GONE);
            makeText(ctx,error.getMessage(),LENGTH_SHORT).show();
        }));
    }
}
