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.Toast;

import androidx.annotation.NonNull;

import com.google.gson.JsonArray;
import com.younki.maidmatching.R;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.GlobalResponse;
import com.younki.maidmatching.services.HTTP.AddSkillRequest;
import com.younki.maidmatching.services.HTTP.SkillResponse;
import com.younki.maidmatching.services.SharedPreference.Preferences;

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

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

public class AddMaidSkillDialog extends Dialog {
    private static AddMaidSkillDialog activeDialog;
    public AddMaidSkillDialog(@NonNull Context context) {
        super(context);
    }

    public static AddMaidSkillDialog 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();
        }
    }

    String[] skills = {"Memasak", "Bersih-Bersih", "Hias Kebun", "Mencuci", "Momong Anak/Baby Sister"};

    ArrayAdapter<String> skillAdapter;

    ListView listSkill;

    Button btnSvSkill;

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

        getSkills();

        btnSvSkill = findViewById(R.id.btn_sv_skill);
        btnSvSkill.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setSkills();
            }
        });
    }

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

    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.getUserService(getContext()).userSkills(
                jobSkillRequest, String.valueOf(Preferences.getUserId(getContext()))
        );

        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()) {
                        Preferences.setUserSkills(getContext(), 1);
                        AddMaidSkillDialog.getActiveDialog().dismiss();
                        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();
            }
        });
    }

}