package com.friendvilla.bucksbuddy;

import static android.util.Base64.DEFAULT;
import static android.util.Base64.decode;
import static android.util.Base64.encode;
import static android.widget.Toast.LENGTH_LONG;
import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static androidx.recyclerview.widget.LinearLayoutManager.VERTICAL;
import static com.friendvilla.bucksbuddy.MainActivity.USER;
import static com.friendvilla.bucksbuddy.Method.formatedDate;
import static com.friendvilla.bucksbuddy.Method.processTxn;
import static com.friendvilla.bucksbuddy.Method.title;
import static com.friendvilla.bucksbuddy.Method.updateUser;
import static com.friendvilla.bucksbuddy.controls.Constant.GET_TXN;
import static com.friendvilla.bucksbuddy.controls.Constant.Tag;
import static com.friendvilla.bucksbuddy.controls.Constant.USER_ID;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.friendvilla.bucksbuddy.controls.DepositBox;
import com.friendvilla.bucksbuddy.controls.MessageBox;
import com.friendvilla.bucksbuddy.controls.WithdrawBox;
import com.friendvilla.bucksbuddy.model.Txn;
import com.friendvilla.bucksbuddy.model.User;
import com.razorpay.Checkout;
import com.razorpay.PaymentResultListener;

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

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class WalletActivity extends AppCompatActivity implements PaymentResultListener {

    private User user;
    private JSONObject obj;
    private ProgressDialog pb;
    private static int Amt;
    private TextView tbal,dbal,wbal;
    private RecyclerView transactionVew;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wallet);
        Checkout.preload(getApplicationContext());
        pb = new ProgressDialog(this);pb.setMessage("Please Wait...");pb.setCancelable(false);
        ((TextView)findViewById(R.id.tvTitle)).setText(title(this,getString(R.string.your_wallet),5));
        user = USER.getValue(); assert user != null;
        tbal = findViewById(R.id.totalbal);dbal = findViewById(R.id.dbal);
        wbal = findViewById(R.id.wbal);transactionVew = findViewById(R.id.transactionView);
        BigDecimal bal = new BigDecimal(user.getDeposit()).add(new BigDecimal(user.getWithdraw()));
        tbal.setText("₹ " + bal);dbal.setText("₹ " + user.getDeposit());wbal.setText("₹ " + user.getWithdraw());
        transactionVew.setLayoutManager(new LinearLayoutManager(this,VERTICAL,false));
        transactionVew.setHasFixedSize(false);findViewById(R.id.ivMenu).setOnClickListener(v -> finish());
        findViewById(R.id.addmoney).setOnClickListener(v -> {
            DepositBox deposit = new DepositBox(this);
            deposit.show(getSupportFragmentManager(),Tag);
        });
        findViewById(R.id.withdraw).setOnClickListener(v -> {
            WithdrawBox withdraw = new WithdrawBox(this);
            withdraw.show(getSupportFragmentManager(),Tag);
        });
        String BASE = new String(decode(BuildConfig.BASE_URL,DEFAULT));
        String DATA = USER_ID + "@1@10";
        String HASH = new String(encode(DATA.getBytes(),DEFAULT));
        String URL = BASE + GET_TXN + HASH; List<Txn> txnList = new ArrayList<>();
        Volley.newRequestQueue(this).add(new JsonObjectRequest(URL, response -> {
            try {
                JSONArray res = response.getJSONArray("posts");
                for(int i = 0; i < res.length(); i++) {
                    JSONObject obj = res.getJSONObject(i);
                    String id = obj.getString("id");
                    String uid = obj.getString("userid");
                    String status = obj.getString("status");
                    String date = obj.getString("date");
                    String txn = obj.getString("txn");
                    txnList.add(new Txn(id,uid,status,date,txn));
                }
                transactionVew.setAdapter(new TxnAdapter(txnList));
            } catch (JSONException e) {
                MessageBox msg = new MessageBox(e.getMessage());
                msg.show(getSupportFragmentManager(),Tag);
            }
        }, error -> {
            MessageBox msg = new MessageBox(error.getMessage());
            msg.show(getSupportFragmentManager(),Tag);
        }));
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        BigDecimal bal = new BigDecimal(user.getDeposit()).add(new BigDecimal(user.getWithdraw()));
        tbal.setText("₹ " + bal);dbal.setText("₹ " + user.getDeposit());wbal.setText("₹ " + user.getWithdraw());
    }

    @Override
    public void onPaymentSuccess(String s) {
       /* BigDecimal bd = new BigDecimal(user.getDeposit()).add(new BigDecimal(Amt));
        String d = bd.toString(); pb.show();
        updateUser(this,d,user.getWithdraw(),"0");
        String txnDetails = "Deposit," + Amt + "," + s;
        obj = processTxn(this,0,txnDetails);checkValue();*/
        makeText(this,s,LENGTH_LONG).show();
    }

    @Override
    public void onPaymentError(int i, String s) {
        try {
            JSONObject response = new JSONObject(s);
            JSONObject obj = response.getJSONObject("error");
            makeText(this,obj.getString("description"),LENGTH_SHORT).show();
        } catch (JSONException e) {
            makeText(this,e.getMessage(),LENGTH_SHORT).show();
        }
    }

    private void checkValue() {
        try {
            if(obj != null) {
                pb.dismiss();
                if(obj.getString("success").equals("1")) {
                    makeText(this,"Money Added Successfully!",LENGTH_SHORT).show();
                } else {
                    makeText(this, obj.getString("msg"), LENGTH_SHORT).show();
                }
            } else {
                checkValue();
            }
        } catch (Exception e) {
            pb.dismiss();
            makeText(this,e.getMessage(), LENGTH_SHORT).show();
        }
    }

    public static void startPayment(Activity ctx, int amount, String mail, String mob) {
        final Checkout co = new Checkout();
        co.setImage(R.mipmap.logo);Amt = amount;
        try {
            JSONObject options = new JSONObject();
            options.put("name",ctx.getString(R.string.app_name));
            options.put("description",ctx.getString(R.string.add_money));
            options.put("send_sms_hash",true);
            options.put("allow_rotation", true);
            options.put("currency", "INR");
            options.put("amount",amount*100);
            JSONObject preFill = new JSONObject();
            preFill.put("email",mail);
            preFill.put("contact",mob);
            options.put("prefill",preFill);
            co.open(ctx,options);
        } catch (Exception e) {
            makeText(ctx,"Error in payment: " + e.getMessage(),LENGTH_SHORT).show();
        }
    }

    private static class TxnAdapter extends RecyclerView.Adapter<TxnAdapter.TxnView> {
        private final List<Txn> txnList;
        TxnAdapter(List<Txn> txnList) {
            this.txnList = txnList;
        }

        @NonNull
        @Override
        public TxnView onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.txn,parent,false);
            return new TxnView(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(@NonNull TxnView holder, int position) {
            Txn txn = txnList.get(position);
            String[] data = txn.getTxn().split(",");
            if(data[0].equalsIgnoreCase("deposit")) {
                holder.type.setText("Deposit Money");
            } else if(data[0].equalsIgnoreCase("withdraw")) {
                holder.icon.setRotation(180);
                holder.type.setText("Withdraw Money");
            } else {
                holder.type.setText(data[0]);
            }
            holder.date.setText(formatedDate(txn.getDate()));
            holder.amnt.setText(data[1] + " INR");
            switch (txn.getStatus()) {
                case "0":
                    holder.stats.setText("Pending");
                    holder.stats.setTextColor(Color.DKGRAY);
                    break;
                case "1":
                    holder.stats.setText("Success");
                    holder.stats.setTextColor(Color.GREEN);
                    break;
                case "2":
                    holder.stats.setText("Reject");
                    holder.stats.setTextColor(Color.RED);
                    break;
            }
        }

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

        private static class TxnView extends RecyclerView.ViewHolder {
            private final TextView icon;
            private final TextView type;
            private final TextView date;
            private final TextView amnt;
            private final TextView stats;
            public TxnView(@NonNull View itemView) {
                super(itemView);
                icon = itemView.findViewById(R.id.icon);
                type = itemView.findViewById(R.id.type);
                date = itemView.findViewById(R.id.date);
                amnt = itemView.findViewById(R.id.amnt);
                stats = itemView.findViewById(R.id.stats);
            }
        }
    }

}