package com.younki.maidmatching.ui;

import static android.app.Activity.RESULT_OK;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.younki.maidmatching.R;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.GlobalResponse;
import com.younki.maidmatching.services.SharedPreference.Preferences;
import com.younki.maidmatching.ui.maid.MaidProfileFragment;
import com.younki.maidmatching.ui.owner.OwnerProfileFragment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link VerifyAccountFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class VerifyAccountFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public VerifyAccountFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment VerifyAccountFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static VerifyAccountFragment newInstance(String param1, String param2) {
        VerifyAccountFragment fragment = new VerifyAccountFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    private View rootView;
    private File image_verif = null;
    private File ktp = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_verify_account, container, false);

        Button btn_image_verif = rootView.findViewById(R.id.input_image);
        Button btn_ktp = rootView.findViewById(R.id.input_ktp);
        Button btn_kyc = rootView.findViewById(R.id.btn_kyc);

        btn_image_verif.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                chooseImage(view, 1);
            }
        });

        btn_ktp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    chooseImage(view, 2);
            }
        });

        btn_kyc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestKyc();
            }
        });

        return rootView;
    }

    private void requestKyc() {
        ProgressDialog progressDialog = new ProgressDialog(getContext());
        progressDialog.setMessage("Loading..."); // Set message untuk dialog
        progressDialog.setCancelable(false); // Set apakah dialog bisa di-cancel atau tidak

        progressDialog.show(); // Menampilkan dialog

        Call<GlobalResponse> globalResponseCall = null;

        if (image_verif == null || ktp == null) {
            Toast.makeText(getContext(), "Lengkapi data terlebih dahulu.", Toast.LENGTH_SHORT).show();
            progressDialog.dismiss();
            return;
        }

        File file = new File(image_verif.getPath());
        RequestBody fotoRequestBody = RequestBody.create(file, MediaType.parse("image/jpeg"));
        MultipartBody.Part imagePart = MultipartBody.Part.createFormData("image_verif", file.getName(), fotoRequestBody);

        File file2 = new File(ktp.getPath());
        RequestBody foto2RequestBody = RequestBody.create(file2, MediaType.parse("image/jpeg"));
        MultipartBody.Part image2Part = MultipartBody.Part.createFormData("ktp", file2.getName(), foto2RequestBody);

        globalResponseCall = ApiClient.getUserService(getContext()).verify(
                Preferences.getUserId(getContext()),
                imagePart,
                image2Part
        );

        globalResponseCall.enqueue(new Callback<GlobalResponse>() {
            @Override
            public void onResponse(Call<GlobalResponse> call, Response<GlobalResponse> response) {
                progressDialog.dismiss();
                if (response.isSuccessful()) {
                    GlobalResponse globalResponse = response.body();

                    if (!globalResponse.isError()) {
                        Toast.makeText(getContext(), globalResponse.getMessage(), Toast.LENGTH_SHORT).show();

                        // Tampilkan dialog sukses
                        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(getContext());
                        builder.setTitle("Verifikasi Identitas");
                        builder.setMessage("Verifikasi identitas selesai, silahkan tunggu admin untuk konfirmasi.");
                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // Tindakan setelah tombol OK ditekan, jika diperlukan
                                if (Preferences.getRole(getContext()) == 2) {
                                    OwnerProfileFragment detailJobFragment = new OwnerProfileFragment();
                                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                                    transaction.replace(R.id.frame_layout, detailJobFragment);
                                    transaction.addToBackStack(null);
                                    transaction.commit();
                                } else {
                                    MaidProfileFragment detailJobFragment = new MaidProfileFragment();
                                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                                    transaction.replace(R.id.frame_layout, detailJobFragment);
                                    transaction.addToBackStack(null);
                                    transaction.commit();
                                }
                            }
                        });
                        builder.show();
                    } else {
                        Toast.makeText(getContext(), globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "Gagal meminta verifikasi.", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<GlobalResponse> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(getContext(), "Throwable "+t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void chooseImage(View view, int i) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, i);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
           if (data != null) {
                // Mendapatkan foto yang diambil menggunakan kamera
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                // Menampilkan foto pada ImageView
                showImageDialog(photo, requestCode);
            }
        }
    }

    private void showImageDialog(Bitmap bitmap, int requestCode) {
        Dialog dialog = new Dialog(getContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.preview_image_dialog);

        ImageView dialogImage = dialog.findViewById(R.id.dialog_image);
        dialogImage.setImageBitmap(bitmap);

        dialog.show();

        if (requestCode == 1) {
            image_verif = bitmapToFile(bitmap, requestCode);
        } else {
            ktp = bitmapToFile(bitmap, requestCode);
        }
    }

    public File bitmapToFile(Bitmap bitmap, int requestCode) {
        try {
            // Bitmap resizedBitmap = resizeBitmap(bitmap, 800, 600);

            File file = new File(getContext().getCacheDir(), "temp_image"+requestCode+".png");
            file.createNewFile();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
            byte[] bitmapData = byteArrayOutputStream.toByteArray();

            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(bitmapData);
            fileOutputStream.flush();
            fileOutputStream.close();

            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Bitmap resizeBitmap(Bitmap original, int maxWidth, int maxHeight) {
        int width = original.getWidth();
        int height = original.getHeight();
        float ratioBitmap = (float) width / (float) height;
        float ratioMax = (float) maxWidth / (float) maxHeight;

        int finalWidth = maxWidth;
        int finalHeight = maxHeight;
        if (ratioMax > 1) {
            finalWidth = (int) ((float) maxHeight * ratioBitmap);
        } else {
            finalHeight = (int) ((float) maxWidth / ratioBitmap);
        }
        return Bitmap.createScaledBitmap(original, finalWidth, finalHeight, true);
    }
}