package com.younki.maidmatching.ui.maid;

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.JobData;
import com.younki.maidmatching.services.Adapter.JobMaidAdapter;
import com.younki.maidmatching.services.Adapter.JobOwnerAdapter;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.JobResponse;
import com.younki.maidmatching.services.SharedPreference.Preferences;
import com.younki.maidmatching.ui.DetailJobFragment;
import com.younki.maidmatching.ui.owner.OwnerJobFragment;
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 MaidJobFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MaidJobFragment 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 MaidJobFragment() {
        // 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 MaidJobFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MaidJobFragment newInstance(String param1, String param2) {
        MaidJobFragment fragment = new MaidJobFragment();
        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_maid_job, container, false);

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

        getJob(recyclerView, null);

        EditText inputSearch = rootview.findViewById(R.id.cari_job);
        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();
                    getJob(recyclerView, (searchQuery.isEmpty())? "" : searchQuery);
                    return true;
                }
                return false;
            }
        });

        return rootview;
    }

    private void getJob(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

        String user_id = String.valueOf(Preferences.getUserId(getContext()));

        Call<JobResponse> jobResponseCall = null;
        if (search == null || search.isEmpty()) {
            jobResponseCall = ApiClient.getJobService(rootview.getContext()).getUserJobApplied(user_id);
        } else {
            jobResponseCall = ApiClient.getJobService(rootview.getContext()).getUserJobApplied(user_id, search);
        }

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

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

                        // Mengubah List menjadi array JobData[]
                        JobData[] jobData = new JobData[dataList.size()];

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

                            jobData[i] = new JobData(
                                    data.getId(),
                                    data.getUser_id(),
                                    data.getName(),
                                    data.getDescription(),
                                    data.getImage(),
                                    data.getSalary(),
                                    data.getAddress(),
                                    data.getLocation(),
                                    data.getRecommended_age(),
                                    data.getSkills(),
                                    data.getParameters(),
                                    data.getApplicant(),
                                    data.getApplicants(),
                                    data.getRecruit_id(),
                                    data.getAccommodation(),
                                    data.getWorking_days(),
                                    data.getWorking_hours(),
                                    data.getUser_kyc()
                            );
                        }

                        JobMaidAdapter jobAdapter = new JobMaidAdapter(jobData, rootview.getContext(), MaidJobFragment.this);
                        recyclerView.setAdapter(jobAdapter);

                        if (dataList.size() == 0) {
                            rootview.findViewById(R.id.job_list).setVisibility(View.GONE);
                            rootview.findViewById(R.id.job_list_null).setVisibility(View.VISIBLE);
                        } else {
                            rootview.findViewById(R.id.job_list).setVisibility(View.VISIBLE);
                            rootview.findViewById(R.id.job_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<JobResponse> call, Throwable t) {
                progressDialog.dismiss();

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

    @Override
    public void onClickedUserData(JobData jobData) {
        navigateToDetailJobFragment(jobData);
    }

    @Override
    public void onClickedUser() {
        OwnerJobFragment ownerJobFragment = new OwnerJobFragment();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, ownerJobFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    private void navigateToDetailJobFragment(JobData jobData) {
        DetailJobFragment detailJobFragment = new DetailJobFragment(jobData);
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, detailJobFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}