package com.younki.maidmatching.ui;

import static android.content.ContentValues.TAG;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentTransaction;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.younki.maidmatching.R;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.GlobalResponse;
import com.younki.maidmatching.services.HTTP.JobParameterRequest;
import com.younki.maidmatching.services.HTTP.AddSkillRequest;
import com.younki.maidmatching.services.HTTP.SkillResponse;
import com.younki.maidmatching.ui.owner.OwnerCreateJobFragment;
import com.younki.maidmatching.ui.owner.OwnerJobFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class AddJobDetailDialog extends Dialog {
    private static AddJobDetailDialog activeDialog;
    private Context context;
    private int jobId;
    public AddJobDetailDialog(@NonNull Context context, Integer jobId) {
        super(context);
        this.context = context;
        this.jobId = jobId;
    }

    public static AddJobDetailDialog getActiveDialog() {
        return activeDialog;
    }

    @Override
    protected void onStart() {
        super.onStart();

        // set activeDialog ke instance dari dialog yang sedang aktif
        activeDialog = this;
    }

    @Override
    protected void onStop() {
        super.onStop();

        // set activeDialog ke null ketika dialog tidak lagi aktif
        activeDialog = null;
    }

    public void dissmissDialog() {
        // cek apakah dialog sedang aktif
        if (activeDialog != null) {
            // dialog sedang aktif, lakukan sesuatu di sini
            dismiss();
        }
    }

    ArrayAdapter<String> skillAdapter;

    ListView listSkill;

    Button btnSvSkill;
    private Spinner spinner_umur, spinner_gaji, spinner_skill, spinner_jarak;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_job_detail_dialog);

        getSkills();

        spinner_umur = findViewById(R.id.spinner_umur);
        setSpinnerParameterAdapter(spinner_umur);

        spinner_gaji = findViewById(R.id.spinner_gaji);
        setSpinnerParameterAdapter(spinner_gaji);

        spinner_skill = findViewById(R.id.spinner_skill);
        setSpinnerParameterAdapter(spinner_skill);

        spinner_jarak = findViewById(R.id.spinner_jarak);
        setSpinnerParameterAdapter(spinner_jarak);

        btnSvSkill = findViewById(R.id.btn_sv_job_detail);
        btnSvSkill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setParameter();
                setSkills();
                AddJobDetailDialog.getActiveDialog().dismiss();
            }
        });
    }

    private void setParameter() {
        Call<GlobalResponse> globalResponseCall = null;
        Map<String, String[]> parameters = new HashMap<>();
        parameters.put("1", new String[]{"umur", spinner_umur.getSelectedItem().toString()});
        parameters.put("2", new String[]{"gaji", spinner_gaji.getSelectedItem().toString()});
        parameters.put("3", new String[]{"skill", spinner_skill.getSelectedItem().toString()});
        parameters.put("4", new String[]{"jarak", spinner_jarak.getSelectedItem().toString()});

        List<Map<String, String>> parameterList = new ArrayList<>();
        for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
            Map<String, String> parameter = new HashMap<>();
            parameter.put("parameter_id", entry.getKey());
            parameter.put("weight", entry.getValue()[1]);
            parameterList.add(parameter);
        }

        JsonArray jsonArray = new JsonArray();
        for (Map<String, String> parameter : parameterList) {
            JsonObject jsonObject = new JsonObject();
            for (Map.Entry<String, String> entry : parameter.entrySet()) {
                jsonObject.addProperty(entry.getKey(), entry.getValue());
            }
            jsonArray.add(jsonObject);
        }

        JobParameterRequest jobParameterRequest = new JobParameterRequest();
        jobParameterRequest.setParameters(jsonArray);

        globalResponseCall = ApiClient.getJobService(getContext()).jobParameter(
                jobParameterRequest, String.valueOf(jobId)
        );

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

                    if (!globalResponse.isError()) {
                        Toast.makeText(getContext(), globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "Gagal Menambahkan Parameter Job.", 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();
            }
        });
    }

    private void setSkills() {
        Call<GlobalResponse> globalResponseCall = null;

        // Ambil data dari listSkill yang dicentang
        SparseBooleanArray checkedItems = listSkill.getCheckedItemPositions();
        String[] selectedSkills = new String[checkedItems.size()];
        for (int i = 0; i < checkedItems.size(); i++) {
            int position = checkedItems.keyAt(i);
            if (checkedItems.get(position)) {
                String[] skillData = skillAdapter.getItem(position).split(".] ");
                selectedSkills[i] = skillData[0].trim();
            }
        }

        JsonArray jsonArray = new JsonArray();
        for (String skill : selectedSkills) {
            jsonArray.add(skill);
        }

        AddSkillRequest jobSkillRequest = new AddSkillRequest();
        jobSkillRequest.setSkills(jsonArray);

        globalResponseCall = ApiClient.getJobService(getContext()).jobSkills(
                jobSkillRequest, String.valueOf(jobId)
        );

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

                    if (!globalResponse.isError()) {
                        Toast.makeText(getContext(), globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "Gagal Menambahkan Skill Job.", 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();
            }
        });
    }

    private void getSkills() {
        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<SkillResponse> skillResponseCall = null;
        skillResponseCall = ApiClient.getSkillService(getContext()).getSkill();

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

                if (response.isSuccessful()){
                    SkillResponse skillResponse = response.body();
                    if (skillResponse != null) {
                        List<SkillResponse.Data> dataList = skillResponse.getData();

                        Map<Integer, String> skillMap = new HashMap<>();

                        for (int i = 0; i < dataList.size(); i++) {
                            SkillResponse.Data data = dataList.get(i);
                            skillMap.put(data.getId(), data.getName());
                        }

                        String[] skills = new String[skillMap.size()];
                        int i = 0;
                        for (Map.Entry<Integer, String> entry : skillMap.entrySet()) {
                            skills[i] = entry.getKey() + ".] " + entry.getValue();
                            i++;
                        }

                        listSkill = findViewById(R.id.skill_list);
                        skillAdapter = new ArrayAdapter<String>(getContext(),
                                android.R.layout.simple_list_item_multiple_choice, skills);
                        listSkill.setAdapter(skillAdapter);

                    } else {
                        Toast.makeText(getContext(), "Data Skill Kosong", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "Gagal Mengambil Data", Toast.LENGTH_SHORT).show();
                }
            }

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

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

    public void setSpinnerParameterAdapter(Spinner spinner){
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
                R.array.parameter_arrays, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }

}
