package com.younki.maidmatching.ui;

import android.Manifest;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.younki.maidmatching.R;
import com.younki.maidmatching.services.ApiClient;
import com.younki.maidmatching.services.HTTP.AddDetailRequest;
import com.younki.maidmatching.services.HTTP.GlobalResponse;
import com.younki.maidmatching.services.HTTP.RegisterRequest;
import com.younki.maidmatching.services.SharedPreference.Preferences;
import com.younki.maidmatching.ui.auth.LoginActivity;
import com.younki.maidmatching.ui.auth.RegisterAsMaidActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.PrivateKey;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

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

public class CompleteProfileDialog extends Dialog implements OnMapReadyCallback {
    private static CompleteProfileDialog activeDialog;
    private Context context;
    public CompleteProfileDialog(@NonNull Context context) {
        super(context);
        this.context = context;
    }

    public static CompleteProfileDialog getActiveDialog() {
        return activeDialog;
    }

    @Override
    protected void onStart() {
        super.onStart();

        // set activeDialog ke instance dari dialog yang sedang aktif
        activeDialog = this;
    }

    @Override
    protected void onStop() {
        super.onStop();

        // set activeDialog ke null ketika dialog tidak lagi aktif
        activeDialog = null;
        handler.removeCallbacks(locationRunnable); // Hentikan Handler
    }

    @Override
    public void setOnDismissListener(@Nullable OnDismissListener listener) {
        super.setOnDismissListener(listener);
        handler.removeCallbacks(locationRunnable); // Hentikan Handler
    }

    public void dissmissDialog() {
        // cek apakah dialog sedang aktif
        if (activeDialog != null) {
            // dialog sedang aktif, lakukan sesuatu di sini
            dismiss();
        }
    }

    private EditText inputBirthdate, additional_skills, desired_salary;
    private Spinner genderSpinner, educationSpinner, maritalSpinner;

    private Button btnSvProfile;

    private int tahun,bulan,tanggal;

    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1001;
    private MapView mapView;
    private GoogleMap googleMap;
    private FusedLocationProviderClient fusedLocationClient;
    private Handler handler = new Handler();
    private Runnable locationRunnable;
    final String[] currentLocation = {"Lokasi terkini belum didapatkan"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.complete_profile_dialog);

        fusedLocationClient = LocationServices.getFusedLocationProviderClient(context);

        mapView = findViewById(R.id.user_location_map);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);

        // Get Current Location
        locationRunnable = new Runnable() {
            @Override
            public void run() {
                getLastLocation();
                handler.postDelayed(this, 5000);
            }
        };
        handler.post(locationRunnable);

        additional_skills = findViewById(R.id.additional_skill);
        desired_salary = findViewById(R.id.desired_salary);

        if (Preferences.getRole(context) == 3) {
            additional_skills.setVisibility(View.VISIBLE);
            desired_salary.setVisibility(View.VISIBLE);
        }

        inputBirthdate = findViewById(R.id.birthdate);
        inputBirthdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b == true){
                    Calendar calendar = Calendar.getInstance();
                    tahun = calendar.get(Calendar.YEAR);
                    bulan = calendar.get(Calendar.MONTH);
                    tanggal = calendar.get(Calendar.DAY_OF_MONTH);

                    DatePickerDialog dialog;
                    dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                            tahun = year;
                            bulan = month;
                            tanggal = dayOfMonth;

                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                            Calendar calendar = Calendar.getInstance();
                            calendar.set(tahun, bulan, tanggal);
                            String formattedDate = dateFormat.format(calendar.getTime());

                            inputBirthdate.setText(formattedDate);
                        }
                    },tahun,bulan,tanggal);
                    dialog.show();
                }
            }
        });
        inputBirthdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                tahun = calendar.get(Calendar.YEAR);
                bulan = calendar.get(Calendar.MONTH);
                tanggal = calendar.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog;
                dialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        tahun = year;
                        bulan = month;
                        tanggal = dayOfMonth;

                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                        Calendar calendar = Calendar.getInstance();
                        calendar.set(tahun, bulan, tanggal);
                        String formattedDate = dateFormat.format(calendar.getTime());

                        inputBirthdate.setText(formattedDate);
                    }
                },tahun,bulan,tanggal);
                dialog.show();
            }
        });

        maritalSpinner = findViewById(R.id.spinner_marital_status);
        ArrayAdapter<CharSequence> maritalAdapter = ArrayAdapter.createFromResource(context,
                R.array.marital_status, android.R.layout.simple_spinner_item);
        maritalAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        maritalSpinner.setAdapter(maritalAdapter);

        genderSpinner = findViewById(R.id.spinner_gender);
        ArrayAdapter<CharSequence> genderAdapter = ArrayAdapter.createFromResource(context,
                R.array.gender_arrays, android.R.layout.simple_spinner_item);
        genderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        genderSpinner.setAdapter(genderAdapter);

        educationSpinner = findViewById(R.id.spinner_education);
        ArrayAdapter<CharSequence> educationAdapter = ArrayAdapter.createFromResource(context,
                R.array.education_arrays, android.R.layout.simple_spinner_item);
        educationAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        educationSpinner.setAdapter(educationAdapter);

        btnSvProfile = findViewById(R.id.btn_sv_profile);
        btnSvProfile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setDetail();
            }
        });
    }

    @Override
    public void onPanelClosed(int featureId, @NonNull Menu menu) {
        super.onPanelClosed(featureId, menu);
        handler.removeCallbacks(locationRunnable); // Hentikan Handler
    }

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        this.googleMap = googleMap;
    }

    private void getLastLocation() {
        Activity activity = context instanceof Activity ? (Activity) context : null;
        if (activity != null) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED &&
                    ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                fusedLocationClient.requestLocationUpdates(LocationRequest.create(), locationCallback, Looper.getMainLooper());
                fusedLocationClient.getLastLocation()
                        .addOnSuccessListener((Activity) context, new OnSuccessListener<Location>() {
                            @Override
                            public void onSuccess(Location location) {
                                Log.e("TAG", "getLastLocation: "+location);
                                if (location != null) {
                                    googleMap.clear();
                                    LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
                                    googleMap.addMarker(new MarkerOptions().position(userLocation).title("You are here"));
                                    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));

                                    TextView txt_location = findViewById(R.id.txt_location);

                                    String latlngval = String.valueOf(userLocation);

                                    latlngval = latlngval.replace("lat/lng: ", "");

                                    String[] values = latlngval.split(",");
                                    double lat = Double.parseDouble(values[0].replace("(", ""));
                                    double lng = Double.parseDouble(values[1].replace(")", ""));

                                    JSONObject coordinates = new JSONObject();
                                    try {
                                        coordinates.put("lat", lat);
                                        coordinates.put("lng", lng);
                                    } catch (JSONException e) {
                                        throw new RuntimeException(e);
                                    }

                                    txt_location.setText(coordinates.toString());
                                } else {
                                    Toast.makeText(context, "Location not available", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
            } else {
                ActivityCompat.requestPermissions((Activity) context,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        LOCATION_PERMISSION_REQUEST_CODE);

                ActivityCompat.requestPermissions((Activity) context,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        123);
            }
        } else {
            Toast.makeText(context, "Null", Toast.LENGTH_SHORT).show();
        }
    }

    private LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            super.onLocationResult(locationResult);
            Location location = locationResult.getLastLocation();
            Log.e("TAG", "onLocationResult: "+location);
            if (location != null) {
                googleMap.clear();
                LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
                googleMap.addMarker(new MarkerOptions().position(userLocation).title("You are here"));
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));

                TextView txt_location = findViewById(R.id.txt_location);

                String latlngval = String.valueOf(userLocation);

                latlngval = latlngval.replace("lat/lng: ", "");

                String[] values = latlngval.split(",");
                double lat = Double.parseDouble(values[0].replace("(", ""));
                double lng = Double.parseDouble(values[1].replace(")", ""));

                JSONObject coordinates = new JSONObject();
                try {
                    coordinates.put("lat", lat);
                    coordinates.put("lng", lng);
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                txt_location.setText(coordinates.toString());
            } else {
                Toast.makeText(context, "Location not available", Toast.LENGTH_SHORT).show();
            }
        }
    };

    private void setDetail() {
        EditText phone, address, birthdate;
        phone = findViewById(R.id.phone);
        address = findViewById(R.id.address);
        birthdate = findViewById(R.id.birthdate);

        String gender = genderSpinner.getSelectedItem().toString();
        String last_education = educationSpinner.getSelectedItem().toString();
        String marital_status = maritalSpinner.getSelectedItem().toString();

        TextView location = findViewById(R.id.txt_location);

        AddDetailRequest addDetailRequest = new AddDetailRequest();
        addDetailRequest.setPhone(phone.getText().toString());
        addDetailRequest.setAddress(address.getText().toString());
        addDetailRequest.setBirthdate(birthdate.getText().toString());
        addDetailRequest.setGender(gender);
        addDetailRequest.setMarital_status(marital_status);
        addDetailRequest.setLast_education(last_education);
        addDetailRequest.setLocation(location.getText().toString());
        addDetailRequest.setDesired_salary(desired_salary.getText().toString());
        addDetailRequest.setAdditional_skills(additional_skills.getText().toString());

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

        Call<GlobalResponse> globalResponseCall = ApiClient.getUserService(context).userDetails(addDetailRequest, String.valueOf(Preferences.getUserId(context)));
        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();
                        Preferences.setUserStatus(context, 2);
                        Preferences.setUserLocation(context, location.getText().toString());
                        CompleteProfileDialog.getActiveDialog().dismiss();
                    } else {
                        Toast.makeText(context, globalResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(context, "Detail Gagal Ditambahkan.", Toast.LENGTH_SHORT).show();
                }
            }

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

}
