package com.cscodetech.moverslorry.ui;


import static com.cscodetech.moverslorry.utils.SessionManager.currency;
import static com.cscodetech.moverslorry.utils.SessionManager.wallet;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.cscodetech.moverslorry.R;
import com.cscodetech.moverslorry.databinding.ActivityMywalletBinding;
import com.cscodetech.moverslorry.model.EarningData;
import com.cscodetech.moverslorry.model.Payout;
import com.cscodetech.moverslorry.model.PayoutlistItem;
import com.cscodetech.moverslorry.model.RestResponse;
import com.cscodetech.moverslorry.model.UserLogin;
import com.cscodetech.moverslorry.retrofit.APIClient;
import com.cscodetech.moverslorry.retrofit.GetResult;
import com.cscodetech.moverslorry.utils.CustPrograssbar;
import com.cscodetech.moverslorry.utils.SessionManager;
import com.cscodetech.moverslorry.utils.Utility;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

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

import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;

public class WalletActivity extends BaseActivity implements GetResult.MyListener {

    private ActivityMywalletBinding binding;
    CustPrograssbar custPrograssbar;
    UserLogin user;
    private String owneri = "owner_id";
    private String applicationjson = "application/json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMywalletBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        custPrograssbar = new CustPrograssbar();

        user = sessionmanager.getUserDetails();
        binding.txtTotal.setText("" + sessionmanager.getStringData(currency) + sessionmanager.getFloatData(wallet));

        binding.recyTransaction.setLayoutManager(new GridLayoutManager(this, 1));
        binding.recyTransaction.setItemAnimator(new DefaultItemAnimator());

        // Wire up clicks via ViewBinding
        binding.imgBack.setOnClickListener(v -> finish());
        binding.txtAddmunny.setOnClickListener(v -> bottonWithdraw());

        getEarning();

    }

    private void getHistry() {
        custPrograssbar.prograssCreate(WalletActivity.this);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(owneri, user.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse(applicationjson));
        Call<JsonObject> call = APIClient.getInterface().payoutList(bodyRequest);
        GetResult getResult = new GetResult(this);
        getResult.setMyListener(this);
        getResult.callForLogin(call, "1");

    }

    private void getEarning() {
        custPrograssbar.prograssCreate(WalletActivity.this);
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put(owneri, user.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse(applicationjson));
        Call<JsonObject> call = APIClient.getInterface().getearning(bodyRequest);
        GetResult getResult = new GetResult(this);
        getResult.setMyListener(this);
        getResult.callForLogin(call, "3");

    }

    private void sendWithdraw(String amt, String type, String bankname, String accnumber, String acc_name, String ifsccode, String upiid, String paypalid) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put(owneri, user.getId());
            jsonObject.put("amt", amt);
            jsonObject.put("r_type", type);
            jsonObject.put("bank_name", bankname);
            jsonObject.put("acc_number", accnumber);
            jsonObject.put("acc_name", acc_name);
            jsonObject.put("ifsc_code", ifsccode);
            jsonObject.put("upi_id", upiid);
            jsonObject.put("paypal_id", paypalid);
            RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse(applicationjson));
            Call<JsonObject> call = APIClient.getInterface().requestWithdraw(bodyRequest);
            GetResult getResult = new GetResult(this);
            getResult.setMyListener(this);
            getResult.callForLogin(call, "2");
            custPrograssbar.prograssCreate(WalletActivity.this);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    
    public void onClick(View view) {

        int id = view.getId();
        if (id == R.id.img_back) {
            finish();
        } else if (id == R.id.txt_addmunny) {
            bottonWithdraw();
        }
    }

    @Override
    public void callback(JsonObject result, String callNo) {
        try {
            custPrograssbar.closePrograssBar();
            if (callNo.equalsIgnoreCase("1")) {
                Gson gson = new Gson();
                Payout walletHistry = gson.fromJson(result.toString(), Payout.class);

                if (walletHistry.getResult().equalsIgnoreCase("true")) {
                    if (walletHistry.getPayoutlist().isEmpty()) {
                        binding.recyTransaction.setVisibility(View.GONE);
                        binding.lvlNotfound.setVisibility(View.VISIBLE);
                    } else {
                        HistryAdp histryAdp = new HistryAdp(walletHistry.getPayoutlist());
                        binding.recyTransaction.setAdapter(histryAdp);
                    }

                } else {
                    binding.recyTransaction.setVisibility(View.GONE);
                    binding.lvlNotfound.setVisibility(View.VISIBLE);
                }
            } else if (callNo.equalsIgnoreCase("2")) {

                Gson gson = new Gson();
                RestResponse restResponse = gson.fromJson(result.toString(), RestResponse.class);
                Toast.makeText(this, restResponse.getResponseMsg(), Toast.LENGTH_LONG).show();
                if (restResponse.getResult().equalsIgnoreCase("true")) {
                    finish();
                }
            } else if (callNo.equalsIgnoreCase("3")) {

                Gson gson = new Gson();
                EarningData withdraw = gson.fromJson(result.toString(), EarningData.class);
                if (withdraw.getResult().equalsIgnoreCase("true")) {
                    binding.txtErlimit.setText(getResources().getString(R.string.withdraw_limit) + " " + sessionmanager.getStringData(SessionManager.currency) + withdraw.getEarning().getWithdrawLimit());
                    binding.txtTotal.setText(sessionmanager.getStringData(SessionManager.currency) + withdraw.getEarning().getEarninga());
                    getHistry();
                }
            }
        } catch (Exception e) {
            e.toString();

        }

    }


    private void bottonWithdraw() {
        BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(this);
        View sheetView = getLayoutInflater().inflate(R.layout.bottom_withdraw, null);
        mBottomSheetDialog.setContentView(sheetView);

        RadioGroup radio = sheetView.findViewById(R.id.radio);
        TextView btnSubmit = sheetView.findViewById(R.id.btn_submit);
        TextView txtReject = sheetView.findViewById(R.id.txt_reject);
        EditText edAmount = sheetView.findViewById(R.id.ed_amount);
        EditText edbankname = sheetView.findViewById(R.id.ed_bankname);
        EditText edaccountno = sheetView.findViewById(R.id.ed_accountno);
        EditText edaccountname = sheetView.findViewById(R.id.ed_accountname);
        EditText edaccountifsc = sheetView.findViewById(R.id.ed_accountifsc);
        EditText edaccountupi = sheetView.findViewById(R.id.ed_accountupi);
        EditText edaccountpaypal = sheetView.findViewById(R.id.ed_accountpaypal);

        radio.setOnCheckedChangeListener((radioGroup, i) -> {
            RadioButton radioButton = sheetView.findViewById(i);
            Log.e("IT", "-->" + i);
            switch (radioButton.getText().toString()) {
                case "upi":
                    setVisibility(edbankname, edaccountno, edaccountname, edaccountifsc, edaccountupi, edaccountpaypal, false, false, false, false, true,false);
                    break;
                case "bank transfer":
                    setVisibility(edbankname, edaccountno, edaccountname, edaccountifsc, edaccountupi, edaccountpaypal, true, true, true, true, false,false);
                    break;
                case "paypal":
                    setVisibility(edbankname, edaccountno, edaccountname, edaccountifsc, edaccountupi, edaccountpaypal, false, false, false, false, false,true);
                    break;
                default:
                    break;
            }
        });

        txtReject.setOnClickListener(view -> mBottomSheetDialog.cancel());

        btnSubmit.setOnClickListener(view -> {
            RadioButton radioButton = sheetView.findViewById(radio.getCheckedRadioButtonId());
            String paymentType = radioButton.getText().toString();

            switch (paymentType) {
                case "upi":
                    if (TextUtils.isEmpty(edaccountupi.getText().toString())) {
                        edaccountupi.setError("");
                    } else {
                        mBottomSheetDialog.cancel();
                        sendWithdraw(edAmount.getText().toString(), paymentType, "", "", "", "", edaccountupi.getText().toString(), "");
                    }
                    break;
                case "bank transfer":
                    if (TextUtils.isEmpty(edbankname.getText().toString())) {
                        edbankname.setError("");
                    } else if (TextUtils.isEmpty(edaccountname.getText().toString())) {
                        edaccountname.setError("");
                    } else if (TextUtils.isEmpty(edaccountno.getText().toString())) {
                        edaccountno.setError("");
                    } else if (TextUtils.isEmpty(edaccountifsc.getText().toString())) {
                        edaccountifsc.setError("");
                    } else {
                        mBottomSheetDialog.cancel();
                        sendWithdraw(edAmount.getText().toString(), paymentType, edbankname.getText().toString(), edaccountno.getText().toString(), edaccountname.getText().toString(), edaccountifsc.getText().toString(), "", "");
                    }
                    break;
                case "paypal":
                    if (TextUtils.isEmpty(edaccountpaypal.getText().toString())) {
                        edaccountpaypal.setError("");
                    } else {
                        mBottomSheetDialog.cancel();
                        sendWithdraw(edAmount.getText().toString(), paymentType, "", "", "", "", "", edaccountpaypal.getText().toString());
                    }
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + paymentType);
            }
        });

        mBottomSheetDialog.show();
    }

    private void setVisibility(View view1, View view2, View view3, View view4, View view5, View view6, boolean v1, boolean v2, boolean v3, boolean v4, boolean v5, boolean v6) {
        view1.setVisibility(v1 ? View.VISIBLE : View.GONE);
        view2.setVisibility(v2 ? View.VISIBLE : View.GONE);
        view3.setVisibility(v3 ? View.VISIBLE : View.GONE);
        view4.setVisibility(v4 ? View.VISIBLE : View.GONE);
        view5.setVisibility(v5 ? View.VISIBLE : View.GONE);
        view6.setVisibility(v6 ? View.VISIBLE : View.GONE);
    }

    public class HistryAdp extends RecyclerView.Adapter<HistryAdp.MyViewHolder> {
        private List<PayoutlistItem> list;

        public class MyViewHolder extends RecyclerView.ViewHolder {
            private ImageView imgProof;
            private TextView txtStatus;
            private TextView txtRequst;
            private TextView txtAmt;
            private TextView txtPayby;
            private TextView txtRDate;

            public MyViewHolder(View view) {
                super(view);
                imgProof = view.findViewById(R.id.img_proof);
                txtStatus = view.findViewById(R.id.txt_status);
                txtRequst = view.findViewById(R.id.txt_requst);
                txtAmt = view.findViewById(R.id.txt_amt);
                txtPayby = view.findViewById(R.id.txt_payby);
                txtRDate = view.findViewById(R.id.txt_r_date);
            }
        }

        public HistryAdp(List<PayoutlistItem> list) {
            this.list = list;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_histry, parent, false);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, int position) {
            PayoutlistItem payout = list.get(position);
            Glide.with(WalletActivity.this).load(APIClient.BASE_URL + "/" + payout.getProof()).into(holder.imgProof);
            holder.txtStatus.setText("" + payout.getStatus());
            holder.txtRequst.setText("" + payout.getPayoutId());
            holder.txtAmt.setText(sessionmanager.getStringData(SessionManager.currency) + payout.getAmt());
            holder.txtPayby.setText("" + payout.getRType());
            holder.txtRDate.setText("" + payout.getRDate());
        }

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

    @Override
    protected void onResume() {
        super.onResume();
        if (Utility.getInstance().walletUp) {
            Utility.getInstance().walletUp = false;
            getHistry();
        }
    }
}

