package uprrp.tania.activities;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Objects;

import uprrp.tania.GlobalValues;
import uprrp.tania.R;
import uprrp.tania.networking.SendUserRegistration;
import uprrp.tania.models.UserModel;
import uprrp.tania.utils.URLEventListener;

public class UserRegistrationActivity extends AppCompatActivity {

    private static final String TAG = "RegisterActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Constructor stuff
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_registration);

        // Set onClick listener for the birth date text
        // TODO: should change UI to use an actual datePicker instead of this garbage
        final TextView birthDateText = findViewById(R.id.birthDateText);
        birthDateText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                openDatePickerNew();
            }
        });

        // Change all caps text to normal capitalization and add onClick listener
        final Button buttonRegister = findViewById(R.id.registerButton);
        buttonRegister.setTransformationMethod(null); // TODO: this is a workaround I found, any other acceptable solution is welcome
        buttonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRegistrationData();
            }
        });

    }

    private void openDatePickerNew() {
        final TextView birthDateText = findViewById(R.id.birthDateText);

        DatePickerDialog dialog = new DatePickerDialog(UserRegistrationActivity.this, android.R.style.Theme_Holo_Light_Dialog_MinWidth);
        dialog.setOnDateSetListener(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int day) {
                month = month + 1; // 0-indexed month
                Log.d(TAG, "onDateSet: mm/dd/yyy: " + month + "/" + day + "/" + year);
                String date = month + "/" + day + "/" + year;
                birthDateText.setText(date);
            }
        });

        // Remove ugly border
        Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        dialog.show();
    }

    private boolean validInputs() {

        final EditText nameEditText = findViewById(R.id.nameEditText);
        final TextView birthDateText = findViewById(R.id.birthDateText);

        final RadioButton maleGender = findViewById(R.id.maleRadioButton);
        final RadioButton femaleGender = findViewById(R.id.femaleRadioButton);
        final RadioButton notSpecifyGender = findViewById(R.id.notSayRadioButton);
        final RadioButton otherGender = findViewById(R.id.otherRadioButton);

        final RadioButton partTime = findViewById(R.id.partTimeRadioButton);
        final RadioButton fullTime = findViewById(R.id.fullTimeRadioButton);
        final RadioButton noJob = findViewById(R.id.noJobRadioButton);

        final EditText emailText = findViewById(R.id.emailText);
        final EditText passwordText = findViewById(R.id.passwordText);

        if(nameEditText.getText().toString().equals("")) {
            return false;
        }

        if(birthDateText.getText().toString().equals("")) {
            return false;
        }

        if(emailText.getText().toString().equals("")) {
            return false;
        }

        if(passwordText.getText().toString().equals("")) {
            return false;
        }

        // Genders
        if(!(maleGender.isChecked() || femaleGender.isChecked() || notSpecifyGender.isChecked() || otherGender.isChecked())) {
            return false;
        }

        // Job Field
        if(!(partTime.isChecked() || fullTime.isChecked() || noJob.isChecked())) {
            return false;
        }

        return true;
    }

    private void sendRegistrationData() {

        final EditText nameEditText = findViewById(R.id.nameEditText);
        final TextView birthDateText = findViewById(R.id.birthDateText);

        final RadioButton maleGender = findViewById(R.id.maleRadioButton);
        final RadioButton femaleGender = findViewById(R.id.femaleRadioButton);
        final RadioButton notSpecifyGender = findViewById(R.id.notSayRadioButton);
        final RadioButton otherGender = findViewById(R.id.otherRadioButton);

        final RadioButton partTime = findViewById(R.id.partTimeRadioButton);
        final RadioButton fullTime = findViewById(R.id.fullTimeRadioButton);
        final RadioButton noJob = findViewById(R.id.noJobRadioButton);

        final EditText emailText = findViewById(R.id.emailText);
        final EditText passwordText = findViewById(R.id.passwordText);


        if(this.validInputs()) {

            // Extract fields
            String name = nameEditText.getText().toString();
            String birthDate = birthDateText.getText().toString();
            String email = emailText.getText().toString();
            String password = passwordText.getText().toString();
            String deviceToken = GlobalValues.getInstance().getDeviceToken();

            String genderText;
            if(maleGender.isChecked()) {
                genderText = "Male";
            } else if (femaleGender.isChecked()) {
                genderText = "Female";
            } else if (notSpecifyGender.isChecked()) {
                genderText = "Prefer not to say";
            } else if (otherGender.isChecked()){
                genderText = "Other";
            } else {
                Log.wtf(TAG, "Unknown radio button case for gender!");
                genderText = "Other";
            }

            String jobType;
            if(partTime.isChecked()) {
                jobType = "Part time";
            } else if (fullTime.isChecked()) {
                jobType = "Full time";
            } else if (noJob.isChecked()) {
                jobType = "No job";
            } else {
                Log.wtf(TAG, "Unknown radio button case for job type!");
                jobType = "No job";
            }

            // Save name in preferences
            SharedPreferences prefs = getSharedPreferences("prefs", MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putString("consentName", name);
            editor.apply();

            // Send registration request
            UserModel user = new UserModel(birthDate, email, password, genderText, jobType, deviceToken);
            this.sendUserRegistrationRequest(user);

        } else {
            Toast.makeText(UserRegistrationActivity.this, "All fields are required!", Toast.LENGTH_LONG).show();
        }

    }

    private void sendUserRegistrationRequest(UserModel user) {

        // Initiate progress dialog
        // TODO: find substitute for this deprecated dialog box
        final ProgressDialog progressDialog = ProgressDialog.show(UserRegistrationActivity.this,
                "Registering User",
                getString(R.string.progressDialogDescriptionText));

        // Send registration request to server
        SendUserRegistration sendUserRegistrationTask = new SendUserRegistration(new URLEventListener() {
            @Override
            public void onSuccess() {

                progressDialog.dismiss();
                Context context = getApplicationContext();
                Toast.makeText(getApplicationContext(), "Welcome to TANIA!", Toast.LENGTH_LONG).show();

                // Change needsToRegister to false
                SharedPreferences prefs = context.getSharedPreferences("prefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putBoolean("needsToRegister", false);
                editor.apply();

                // Redirect to MainActivity
                Intent intent = new Intent(context, MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }

            @Override
            public void onFailure(Exception e) {
                progressDialog.dismiss();
                Toast.makeText(getApplicationContext(), "An error occurred while trying to register. Please start again.", Toast.LENGTH_LONG).show();
                Log.e(TAG, "An error occurred while trying to register user!");
                e.printStackTrace();
            }
        });

        // Start task
        sendUserRegistrationTask.execute(user);

    }

}
