package com.cscodetech.moverslorry.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.cscodetech.moverslorry.R;
import com.cscodetech.moverslorry.databinding.ActivityMyLoadDetailsBinding;
import com.cscodetech.moverslorry.model.LoadDetailMain;
import com.cscodetech.moverslorry.model.LoadDetails;
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 okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;

public class MyLoadDetailsActivity extends AppCompatActivity implements GetResult.MyListener {

    private ActivityMyLoadDetailsBinding binding;
    SessionManager sessionManager;
    UserLogin userLogin;
    CustPrograssbar custPrograssbar;
    String ownerid = "owner_id";
    String load_id = "load_id";
    String applicationjson = "application/json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMyLoadDetailsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        sessionManager = new SessionManager(this);
        userLogin = sessionManager.getUserDetails();
        custPrograssbar = new CustPrograssbar();
        // Wire clicks via ViewBinding
        binding.imgBack.setOnClickListener(this::onBindClick);
        binding.btnPickup.setOnClickListener(this::onBindClick);
        binding.imgCallPick.setOnClickListener(this::onBindClick);
        binding.imgCallDrop.setOnClickListener(this::onBindClick);
        binding.btnDrop.setOnClickListener(this::onBindClick);
        binding.btnRating.setOnClickListener(this::onBindClick);
        binding.imgs.setOnClickListener(this::onBindClick);

        getLoad();
    }

    
    public void onBindClick(View view) {
        int id = view.getId();
        if (id == R.id.img_back) {
            finish();
        } else if (id == R.id.btn_pickup) {
            getLorryDecision("1");
        } else if (id == R.id.img_call_pick) {
            Log.e("Number", "-->" + loadDetails.getLoadDetails().getLoaderMobile());
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + loadDetails.getLoadDetails().getPickMobile()));
            startActivity(intent);
        } else if (id == R.id.img_call_drop) {
            Intent intent1 = new Intent(Intent.ACTION_CALL);
            intent1.setData(Uri.parse("tel:" + loadDetails.getLoadDetails().getDropMobile()));
            startActivity(intent1);
        } else if (id == R.id.btn_drop) {
            getLorryDecision("2");
        } else if (id == R.id.btn_rating) {
            sendReview(this);
        } else if (id == R.id.imgs) {
            startActivity(new Intent(this, BidderInfoActivity.class)
                    .putExtra("uid", loadDetails.getLoadDetails().getUid()));
        }
    }

    private void getLoad() {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("owner_id", userLogin.getId());
            jsonObject.put(load_id, getIntent().getStringExtra("lid"));

            RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse(applicationjson));
            Call<JsonObject> call = APIClient.getInterface().loadDetails(bodyRequest);
            GetResult getResult = new GetResult(this);
            getResult.setMyListener(this);
            getResult.callForLogin(call, "1");
            custPrograssbar.prograssCreate(this);


        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void getLorryDecision(String status) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("owner_id", sessionManager.getUserDetails().getId());
            jsonObject.put(load_id, getIntent().getStringExtra("lid"));
            jsonObject.put("status", status);
            jsonObject.put("load_type", "POST_LOAD");


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

    private void getRateUpdate(String rate, String ratetext) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("uid", sessionManager.getUserDetails().getId());
            jsonObject.put(load_id, getIntent().getStringExtra("lid"));
            jsonObject.put("total_lrate", rate);
            jsonObject.put("rate_ltext", ratetext);
            RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse(applicationjson));
            Call<JsonObject> call = APIClient.getInterface().rateUpdate(bodyRequest);
            GetResult getResult = new GetResult(this);
            getResult.setMyListener(this);
            getResult.callForLogin(call, "2");
            custPrograssbar.prograssCreate(MyLoadDetailsActivity.this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void sendReview(Context context) {
        Activity activity = (Activity) context;
        BottomSheetDialog mBottomSheetDialog = new BottomSheetDialog(activity);
        View rootView = activity.getLayoutInflater().inflate(R.layout.sendrview_layout, null);
        mBottomSheetDialog.setContentView(rootView);
        TextView txtClick = rootView.findViewById(R.id.btn_load);
        ImageView img_p = rootView.findViewById(R.id.img_p);
        TextView txt_name = rootView.findViewById(R.id.txt_name);
        TextView txt_lorry = rootView.findViewById(R.id.txt_lorry);
        EditText edRevire = rootView.findViewById(R.id.ed_revire);
        RatingBar rating = rootView.findViewById(R.id.rating);
        txtClick.setText(getResources().getString(R.string.rate_to) + " " + loadDetails.getLoadDetails().getLoaderName());
        Glide.with(this).load(APIClient.BASE_URL + "/" + loadDetails.getLoadDetails().getLoaderImg()).thumbnail(Glide.with(MyLoadDetailsActivity.this).load(R.drawable.tprofile)).into(img_p);
        txt_name.setText("" + loadDetails.getLoadDetails().getLoaderName());
        txt_lorry.setText("" + loadDetails.getLoadDetails().getLoaderMobile());
        txtClick.setOnClickListener(v -> {
            mBottomSheetDialog.cancel();
            String ratin = String.valueOf(rating.getRating());
            getRateUpdate(ratin, edRevire.getText().toString());


        });
        mBottomSheetDialog.setCancelable(true);
        mBottomSheetDialog.show();
    }

    LoadDetailMain loadDetails;

    @Override
    public void callback(JsonObject result, String callNo) {
        try {
            custPrograssbar.closePrograssBar();
            if (callNo.equalsIgnoreCase("1")) {
                handleLoadDetails(result.toString());
            } else if (callNo.equalsIgnoreCase("2")) {
                handleRestResponse(result.toString());
            }
        } catch (Exception e) {
            Log.e("Error", "--> " + e.getMessage());
        }

    }

    private void handleLoadDetails(String result) {
        Gson gson = new Gson();
        loadDetails = gson.fromJson(result, LoadDetailMain.class);
        if (loadDetails.getResult().equalsIgnoreCase("true")) {
            setLoadDetails(loadDetails.getLoadDetails());
        }
    }

    private void setLoadDetails(LoadDetails loadDetails) {

        Glide.with(this).load(APIClient.BASE_URL + "/" + loadDetails.getVehicleImg()).thumbnail(Glide.with(MyLoadDetailsActivity.this).load(R.drawable.tprofile)).into(binding.imgt);
        binding.txtActionbar.setText(getResources().getString(R.string.load) + " #" + loadDetails.getId());
        binding.txtTitle.setText("" + loadDetails.getVehicleTitle());
        binding.txtPrice.setText(sessionManager.getStringData(SessionManager.currency) + loadDetails.getAmount());
        binding.txtTonneorfix.setText(" /" + loadDetails.getAmtType());
        binding.txtPick.setText("" + loadDetails.getPickupState());
        binding.txtPickaddress.setText("" + loadDetails.getPickupPoint());
        binding.txtDrop.setText("" + loadDetails.getDropState());
        binding.txtDropaddress.setText("" + loadDetails.getDropPoint());
        binding.txtDate.setText("" + Utility.getInstance().parseDateToddMMyy(loadDetails.getPostDate()));
        binding.txtTonne.setText("" + loadDetails.getWeight());
        binding.txtMaterial.setText("" + loadDetails.getMaterialName());

        Glide.with(this).load(APIClient.BASE_URL + "/" + loadDetails.getLoaderImg()).thumbnail(Glide.with(MyLoadDetailsActivity.this).load(R.drawable.tprofile)).into(binding.imgs);
        binding.txtName.setText("" + loadDetails.getLoaderName());
        binding.txtRates.setText("" + loadDetails.getLoaderRate());
        binding.txtPricel.setText(sessionManager.getStringData(SessionManager.currency) + loadDetails.getAmount());
        binding.txtTonnefixb.setText("/ " + loadDetails.getAmtType());

        binding.txtPmethod.setText("" + loadDetails.getpMethodName());
        binding.txtTrasaction.setText("" + loadDetails.getOrderTransactionId());
        binding.txtSubtotal.setText(sessionManager.getStringData(SessionManager.currency) + loadDetails.getTotalAmt());
        binding.txtWallet.setText(sessionManager.getStringData(SessionManager.currency) + loadDetails.getWalAmt());
        binding.txtTpayment.setText(sessionManager.getStringData(SessionManager.currency) + loadDetails.getPayAmt());

        if (loadDetails.getWalAmt().equalsIgnoreCase("0")) {
            binding.lvlWalletRow.setVisibility(View.GONE);
        } else {
            binding.lvlWalletRow.setVisibility(View.VISIBLE);
            binding.txtWallet.setText(getResources().getString(R.string.load) + " #" + loadDetails.getWalAmt());
        }

        handleFlowId(loadDetails.getFlowId(), loadDetails.getIsRate(), loadDetails.getLoaderName());
    }

    private void handleFlowId(String flowId, String isRate, String loaderName) {
        if (flowId.equalsIgnoreCase("0")) {
            Log.e("Error", "--> ");
        } else if (flowId.equalsIgnoreCase("1")) {
            binding.btnPickup.setVisibility(View.VISIBLE);
            binding.lvlContact.setVisibility(View.VISIBLE);
            binding.btnDrop.setVisibility(View.GONE);
            binding.txtPickName.setText("" + loadDetails.getLoadDetails().getPickName());
            binding.txtPickMob.setText("" + loadDetails.getLoadDetails().getPickMobile());
            binding.txtDropName.setText("" + loadDetails.getLoadDetails().getDropName());
            binding.txtDropMob.setText("" + loadDetails.getLoadDetails().getDropMobile());

        } else if (flowId.equalsIgnoreCase("2")) {
            binding.btnDrop.setVisibility(View.VISIBLE);
            binding.btnPickup.setVisibility(View.GONE);
            binding.lvlContact.setVisibility(View.VISIBLE);
            binding.txtPickName.setText("" + loadDetails.getLoadDetails().getPickName());
            binding.txtPickMob.setText("" + loadDetails.getLoadDetails().getPickMobile());
            binding.txtDropName.setText("" + loadDetails.getLoadDetails().getDropName());
            binding.txtDropMob.setText("" + loadDetails.getLoadDetails().getDropMobile());
        } else if (flowId.equalsIgnoreCase("3") && isRate.equalsIgnoreCase("0")) {
            binding.btnDrop.setVisibility(View.GONE);
            binding.btnPickup.setVisibility(View.GONE);
            binding.btnRating.setVisibility(View.VISIBLE);
            binding.btnRating.setText(getResources().getString(R.string.rate_to) + " " + loaderName);
        } else if (flowId.equalsIgnoreCase("3")) {
            binding.btnDrop.setVisibility(View.GONE);
            binding.btnPickup.setVisibility(View.GONE);
            binding.btnRating.setVisibility(View.GONE);
        }
    }

    private void handleRestResponse(String result) {
        Gson gson = new Gson();
        RestResponse restResponse = gson.fromJson(result, RestResponse.class);
        Toast.makeText(MyLoadDetailsActivity.this, restResponse.getResponseMsg(), Toast.LENGTH_SHORT).show();
        if (restResponse.getResult().equalsIgnoreCase("true")) {
            finish();
        }
    }
}
