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.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.younki.maidmatching.R;
import com.younki.maidmatching.services.Adapter.ApplicantAdapter;
import com.younki.maidmatching.services.Adapter.ApplicantData;
import com.younki.maidmatching.services.Adapter.JobData;
import com.younki.maidmatching.services.Adapter.RecentApplicantAdapter;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.ApplicantWPResponse;
import com.younki.maidmatching.services.SharedPreference.Preferences;
import com.younki.maidmatching.ui.DetailJobFragment;
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 OwnerHomeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class OwnerHomeFragment 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 OwnerHomeFragment() {
        // 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 OwnerHomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static OwnerHomeFragment newInstance(String param1, String param2) {
        OwnerHomeFragment fragment = new OwnerHomeFragment();
        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_home, container, false);

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

        getApplicant(recyclerView);

        return rootView;
    }

    private void getApplicant(RecyclerView recyclerView) {
        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<ApplicantWPResponse> applicantWPResponseCall = null;
        applicantWPResponseCall = ApiClient.getJobService(getContext()).recentJobApplicant(String.valueOf(Preferences.getUserId(getContext())));

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

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

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

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

                            applicantData[i] = new ApplicantData(
                                    data.getApplicant(),
                                    data.getScore()
                            );
                        }

                        RecentApplicantAdapter applicantAdapter = new RecentApplicantAdapter(applicantData, getContext(), OwnerHomeFragment.this);
                        recyclerView.setAdapter(applicantAdapter);

                        if (dataList.size() == 0) {
                            rootView.findViewById(R.id.recent_applicant_list).setVisibility(View.GONE);
                            rootView.findViewById(R.id.recent_applicant_list_null).setVisibility(View.VISIBLE);
                        } else {
                            rootView.findViewById(R.id.recent_applicant_list).setVisibility(View.VISIBLE);
                            rootView.findViewById(R.id.recent_applicant_list_null).setVisibility(View.GONE);
                        }
                    } else {
                        Toast.makeText(getContext(), "Data Kosong", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getContext(), "Gagal Mengambil Data", Toast.LENGTH_SHORT).show();
                }
            }

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

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

    @Override
    public void onClickedUserData(JobData jobData) {
        BottomNavigationView bottomNavigationView = getActivity().findViewById(R.id.bottomNavigationView);
        bottomNavigationView.setSelectedItemId(R.id.job);

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