package com.younki.maidmatching.ui.owner;

import static android.content.ContentValues.TAG;

import android.app.ProgressDialog;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.younki.maidmatching.R;
import com.younki.maidmatching.services.Adapter.UserData;
import com.younki.maidmatching.services.Adapter.MaidAdapter;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.UserResponse;
import com.younki.maidmatching.ui.DetailUserFragment;
import com.younki.maidmatching.utils.OnUserClickListener;

import java.util.List;

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

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

    // 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 OwnerMaidFragment() {
        // 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 OwnerMaidFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OwnerMaidFragment newInstance(String param1, String param2) {
        OwnerMaidFragment fragment = new OwnerMaidFragment();
        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;

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

        RecyclerView recyclerView = rootview.findViewById(R.id.maid_list);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(rootview.getContext()));

        getMaid(recyclerView, null);

        EditText inputSearch = rootview.findViewById(R.id.cari_maid);
        inputSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String searchQuery = textView.getText().toString();
                    getMaid(recyclerView, (searchQuery.isEmpty())? "" : searchQuery);
                    return true;
                }
                return false;
            }
        });

        return rootview;
    }

    private void getMaid(RecyclerView recyclerView, String search){
        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

        Call<UserResponse> maidResponseCall = null;
        if (search == null || search.isEmpty()) {
            maidResponseCall = ApiClient.getUserService(rootview.getContext()).getMaid();
        } else {
            maidResponseCall = ApiClient.getUserService(rootview.getContext()).getMaid(search);
        }

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

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

                        // Mengubah List menjadi array UserData[]
                        UserData[] userData = new UserData[dataList.size()];

                        for (int i = 0; i < dataList.size(); i++) {
                            UserResponse.Data data = dataList.get(i);

                            // Ambil data yang diperlukan dari objek data
                            int id = data.getId();
                            int role = data.getRole();
                            String name = data.getName();
                            String username = data.getUsername();
                            String email = data.getEmail();

                            userData[i] = new UserData(id, role, name, username, email, data.getSkill(), data.getProfile());
                        }

                        MaidAdapter maidAdapter = new MaidAdapter(userData, rootview.getContext(), OwnerMaidFragment.this);
                        recyclerView.setAdapter(maidAdapter);

                        if (dataList.size() == 0) {
                            rootview.findViewById(R.id.maid_list).setVisibility(View.GONE);
                            rootview.findViewById(R.id.maid_list_null).setVisibility(View.VISIBLE);
                        } else {
                            rootview.findViewById(R.id.maid_list).setVisibility(View.VISIBLE);
                            rootview.findViewById(R.id.maid_list_null).setVisibility(View.GONE);
                        }
                    } else {
                        Toast.makeText(rootview.getContext(), "Data Kosong", Toast.LENGTH_SHORT).show();
                    }
                } 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());
            }
        });
    }

    @Override
    public void onClickedUserData(UserData userData) {
        navigateToDetailFragment(userData);
    }

    private void navigateToDetailFragment(UserData userData) {
        DetailUserFragment detailUserFragment = DetailUserFragment.newInstance(userData.getId());
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, detailUserFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}