package com.younki.maidmatching.ui.owner;

import static android.app.Activity.RESULT_OK;
import static android.content.ContentValues.TAG;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;

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

import android.provider.MediaStore;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.younki.maidmatching.R;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.GlobalResponse;
import com.younki.maidmatching.services.HTTP.UserResponse;
import com.younki.maidmatching.services.SharedPreference.Preferences;
import com.younki.maidmatching.ui.AddJobDetailDialog;
import com.younki.maidmatching.ui.ChangePasswordFragment;
import com.younki.maidmatching.ui.CompleteProfileDialog;
import com.younki.maidmatching.ui.VerifyAccountFragment;
import com.younki.maidmatching.ui.auth.LoginActivity;
import com.younki.maidmatching.utils.CircleTransform;

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 OwnerProfileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OwnerProfileFragment 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 OwnerProfileFragment() {
        // 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 OwnerProfileFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OwnerProfileFragment newInstance(String param1, String param2) {
        OwnerProfileFragment fragment = new OwnerProfileFragment();
        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 static final int PICK_IMAGE_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private File fotoprofile = null;

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

        getUserDetail(Preferences.getUserId(getContext()));

        RelativeLayout btn_kyc = rootView.findViewById(R.id.kyc);
        btn_kyc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                VerifyAccountFragment detailJobFragment = new VerifyAccountFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.frame_layout, detailJobFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

        RelativeLayout btn_logout = rootView.findViewById(R.id.logout);
        btn_logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                logout(view);
            }
        });

        RelativeLayout btn_change_password = rootView.findViewById(R.id.change_password);
        btn_change_password.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChangePasswordFragment detailJobFragment = new ChangePasswordFragment();
                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                transaction.replace(R.id.frame_layout, detailJobFragment);
                transaction.addToBackStack(null);
                transaction.commit();
            }
        });

        RelativeLayout btn_change_profile = rootView.findViewById(R.id.change_profile);
        btn_change_profile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CompleteProfileDialog completeProfileDialog = new CompleteProfileDialog(getContext());
                completeProfileDialog.setCancelable(true);
                completeProfileDialog.getWindow().setBackgroundDrawable(new ColorDrawable(getContext().getResources().getColor(android.R.color.transparent)));
                completeProfileDialog.show();
            }
        });

        Button editProfileButton = rootView.findViewById(R.id.editprofile);

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

        return rootView;
    }

    private void logout(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
        builder.setTitle("Konfirmasi Logout");
        builder.setMessage("Apakah Anda yakin ingin logout?");
        builder.setPositiveButton("Ya", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Kembali ke halaman login
                Preferences.clearLoggedInUser(view.getContext());
                Activity thisActivity = getActivity();
                thisActivity.finishAfterTransition();

                Intent intent = new Intent(thisActivity, LoginActivity.class);
                startActivity(intent);
            }
        });
        builder.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

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

        progressDialog.show(); // Menampilkan dialog

        TextView name = rootView.findViewById(R.id.name);
        TextView username = rootView.findViewById(R.id.username);
        TextView email = rootView.findViewById(R.id.email);
        TextView phone = rootView.findViewById(R.id.phone);
        TextView address = rootView.findViewById(R.id.address);
//        TextView location = rootView.findViewById(R.id.location);
        TextView birthdate = rootView.findViewById(R.id.birthdate);
        TextView gender = rootView.findViewById(R.id.gender);
        TextView marital_status = rootView.findViewById(R.id.marital_status);
        TextView last_education = rootView.findViewById(R.id.last_education);
//        TextView additional_skills = rootView.findViewById(R.id.additional_skills);
//        TextView desired_salary = rootView.findViewById(R.id.desired_salary);
//        TextView skills = rootView.findViewById(R.id.skills);

        TextView verified = rootView.findViewById(R.id.verified);
        TextView verified_reject = rootView.findViewById(R.id.verified_reject);
        LinearLayout kyc_parent = rootView.findViewById(R.id.kyc_parent);

        Call<UserResponse> userResponseCall = ApiClient.getUserService(rootView.getContext()).getUserDetail(String.valueOf(userId));

        userResponseCall.enqueue(new Callback<UserResponse>() {
            @Override
            public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                progressDialog.dismiss();

                if (response.isSuccessful()){
                    UserResponse userResponse = response.body();

                    name.setText(userResponse.getData().get(0).getName());
                    username.setText("@"+userResponse.getData().get(0).getUsername());
                    email.setText(userResponse.getData().get(0).getEmail());
                    phone.setText(userResponse.getData().get(0).getProfile().getPhone());
                    address.setText(userResponse.getData().get(0).getProfile().getAddress());
//                    location.setText(userResponse.getData().get(0).getProfile().getLocation());
                    birthdate.setText(userResponse.getData().get(0).getProfile().getBirthdate());
                    gender.setText(userResponse.getData().get(0).getProfile().getGender());
                    marital_status.setText(userResponse.getData().get(0).getProfile().getMarital_status());
                    last_education.setText(userResponse.getData().get(0).getProfile().getLast_education());
//                    additional_skills.setText(userResponse.getData().get(0).getProfile().getAdditional_skills());
//                    desired_salary.setText(userResponse.getData().get(0).getProfile().getDesired_salary());

                    int kyc = userResponse.getData().get(0).getProfile().getKyc();

                    if (kyc == 2) {
                        verified.setVisibility(View.VISIBLE);
                        verified_reject.setVisibility(View.GONE);
                        kyc_parent.setVisibility(View.GONE);
                    } else if (kyc == 3){
                        verified_reject.setVisibility(View.VISIBLE);
                        verified.setVisibility(View.GONE);
                    } else {
                        verified.setVisibility(View.GONE);
                        verified_reject.setVisibility(View.GONE);
                    }

//                    String html = "<html><ul>";
//                    for (int i = 0; i < userResponse.getData().get(0).getSkill().size(); i++) {
//                        html += "<li>"+userResponse.getData().get(0).getSkill().get(i).getName()+"</li>";
//                    }
//                    html += "</ul></html>";
//                    skills.setText(Html.fromHtml(html));
                    Picasso.get().load(ApiClient.getBaseUrl()+userResponse.getData().get(0).getProfile().getImage())
                            .transform(new CircleTransform())
                            .into((ImageView) rootView.findViewById(R.id.profile));
                } else {
                    Toast.makeText(rootView.getContext(), "Gagal Mengambil Data", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<UserResponse> call, Throwable t) {
                progressDialog.dismiss();

                String errorMessage = t.getMessage();
                Log.e(TAG, "onFailure: "+t.getMessage());
            }
        });
    }

    public void chooseImage(View view) {
        final CharSequence[] options = {"Ambil dari Galeri", "Ambil Foto"};

        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(getContext());
        builder.setTitle("Pilih Foto");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        // Memilih foto dari galeri
                        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(galleryIntent, PICK_IMAGE_REQUEST);
                        break;
                    case 1:
                        // Mengambil foto dengan kamera
                        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(cameraIntent, CAMERA_REQUEST);
                        break;
                }
            }
        });
        builder.show();
    }

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

        if (resultCode == RESULT_OK) {
            if (requestCode == PICK_IMAGE_REQUEST && data != null) {
                // Mendapatkan URI dari gambar yang dipilih dari galeri
                Uri selectedImageUri = data.getData();
                try {
                    // Mengubah URI menjadi Bitmap
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), selectedImageUri);
                    // Menampilkan gambar pada ImageView
                    showImageDialog(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (requestCode == CAMERA_REQUEST && data != null) {
                // Mendapatkan foto yang diambil menggunakan kamera
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                // Menampilkan foto pada ImageView
                showImageDialog(photo);
            }
        }
    }

    private void showImageDialog(Bitmap bitmap) {
        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();

        fotoprofile = bitmapToFile(bitmap);

        updateProfile();
    }

    private void updateProfile() {
        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 (fotoprofile == null) {
            Toast.makeText(getContext(), "Harap Upload Image Terlebih Dahulu.", Toast.LENGTH_SHORT).show();
            return;
        }

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

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

        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("Update Profile");
                        builder.setMessage("Berhasil Mengubah Profile.");
                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // Tindakan setelah tombol OK ditekan, jika diperlukan
                                OwnerProfileFragment ownerProfileFragment = new OwnerProfileFragment();
                                FragmentTransaction transaction = getFragmentManager().beginTransaction();
                                transaction.replace(R.id.frame_layout, ownerProfileFragment);
                                transaction.addToBackStack(null);
                                transaction.commit();
                            }
                        });
                        builder.show();
                    } else {
                        Toast.makeText(getContext(), globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "Gagal Mengubah profile.", 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 File bitmapToFile(Bitmap bitmap) {
        try {
            File file = new File(getContext().getCacheDir(), "temp_image.jpg");
            file.createNewFile();

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 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;
        }
    }
}