package com.younki.maidmatching.services.Adapter;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;
import com.younki.maidmatching.R;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.GlobalResponse;
import com.younki.maidmatching.services.HTTP.JobApplicantRequest;
import com.younki.maidmatching.services.SharedPreference.Preferences;
import com.younki.maidmatching.ui.ShowDetailJobDialog;
import com.younki.maidmatching.utils.OnUserClickListener;

import java.text.NumberFormat;
import java.util.Locale;

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

public class JobAdapter extends RecyclerView.Adapter<JobAdapter.ViewHolder> {

    JobData[] jobData;
    Context context;
    OnUserClickListener onUserClickListener;

    public JobAdapter(JobData[] jobData, Context context, OnUserClickListener onUserClickListener) {
        this.jobData = jobData;
        this.context = context;
        this.onUserClickListener = onUserClickListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View view = layoutInflater.inflate(R.layout.adapter_job_maid_list,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        final Context context = holder.itemView.getContext();
        final JobData jobDataList = jobData[position];
        NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("id", "ID"));

        holder.salary.setText(formatter.format(Integer.valueOf(jobDataList.getSalary())));
        holder.name.setText(jobDataList.getName());
        holder.applicant.setText("Pelamar: "+jobDataList.getApplicant());
        holder.recommended_age.setText("Rentang Umur: "+jobDataList.getRecommended_age());
        Picasso.get().load(ApiClient.getBaseUrl()+jobDataList.getImage()).into(holder.job_image);

        if (jobDataList.getUser_kyc() == 2) {
            holder.verified.setVisibility(View.VISIBLE);
        } else {
            holder.verified.setVisibility(View.GONE);
        }

        boolean isApplicant = false;
        for (int i = 0; i < jobDataList.getApplicants().size(); i++) {
            if (jobDataList.getApplicants().get(i).getUser_id() == Preferences.getUserId(context)) {
                isApplicant = true;
                break;
            }
        }

        if (isApplicant) {
            holder.btn_apply.setEnabled(false);
            holder.btn_apply.setText("Selesai");
            holder.btn_apply.setBackgroundColor(Color.parseColor("#000000")); // Mengatur warna latar belakang menjadi hitam
            holder.btn_apply.setTextColor(Color.parseColor("#FFFFFF")); // Mengatur warna teks menjadi putih
        }

        holder.btn_apply.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                applyJob(jobDataList);
            }
        });

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Buka Dialog
                ShowDetailJobDialog showDetailJobDialog = new ShowDetailJobDialog(v.getContext(), jobDataList);
                showDetailJobDialog.setCancelable(true);
                showDetailJobDialog.getWindow().setBackgroundDrawable(new ColorDrawable(v.getResources().getColor(android.R.color.transparent)));
                showDetailJobDialog.show();
            }
        });
    }

    private void applyJob(JobData jobData) {
        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;

        // Calculate Distance
//        String job_location = jobData.getLocation();
//        String user_location = Preferences.getUserLocation(context);

        JobApplicantRequest jobApplicantRequest = new JobApplicantRequest();
        jobApplicantRequest.setUser_id(Preferences.getUserId(context));

        globalResponseCall = ApiClient.getJobService(context).jobApplicant(
                jobApplicantRequest, String.valueOf(jobData.getId())
        );

        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();
                        onUserClickListener.onClickedUser();
                    } else {
                        Toast.makeText(context, globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "Gagal mendaftar ke job yang dipilih.", 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 int getItemCount() {
        return jobData.length;
    }

    public class ViewHolder extends RecyclerView.ViewHolder{
        TextView salary, name, applicant, recommended_age, verified;
        ImageView job_image;
        Button btn_apply;
        int userId;
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            salary = itemView.findViewById(R.id.salary);
            name = itemView.findViewById(R.id.name);
            applicant = itemView.findViewById(R.id.applicant);
            verified = itemView.findViewById(R.id.verified);
            recommended_age = itemView.findViewById(R.id.recommended_age);

            job_image = itemView.findViewById(R.id.job_image);
            btn_apply = itemView.findViewById(R.id.btn_apply);
        }
    }
}