package com.cscodetech.moverslorry.ui;


import static com.cscodetech.moverslorry.utils.SessionManager.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import com.cscodetech.moverslorry.R;
import com.cscodetech.moverslorry.databinding.ActivitySignUpBinding;
import com.cscodetech.moverslorry.model.Contry;
import com.cscodetech.moverslorry.model.Login;
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.Utility;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.onesignal.OneSignal;

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

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

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

public class SignUpActivity extends BaseActivity implements GetResult.MyListener {

    private ActivitySignUpBinding binding;
    CustPrograssbar custPrograssbar;

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

        // Wire clicks via ViewBinding
        binding.btnSignup.setOnClickListener(this::onBindClick);
        binding.lvlLogin.setOnClickListener(this::onBindClick);
    }

    private void checkMobile() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile", binding.edUsername.getText().toString());
            jsonObject.put("ccode", binding.spinnerautocompet.getText().toString());

            RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json"));
            Call<JsonObject> call = APIClient.getInterface().mobileCheck(bodyRequest);
            GetResult getResult = new GetResult(this);
            getResult.setMyListener(this);
            getResult.callForLogin(call, "2");
            custPrograssbar.prograssCreate(SignUpActivity.this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void onBindClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_signup) {

            if (validationCreate()) {
                checkMobile();

            }
        } else if (id == R.id.lvl_login) {
            finish();
        }
    }

    private void getCode() {
        JSONObject jsonObject = new JSONObject();

        RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json"));
        Call<JsonObject> call = APIClient.getInterface().getCodelist(bodyRequest);
        GetResult getResult = new GetResult(this);
        getResult.setMyListener(this);
        getResult.callForLogin(call, "1");

    }

    @Override
    public void callback(JsonObject result, String callNo) {
        try {
            if (callNo.equalsIgnoreCase("1")) {
                Gson gson = new Gson();
                Contry contry = gson.fromJson(result.toString(), Contry.class);
                List<String> arealist = new ArrayList<>();
                for (int i = 0; i < contry.getCountryCode().size(); i++) {
                    if (contry.getCountryCode().get(i).getStatus().equalsIgnoreCase("1")) {
                        arealist.add(contry.getCountryCode().get(i).getCcode());
                    }
                }
                ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                        android.R.layout.simple_dropdown_item_1line, arealist);
                binding.spinnerautocompet.setText(arealist.get(0));
                binding.spinnerautocompet.setAdapter(adapter);
            } else if (callNo.equalsIgnoreCase("2")) {
                Gson gson = new Gson();
                RestResponse response = gson.fromJson(result.toString(), RestResponse.class);
                if (response.getResult().equals("true")) {

                    Utility.getInstance().isvarification = 1;
                    UserLogin userLogin = new UserLogin();
                    userLogin.setCcode(binding.spinnerautocompet.getText().toString());
                    userLogin.setMobile(binding.edUsername.getText().toString());
                    userLogin.setName(binding.editFullname.getText().toString());
                    userLogin.setEmail(binding.editEmail.getText().toString());
                    userLogin.setPassword(binding.editPassword.getText().toString());
                    userLogin.setRefercode(binding.editRefercode.getText().toString());
                    sessionmanager.setUserDetails(userLogin);
                    if (response.getOtpAuth().equalsIgnoreCase("No")) {
                        createUser();
                    } else {
                        startActivity(new Intent(this, VerificationActivity.class));
                    }


                } else {
                    Toast.makeText(this, "Number is register", Toast.LENGTH_SHORT).show();
                }
            } else if (callNo.equalsIgnoreCase("3")) {
                Gson gson = new Gson();
                Login loginUser = gson.fromJson(result.toString(), Login.class);
                Toast.makeText(this, loginUser.getResponseMsg(), Toast.LENGTH_LONG).show();
                if (loginUser.getResult().equalsIgnoreCase("true")) {
                    sessionmanager.setBooleanData(login, true);
                    sessionmanager.setUserDetails(loginUser.getUserLogin());
                    OneSignal.sendTag("owner_id", loginUser.getUserLogin().getId());

                    startActivity(new Intent(this, HomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
                }
            }

        } catch (Exception e) {
            Log.e("Error", "--> " + e.getMessage());

        }
    }

    public boolean validationCreate() {
        if (TextUtils.isEmpty(binding.edUsername.getText().toString())) {
            binding.edUsername.setError("Enter Mobile");
            return false;
        }
        if (TextUtils.isEmpty(binding.editFullname.getText().toString())) {
            binding.editFullname.setError("Enter Name");
            return false;
        }

        if (TextUtils.isEmpty(binding.editEmail.getText().toString())) {
            binding.editEmail.setError("Enter Email");
            return false;
        }
        if (TextUtils.isEmpty(binding.editPassword.getText().toString())) {
            binding.editPassword.setError("Enter Password");
            return false;
        }

        return true;
    }

    private void createUser() {

        custPrograssbar.prograssCreate(this);
        UserLogin user = sessionmanager.getUserDetails();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", user.getName());
            jsonObject.put("mobile", user.getMobile());
            jsonObject.put("ccode", user.getCcode());
            jsonObject.put("email", user.getEmail());
            jsonObject.put("password", user.getPassword());
            jsonObject.put("refercode", user.getRefercode());

        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json"));
        Call<JsonObject> call = APIClient.getInterface().createUser(bodyRequest);
        GetResult getResult = new GetResult(this);
        getResult.setMyListener(this);
        getResult.callForLogin(call, "3");

    }
}