package com.cscodetech.moverslorry.ui;

import static com.cscodetech.moverslorry.utils.FileUtils.isLocal;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.cscodetech.moverslorry.R;
import com.cscodetech.moverslorry.databinding.ActivityAddLorryThreeBinding;
import com.cscodetech.moverslorry.model.RestResponse;
import com.cscodetech.moverslorry.model.TempAddLorry;
import com.cscodetech.moverslorry.model.UserLogin;
import com.cscodetech.moverslorry.retrofit.APIClient;
import com.cscodetech.moverslorry.utils.CustPrograssbar;
import com.cscodetech.moverslorry.utils.FileUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddLorryThreeActivity extends BaseActivity {

    private ActivityAddLorryThreeBinding binding;

    CustPrograssbar custPrograssbar;

    UserLogin userLogin;

    ArrayList<Imagemode> arrayListImage = new ArrayList<>();
    TempAddLorry tempAddLorry;
    String image = "image";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityAddLorryThreeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        custPrograssbar = new CustPrograssbar();

        userLogin = sessionmanager.getUserDetails();

        tempAddLorry = (TempAddLorry) getIntent().getSerializableExtra("mydata");
        binding.recyclerselectimg.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        binding.recyclerselectimg.setItemAnimator(new DefaultItemAnimator());

        if (!tempAddLorry.getRecordId().equalsIgnoreCase("-1")) {
            binding.edMaterialname.setText(tempAddLorry.getDescription());
        }

        // Wire clicks via ViewBinding
        binding.imgBack.setOnClickListener(this::onBindClick);
        binding.btnNext.setOnClickListener(this::onBindClick);
        binding.lvlDocument.setOnClickListener(this::onBindClick);
    }

    public void onBindClick(View view) {
        int id = view.getId();
        if (id == R.id.img_back) {
            finish();
        } else if (id == R.id.btn_next) {
            if (!TextUtils.isEmpty(binding.edMaterialname.getText().toString())) {
                tempAddLorry.setDescription(binding.edMaterialname.getText().toString());
                if (arrayListImage.size() != 0 && tempAddLorry.getRecordId().equalsIgnoreCase("-1")) {
                    uploadMultiFile(arrayListImage);
                } else {
                    uploadEditMultiFile(arrayListImage);
                }
            } else {
                binding.edMaterialname.setError("");
            }
        } else if (id == R.id.lvl_document) {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            launcher.launch(intent);
        }
    }

    private void uploadMultiFile(ArrayList<Imagemode> filePaths) {
        custPrograssbar.prograssCreate(AddLorryThreeActivity.this);
        List<MultipartBody.Part> parts = new ArrayList<>();

        if (filePaths != null) {
            for (int i = 0; i < filePaths.size(); i++) {
                parts.add(prepareFilePart(image + i, filePaths.get(i).img));
            }
        }

        RequestBody ownerid = createPartFromString(tempAddLorry.getOwnerId());
        RequestBody lorryNo = createPartFromString(tempAddLorry.getLorryNo());
        RequestBody weight = createPartFromString(tempAddLorry.getWeight());
        RequestBody description = createPartFromString(tempAddLorry.getDescription());
        RequestBody vehicleId = createPartFromString(tempAddLorry.getVehicleId());
        RequestBody status = createPartFromString("1");
        RequestBody currLocation = createPartFromString(tempAddLorry.getCurrLocation());
        RequestBody currStateId = createPartFromString("1");
        RequestBody routes = createPartFromString(tempAddLorry.getRoutes());
        RequestBody size = createPartFromString("" + parts.size());

        Call<JsonObject> call = APIClient.getInterface().uploadMultiFile(
                ownerid, lorryNo, weight, description, vehicleId, status, currLocation, currStateId, routes, size, parts);

        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                custPrograssbar.closePrograssBar();
                Gson gson = new Gson();
                RestResponse restResponse = gson.fromJson(response.body(), RestResponse.class);
                Toast.makeText(AddLorryThreeActivity.this, restResponse.getResponseMsg(), Toast.LENGTH_SHORT).show();
                if (restResponse.getResult().equalsIgnoreCase("true")) {
                    arrayListImage.clear();
                    startActivity(new Intent(AddLorryThreeActivity.this, HomeActivity.class)
                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
                    finish();
                }
            }

            @Override
            public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                custPrograssbar.closePrograssBar();
            }
        });
    }

    private void uploadEditMultiFile(ArrayList<Imagemode> filePaths) {
        custPrograssbar.prograssCreate(AddLorryThreeActivity.this);
        List<MultipartBody.Part> parts = new ArrayList<>();

        if (filePaths != null) {
            for (int i = 0; i < filePaths.size(); i++) {
                parts.add(prepareFilePart(image + i, filePaths.get(i).img));
            }
        }

        RequestBody recordid = createPartFromString(tempAddLorry.getRecordId());
        RequestBody ownerid = createPartFromString(tempAddLorry.getOwnerId());
        RequestBody lorryNo = createPartFromString(tempAddLorry.getLorryNo());
        RequestBody weight = createPartFromString(tempAddLorry.getWeight());
        RequestBody description = createPartFromString(tempAddLorry.getDescription());
        RequestBody vehicleId = createPartFromString(tempAddLorry.getVehicleId());
        RequestBody status = createPartFromString("1");
        RequestBody currLocation = createPartFromString(tempAddLorry.getCurrLocation());
        RequestBody currStateId = createPartFromString("1");
        RequestBody routes = createPartFromString(tempAddLorry.getRoutes());
        RequestBody size = createPartFromString("" + parts.size());

        Call<JsonObject> call = APIClient.getInterface().uploadEditMultiFile(
                recordid, ownerid, lorryNo, weight, description, vehicleId, status, currLocation, currStateId, routes, size, parts);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(@NonNull Call<JsonObject> call, @NonNull Response<JsonObject> response) {
                custPrograssbar.closePrograssBar();
                Gson gson = new Gson();
                RestResponse restResponse = gson.fromJson(response.body(), RestResponse.class);
                Toast.makeText(AddLorryThreeActivity.this, restResponse.getResponseMsg(), Toast.LENGTH_SHORT).show();
                if (restResponse.getResult().equalsIgnoreCase("true")) {
                    arrayListImage.clear();
                    startActivity(new Intent(AddLorryThreeActivity.this, HomeActivity.class)
                            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
                    finish();
                }
            }

            @Override
            public void onFailure(@NonNull Call<JsonObject> call, @NonNull Throwable t) {
                custPrograssbar.closePrograssBar();
            }
        });
    }

    private RequestBody createPartFromString(String descriptionString) {
        return RequestBody.create(MediaType.parse(FileUtils.MIME_TYPE_TEXT), descriptionString);
    }

    @NonNull
    private MultipartBody.Part prepareFilePart(String partName, String fileUri) {
        File file = getFile(fileUri);
        RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file);
        return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
    }

    public static File getFile(String path) {
        if (path == null) {
            return null;
        }
        if (isLocal(path)) {
            return new File(path);
        }
        return null;
    }

    ActivityResultLauncher<Intent> launcher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Uri imageUri = result.getData().getData();
                    try (InputStream inputStream = getContentResolver().openInputStream(imageUri)) {
                        File outputDir = getApplicationContext().getFilesDir();
                        File outputFile = File.createTempFile(image, null, outputDir);
                        try (OutputStream outputStream = new FileOutputStream(outputFile)) {
                            byte[] buffer = new byte[1024];
                            int bytesRead;
                            while ((bytesRead = inputStream.read(buffer)) != -1) {
                                outputStream.write(buffer, 0, bytesRead);
                            }
                        }
                        String filePath = outputFile.getAbsolutePath();
                        if (filePath != null) {
                            Imagemode imagemode = new Imagemode();
                            imagemode.setImg(filePath);
                            imagemode.setType("selectimge");
                            arrayListImage.add(imagemode);
                            postImage(arrayListImage);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

    public void postImage(List<Imagemode> urilist) {
        ImageAdp imageAdp = new ImageAdp(urilist);
        binding.recyclerselectimg.setAdapter(imageAdp);
        imgeselect(urilist);
    }

    public void imgeselect(List<Imagemode> urilist) {
        if (urilist.size() == 2) {
            binding.imgIsuploadp.setVisibility(View.VISIBLE);
            binding.txtSubtitle.setText(getString(R.string.uploaded_successfully));
            binding.btnNext.setVisibility(View.VISIBLE);
        } else {
            binding.imgIsuploadp.setVisibility(View.GONE);
            binding.txtSubtitle.setText(getString(R.string.haven_t_uploaded_yet));
            binding.btnNext.setVisibility(View.GONE);
        }
    }

    public class ImageAdp extends RecyclerView.Adapter<ImageAdp.MyViewHolder> {
        private List<Imagemode> arrayList;

        public class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView remove;
            ImageView thumbnail;
            TextView txtType;

            public MyViewHolder(View view) {
                super(view);
                thumbnail = view.findViewById(R.id.image_pic);
                remove = view.findViewById(R.id.image_remove);
                txtType = view.findViewById(R.id.txt_type);
            }
        }

        public ImageAdp(List<Imagemode> arrayList) {
            this.arrayList = arrayList;
        }

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

        @Override
        public void onBindViewHolder(final MyViewHolder holder, int position) {
            Glide.with(AddLorryThreeActivity.this)
                    .load(arrayList.get(position).img)
                    .thumbnail(Glide.with(AddLorryThreeActivity.this).load(R.drawable.tprofile))
                    .into(holder.thumbnail);
            holder.txtType.setVisibility(View.GONE);
            holder.remove.setOnClickListener(v -> {
                if (!arrayList.isEmpty()) {
                    arrayList.remove(position);
                    notifyDataSetChanged();
                    imgeselect(arrayList);
                }
            });
        }

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

    class Imagemode {
        String type;
        String img;

        public String getType() { return type; }
        public void setType(String type) { this.type = type; }
        public String getImg() { return img; }
        public void setImg(String img) { this.img = img; }
    }
}
