package com.younki.maidmatching.ui;

import static android.content.ContentValues.TAG;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
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.text.Html;
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.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
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.JobAdapter;
import com.younki.maidmatching.services.Adapter.JobData;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.ApplicantWPResponse;
import com.younki.maidmatching.services.HTTP.GlobalResponse;
import com.younki.maidmatching.services.HTTP.ApplicantWPResponse;
import com.younki.maidmatching.ui.maid.MaidHomeFragment;
import com.younki.maidmatching.ui.owner.OwnerJobFragment;
import com.younki.maidmatching.utils.OnUserClickListener;

import java.io.Serializable;
import java.text.NumberFormat;
import java.util.List;
import java.util.Locale;

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

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DetailJobFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DetailJobFragment 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 = "user_id";
    private JobData jobData;

    public DetailJobFragment(JobData jobData) {
        // Required empty public constructor
        this.jobData = jobData;
    }

    public static DetailJobFragment newInstance(JobData jobData) {
        DetailJobFragment fragment = new DetailJobFragment(jobData);
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            jobData = (JobData) getArguments().getSerializable(ARG_PARAM1);
        }
    }

    private View rootView;
    TextView salary, name, applicant, recommended_age, description, address, skills, accommodation, working_days, working_hours, param_age, param_salary, param_distance, param_skill;
    ImageView job_image, btn_delete;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        rootView = inflater.inflate(R.layout.fragment_detail_job, container, false);
        NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("id", "ID"));

        salary = rootView.findViewById(R.id.salary);
        name = rootView.findViewById(R.id.name);
        applicant = rootView.findViewById(R.id.applicant);
        recommended_age = rootView.findViewById(R.id.recommended_age);
        description = rootView.findViewById(R.id.description);
        address = rootView.findViewById(R.id.address);
        job_image = rootView.findViewById(R.id.job_image);
        btn_delete = rootView.findViewById(R.id.btn_delete);
        skills = rootView.findViewById(R.id.skills);
        accommodation = rootView.findViewById(R.id.accommodation);
        working_days = rootView.findViewById(R.id.working_days);
        working_hours = rootView.findViewById(R.id.working_hours);

        accommodation.setText(jobData.getAccommodation());
        working_days.setText(jobData.getWorking_days());
        working_hours.setText("Hari Kerja: ("+jobData.getWorking_hours()+" Jam/Hari)");
        salary.setText(formatter.format(Integer.valueOf(jobData.getSalary())));
        name.setText(jobData.getName());
        applicant.setText("Apply: "+jobData.getApplicant());
        recommended_age.setText("Rentang Umur: "+jobData.getRecommended_age());
        description.setText(jobData.getDescription());
        address.setText(jobData.getAddress());
        Picasso.get().load(ApiClient.getBaseUrl()+jobData.getImage()).into(job_image);

        String html = "<html><ul>";
        for (int i = 0; i < jobData.getSkills().size(); i++) {
            html += "<li>"+jobData.getSkills().get(i).getName()+"</li>";
        }
        html += "</ul></html>";
        skills.setText(Html.fromHtml(html));

        param_age = rootView.findViewById(R.id.param_age);
        param_salary = rootView.findViewById(R.id.param_salary);
        param_skill = rootView.findViewById(R.id.param_skill);
        param_distance = rootView.findViewById(R.id.param_distance);

        param_age.setText(jobData.getParameters().get(0).getWeight());
        param_salary.setText(jobData.getParameters().get(1).getWeight());
        param_skill.setText(jobData.getParameters().get(2).getWeight());
        param_distance.setText(jobData.getParameters().get(3).getWeight());

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

        getApplicant(recyclerView, null);

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

        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new AlertDialog.Builder(getContext())
                        .setTitle("Hapus Job")
                        .setMessage("Apakah Anda yakin ingin menghapus job ini?")
                        .setPositiveButton("Ya", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteJob(getContext(), jobData.getId());
                            }
                        })
                        .setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
            }
        });

        return rootView;
    }
    private void getApplicant(RecyclerView recyclerView, String search) {
        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;
        if (search == null || search.isEmpty()) {
            applicantWPResponseCall = ApiClient.getJobService(getContext()).jobApplicantWP(String.valueOf(jobData.getId()));
        } else {
            applicantWPResponseCall = ApiClient.getJobService(getContext()).jobApplicantWP(String.valueOf(jobData.getId()), search);
        }

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

                        ApplicantAdapter applicantAdapter = new ApplicantAdapter(applicantData, getContext(), DetailJobFragment.this, jobData);
                        recyclerView.setAdapter(applicantAdapter);

                        if (dataList.size() == 0) {
                            rootView.findViewById(R.id.applicant_list).setVisibility(View.GONE);
                            rootView.findViewById(R.id.applicant_list_null).setVisibility(View.VISIBLE);
                        } else {
                            rootView.findViewById(R.id.applicant_list).setVisibility(View.VISIBLE);
                            rootView.findViewById(R.id.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());
            }
        });
    }
    private void deleteJob(Context context, int id) {
        ProgressDialog progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("Loading..."); // Set message untuk dialog
        progressDialog.setCancelable(false); // Set apakah dialog bisa di-cancel atau tidak

        progressDialog.show(); // Menampilkan dialog

        Call<GlobalResponse> globalResponseCall = null;

        globalResponseCall = ApiClient.getJobService(context).deleteJob(String.valueOf(id));
        globalResponseCall.enqueue(new Callback<GlobalResponse>() {
            @Override
            public void onResponse(Call<GlobalResponse> call, Response<GlobalResponse> response) {
                progressDialog.dismiss();
                if (response.isSuccessful()) {
                    GlobalResponse globalResponse = response.body();

                    if (!globalResponse.isError()) {
                        Toast.makeText(context, globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(context, globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    OwnerJobFragment ownerJobFragment = new OwnerJobFragment();
                    FragmentTransaction transaction = getFragmentManager().beginTransaction();
                    transaction.replace(R.id.frame_layout, ownerJobFragment);
                    transaction.addToBackStack(null);
                    transaction.commit();
                } else {
                    Toast.makeText(context, "Gagal Menghapus Job.", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onFailure(Call<GlobalResponse> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(context, "Throwable "+t.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onClickedUser(ApplicantData applicantData) {
        DetailUserFragment detailUserFragment = DetailUserFragment.newInstance(applicantData.getApplicant().getUser_id());
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        transaction.replace(R.id.frame_layout, detailUserFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

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