package com.cscodetech.moverslorry.ui;


import static com.cscodetech.moverslorry.utils.FileUtils.createPartFromString;
import static com.cscodetech.moverslorry.utils.FileUtils.prepareFilePart;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
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.core.content.FileProvider;
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.ActivityIdentityVerifyBinding;
import com.cscodetech.moverslorry.model.RestResponse;
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 java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

public class IdentityVerifyActivity extends BaseActivity implements GetResult.MyListener {

    private ActivityIdentityVerifyBinding binding;
    ArrayList<Imagemode> arrayListImage = new ArrayList<>();
    String selectimge;
    CustPrograssbar custPrograssbar;
    String isVerry;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityIdentityVerifyBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        
        isVerry = getIntent().getStringExtra("isverry");

        if (isVerry.equalsIgnoreCase("4")) {
            binding.lvlSelfe.setVisibility(View.GONE);
        } else if (isVerry.equalsIgnoreCase("5")) {
            binding.lvlIdenty.setVisibility(View.GONE);
        }

        custPrograssbar = new CustPrograssbar();

        binding.recyclerselectimg.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
        binding.recyclerselectimg.setItemAnimator(new DefaultItemAnimator());

        // Wire clicks via ViewBinding
        binding.imgBack.setOnClickListener(this::onBindClick);
        binding.btnUpload.setOnClickListener(this::onBindClick);
        binding.lvlPassport.setOnClickListener(this::onBindClick);
        binding.lvlSelfe.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_upload) {
            uploadMultiFile();
        } else if (id == R.id.lvl_passport) {
            if (binding.imgIsuploadp.getVisibility() == View.GONE) {
                selectimge = "doc";
                Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                launcher.launch(intent);
            } else {
                Toast.makeText(IdentityVerifyActivity.this, "Document max 2 pic select", Toast.LENGTH_LONG).show();
            }
        } else if (id == R.id.lvl_selfe) {
            if (binding.imgIsuploadi.getVisibility() == View.GONE) {
                selectimge = "self";
                cameraOpen();
            } else {
                Toast.makeText(IdentityVerifyActivity.this, "Self 1 pic select", Toast.LENGTH_LONG).show();
            }
        }


    }


    private void cameraOpen() {

        Intent captureImageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (captureImageIntent.resolveActivity(getPackageManager()) != null) {
            // Create a file to store the image
            File imageFile = null;
            try {
                imageFile = createImageFile();
            } catch (IOException ex) {
                // Handle error
                ex.printStackTrace();
            }
            if (imageFile != null) {
                // Get the URI for the file
                imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", imageFile);
                // Add the URI as an extra to the intent
                Log.e("Image Camera", "-->" + imageUri);
                captureImageIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                // Launch the camera app with the intent
//                launcher.launch(captureImageIntent);
                startActivityForResult(captureImageIntent, 1888);

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_CANCELED) {

            if (requestCode == 1888) {


                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);
                        }
                    }

                    // Get the file path of the saved image file
                    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();

                }
            }
        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        return File.createTempFile(imageFileName, ".jpg", storageDir);
    }

    String images = "images";
    String image = "image";

    private void uploadMultiFile() {
        custPrograssbar.prograssCreate(IdentityVerifyActivity.this);

        List<MultipartBody.Part> parts = new ArrayList<>();
        List<MultipartBody.Part> partss = new ArrayList<>();

        for (int i = 0; i < arrayListImage.size(); i++) {

            if (arrayListImage.get(i).getType().equalsIgnoreCase("doc")) {
                parts.add(prepareFilePart(getImageName(isVerry, i), arrayListImage.get(i).getImg()));
            } else {
                partss.add(prepareFilePart(getImagesName(isVerry), arrayListImage.get(i).getImg()));
            }
        }

        RequestBody uid = createPartFromString(sessionmanager.getUserDetails().getId());
        RequestBody statuss = createPartFromString(getStatus(isVerry));
        RequestBody size = createPartFromString("" + parts.size());
        RequestBody sizes = createPartFromString("" + partss.size());

        Call<JsonObject> call = APIClient.getInterface().dyAnswer(uid, statuss, size, parts, sizes, partss);
        GetResult getResult = new GetResult(this);
        getResult.setMyListener(this);
        getResult.callForLogin(call, "1");
    }

    private String getStatus(String isVerry) {
        switch (isVerry) {
            case "0":
                return "First";
            case "3":
                return "Both";
            case "4":
                return "Identity";
            case "5":
                return "Selfie";
            default:
                return "";
        }
    }

    private String getImageName(String isVerry, int index) {
        switch (isVerry) {
            case "0":
                return image + index;
            case "3":
            case "4":
                return image + index;
            default:
                return "";
        }
    }

    private String getImagesName(String isVerry) {
        switch (isVerry) {
            case "0":
                return images + 0;
            case "3":
            case "5":
                return images + 0;
            default:
                return "";
        }
    }

    @Override
    public void callback(JsonObject result, String callNo) {

        try {
            custPrograssbar.closePrograssBar();
            Gson gson = new Gson();
            RestResponse response = gson.fromJson(result.toString(), RestResponse.class);
            Toast.makeText(this, response.getResponseMsg(), Toast.LENGTH_SHORT).show();
            Utility.getInstance().walletUp = true;
            if (response.getResult().equalsIgnoreCase("true")) {
                finish();
            }
        } catch (Exception e) {
            Log.e("Error", "--> " + e.getMessage());

        }
    }


    Uri imageUri;
    ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {


                if (result.getResultCode() == Activity.RESULT_OK) {
                    Uri imageUrit;

                    if (result != null && result.getData() != null) {

                        imageUrit = result.getData().getData();
                        Log.e("select Image", "-1212->" + imageUrit);

                    } else {
                        imageUrit = imageUri;
                        Log.e("select Image", "-1313->" + imageUrit);
                    }
                    try (InputStream inputStream = getContentResolver().openInputStream(imageUrit)) {
                        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);
                            }
                        }

                        // Get the file path of the saved image file
                        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) {
        int doc = 0;
        int self = 0;
        for (int i = 0; i < urilist.size(); i++) {
            if (urilist.get(i).getType().equalsIgnoreCase("doc")) {
                doc = doc + 1;
            } else if (urilist.get(i).getType().equalsIgnoreCase("self")) {
                self = self + 1;
            }
        }

        if (doc == 2) {
            binding.imgIsuploadp.setVisibility(View.VISIBLE);
            binding.txtSubtitle.setText(getString(R.string.uploaded_successfully));
        } else {
            binding.imgIsuploadp.setVisibility(View.GONE);
            binding.txtSubtitle.setText(getString(R.string.haven_t_uploaded_yet));


        }
        if (self == 1) {
            binding.txtSubtitle1.setText(getString(R.string.uploaded_successfully));
            binding.imgIsuploadi.setVisibility(View.VISIBLE);
        } else {
            binding.imgIsuploadi.setVisibility(View.GONE);
            binding.txtSubtitle1.setText(getString(R.string.haven_t_uploaded_yet));

        }

        if ((self == 1 && doc == 2) || (doc == 2 && isVerry.equalsIgnoreCase("4")) || (self == 1 && isVerry.equalsIgnoreCase("5"))) {
            binding.btnUpload.setVisibility(View.VISIBLE);
        } else {
            binding.btnUpload.setVisibility(View.GONE);

        }

    }


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


        public class MyViewHolder extends RecyclerView.ViewHolder {

            public ImageView remove;
            public ImageView thumbnail;
            public 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(IdentityVerifyActivity.this)
                    .load(arrayList.get(position).img)
                    .thumbnail(Glide.with(IdentityVerifyActivity.this).load(R.drawable.tprofile))
                    .into(holder.thumbnail);
            holder.txtType.setText(arrayList.get(position).type);
            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;
        }
    }
}
