package com.cpm.lorealbaautomation.leavemanagement;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;

import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;


import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;

import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.download.Downloader;
import com.cpm.lorealbaautomation.gsonGetterSetter.MasterLeaveType;
import com.cpm.lorealbaautomation.gsonGetterSetter.T_LeaveRequest;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Objects;

import static com.cpm.lorealbaautomation.dailyactivity.CounterProfileActivity.getDateDiff;


public class ApplyForLeaveActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemSelectedListener {
    String counterId, visit_date, username, dob_start_date = "", End_date_str = "", TransId = "", start_day_Of_Month = "", str_onedayLeave = "", leaveType = "", leaveTypeId = "0";
    ArrayList<MasterLeaveType> leaveTypeList = new ArrayList<>();
    ArrayList<T_LeaveRequest> leaveRequestList = new ArrayList<>();
    T_LeaveRequest object = new T_LeaveRequest();
    EditText apply_forleave_reason_edt;
    ImageView img_cal_end_date, img_cal_start_date;
    TextView txt_start_date, txt_end_date, tvHeader;
    RecyclerView recycl_leave_status;
    LinearLayout rl_leave_status, onedayRl;
    private RadioGroup radioSexGroup;
    private RadioButton radioSexButton;
    ArrayAdapter<CharSequence> leaveTypeAdapter;
    Spinner leaveTypeSpin;
    Button btn_save;
    CardView card_applyLeave;
    Lorealba_Database db;
    Context context;

    int mYear, mMonth, mDay;
    DatePickerDialog dpd;
    Calendar c;
    boolean clicked_flag = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_apply_for_leave);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }

        iduserinterface();
    }

    @SuppressLint({"RestrictedApi", "CommitPrefEdits"})
    private void iduserinterface() {
        ((ApplyForLeaveActivity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        SharedPreferences preferences = PrefHelper.getPrefs(context);
        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        apply_forleave_reason_edt = (EditText) findViewById(R.id.apply_forleave_reason_edt);
        img_cal_start_date = (ImageView) findViewById(R.id.img_cal_start_date);
        img_cal_end_date = (ImageView) findViewById(R.id.img_cal_end_date);
        txt_start_date = (TextView) findViewById(R.id.txt_start_date);
        txt_end_date = (TextView) findViewById(R.id.txt_end_date);
        btn_save = (Button) findViewById(R.id.btn_apply_leave);
        card_applyLeave = (CardView) findViewById(R.id.card_applyLeave);
        rl_leave_status = (LinearLayout) findViewById(R.id.rl_leave_status);
        onedayRl = (LinearLayout) findViewById(R.id.onedayRl);
        recycl_leave_status = (RecyclerView) findViewById(R.id.recycl_leave_status);
        tvHeader = (TextView) findViewById(R.id.tvHeader);
        radioSexGroup = (RadioGroup) findViewById(R.id.radioGrp_leave);
        leaveTypeSpin = (Spinner) findViewById(R.id.leaveTypeSpin);
        img_cal_start_date.setOnClickListener(this);
        img_cal_end_date.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        TransId = CommonFunctions.getUUID(context);
        setTitle("Apply For Leave -" + username);
        card_applyLeave.setVisibility(View.VISIBLE);
        leaveDetails();
        db.open();
        leaveTypeList = db.getmasterLeaveType(true);
        validate_spin(leaveTypeList);
    }

    private void validate_spin(ArrayList<MasterLeaveType> leaveTypeList) {
        leaveTypeAdapter = new ArrayAdapter<>(context, R.layout.spinner_custom_item);
        leaveTypeAdapter.add("- Select Leave Type -");
        for (int i = 0; i < leaveTypeList.size(); i++) {
            leaveTypeAdapter.add(leaveTypeList.get(i).getLeaveType());
        }
        leaveTypeSpin.setAdapter(leaveTypeAdapter);
        leaveTypeAdapter.setDropDownViewResource(R.layout.spinner_custom_item);
        leaveTypeSpin.setOnItemSelectedListener(this);
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.img_cal_start_date) {
            clicked_flag = true;
            c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            // Launch Date Picker Dialog
            dpd = new DatePickerDialog(context, (view1, year, monthOfYear, dayOfMonth) -> {
                String month_of_year = "";
                if ((monthOfYear + 1) < 10) {
                    month_of_year = "0" + (monthOfYear + 1);
                } else {
                    month_of_year = String.valueOf(monthOfYear + 1);
                }
                if ((dayOfMonth) < 10) {
                    start_day_Of_Month = "0" + dayOfMonth;
                } else {
                    start_day_Of_Month = String.valueOf(dayOfMonth);
                }
                dob_start_date = month_of_year + "/" + start_day_Of_Month + "/" + year;
                txt_start_date.setText(dob_start_date);
                txt_end_date.setText("");
            }, mYear, mMonth, mDay);

            Calendar calendar = Calendar.getInstance();
            ///disable current date
            // calendar.add(Calendar.DATE, +1);
            //Set yesterday time milliseconds as date pickers minimum date
            dpd.getDatePicker().setMinDate(calendar.getTimeInMillis());
            dpd.getDatePicker().setMaxDate(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 25));
            dpd.show();
        } else if (view.getId() == R.id.img_cal_end_date) {
            clicked_flag = true;
            c = Calendar.getInstance();
            mYear = c.get(Calendar.YEAR);
            mMonth = c.get(Calendar.MONTH);
            mDay = c.get(Calendar.DAY_OF_MONTH);
            // Launch Date Picker Dialog
            dpd = new DatePickerDialog(context, (view12, year, monthOfYear, dayOfMonth) -> {
                try {
                    String month_of_year = "", day_Of_Month = "";
                    if ((monthOfYear + 1) < 10) {
                        month_of_year = "0" + (monthOfYear + 1);
                    } else {
                        month_of_year = String.valueOf(monthOfYear + 1);
                    }

                    if ((dayOfMonth) < 10) {
                        day_Of_Month = "0" + dayOfMonth;
                    } else {
                        day_Of_Month = String.valueOf(dayOfMonth);
                    }

                    End_date_str = month_of_year + "/" + day_Of_Month + "/" + year;
                    @SuppressLint("SimpleDateFormat") int monthDiffence = (int) getDateDiff(new SimpleDateFormat("MM"), dob_start_date, End_date_str);
                    if (dob_start_date.equalsIgnoreCase(End_date_str)) {
                        if (dob_start_date.equalsIgnoreCase(visit_date) && End_date_str.equalsIgnoreCase(visit_date)) {
                            db.open();
                            leaveTypeList = db.getmasterLeaveType(false);
                            validate_spin(leaveTypeList);
                        }
                        txt_end_date.setText(End_date_str);
                        onedayRl.setVisibility(View.VISIBLE);
                        leaveTypeSpin.setVisibility(View.VISIBLE);
                    } else if (monthDiffence == 0) {
                        str_onedayLeave = "";
                        onedayRl.setVisibility(View.GONE);
                        leaveTypeSpin.setVisibility(View.VISIBLE);
                        int startdayofmonth = Integer.parseInt(start_day_Of_Month);
                        int enddayofmonth = Integer.parseInt(day_Of_Month);
                        if (startdayofmonth > enddayofmonth) {
                            txt_end_date.setText("");
                            AlertandMessages.showToastMsg(context, "End Date Should be greater than Start Date");
                        } else {
                            txt_end_date.setText(End_date_str);
                        }
                        db.open();
                        leaveTypeList = db.getmasterLeaveType(true);
                        validate_spin(leaveTypeList);
                    } else if (monthDiffence != 0) {
                        str_onedayLeave = "";
                        onedayRl.setVisibility(View.GONE);
                        txt_end_date.setText(End_date_str);
                        leaveTypeSpin.setVisibility(View.VISIBLE);
                        leaveTypeList = db.getmasterLeaveType(true);
                        validate_spin(leaveTypeList);
                    } else {
                        str_onedayLeave = "";
                        db.open();
                        leaveTypeList = db.getmasterLeaveType(true);
                        validate_spin(leaveTypeList);
                        onedayRl.setVisibility(View.GONE);
                        txt_end_date.setText(End_date_str);
                        leaveTypeSpin.setVisibility(View.VISIBLE);
                    }

                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            }, mYear, mMonth, mDay);
            // TODO Hide Future Date Here
            //  dpd.getDatePicker().setMaxDate(System.currentTimeMillis());
            // TODO Hide Past Date Here
            Calendar calendar = Calendar.getInstance();
            //calendar.add(Calendar.DATE);
            //Set yesterday time milliseconds as date pickers minimum date
            dpd.getDatePicker().setMinDate(calendar.getTimeInMillis());
            dpd.getDatePicker().setMaxDate(System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 25));
            dpd.show();
        } else if (view.getId() == R.id.btn_apply_leave) {
            if (txt_start_date.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select Start Date Of Leave ");
            } else if (txt_end_date.getText().toString().isEmpty()) {
                AlertandMessages.showToastMsg(context, "Please Select End Date Of Leave ");
            } else if (leaveTypeSpin.getSelectedItemId() == 0) {
                AlertandMessages.showToastMsg(context, "Please Select Leave Type");
            } else if (!checksameapplyeidDate()) {
                AlertandMessages.showToastMsg(context, "You have already applied for a leave on the specified date");
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(R.string.parinaam).setMessage(R.string.alertsaveData_approval);
                builder.setPositiveButton(android.R.string.yes, (dialogInterface, i) -> {
                    try {
                        object = new T_LeaveRequest();
                        // get selected radio button from radioGroup
                        int selectedId = radioSexGroup.getCheckedRadioButtonId();
                        // find the radiobutton by returned id
                        radioSexButton = (RadioButton) findViewById(selectedId);
                        object.setUserId(username);
                        object.setRequestDate(visit_date);
                        object.setFromDate(txt_start_date.getText().toString());
                        object.setUpload_start_date_str(dob_start_date);
                        object.setToDate(txt_end_date.getText().toString());
                        object.setUpload_end_date_str(End_date_str);
                        object.setLeave_reason(apply_forleave_reason_edt.getText().toString().trim().replaceAll("[(!@#$%^&*?)\"]", " "));
                        object.setLeaveStatus("Pending");
                        object.setTransId(TransId);
                        if (dob_start_date.equalsIgnoreCase(End_date_str)) {
                            str_onedayLeave = radioSexButton.getText().toString();
                        } else {
                            str_onedayLeave = "";
                        }
                        object.setStr_leaveType(leaveType);
                        object.setStr_leaveTypeId(leaveTypeId);
                        object.setOne_day_leave_str(str_onedayLeave);
                        object.setTransId(TransId);
                        db.open();
                        db.insert_leave_management_data(username, visit_date, counterId, object);
                        //download service
                        Intent intent = new Intent(context, Downloader.class);
                        intent.putExtra(CommonString.KEY_LEAVE_Mangemennt, object);
                        Downloader.enqueueWork(context, intent);
                        AlertandMessages.showToastMsg(context, "Data Saved Successfully");
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        apply_forleave_reason_edt.setText("");
                        apply_forleave_reason_edt.setHint("Please Fill Reason");
                        radioSexGroup.clearCheck();
                        ((RadioButton) findViewById(R.id.radioM)).setChecked(true);
                        leaveTypeSpin.setSelection(0);
                        txt_start_date.setText("");
                        txt_end_date.setText("");
                        clicked_flag = false;
                        leaveDetails();
                    } catch (Exception e) {
                        e.fillInStackTrace();
                    }
                });
                builder.setNegativeButton(android.R.string.cancel, (dialogInterface, i) -> dialogInterface.cancel());
                builder.show();
            }

        }
    }

    private boolean checksameapplyeidDate() {
        boolean result = true;
        if (!leaveRequestList.isEmpty()) {
            for (int k = 0; k < leaveRequestList.size(); k++) {
                if (leaveRequestList.get(k).getFromDate().equalsIgnoreCase(txt_start_date.getText().toString()) || leaveRequestList.get(k).getToDate().equalsIgnoreCase(txt_start_date.getText().toString())) {
                    result = false;
                    break;
                }
            }
        }

        return result;
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long l) {
        if (adapterView.getId() == R.id.leaveTypeSpin) {
            if (pos != 0) {
                leaveType = leaveTypeList.get(pos - 1).getLeaveType();
                leaveTypeId = leaveTypeList.get(pos - 1).getLeaveTypeId().toString();
            } else {
                leaveType = "";
                leaveTypeId = "0";
            }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home) {
            if (clicked_flag) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id1) -> {
                    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                    ApplyForLeaveActivity.this.finish();
                }).setNegativeButton("Cancel", (dialog, id12) -> dialog.cancel());
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ApplyForLeaveActivity.this.finish();
            }
        }


        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        if (clicked_flag) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context).setMessage(CommonString.ONBACK_ALERT_MESSAGE).setCancelable(false).setPositiveButton("Ok", (dialog, id) -> {
                overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
                ApplyForLeaveActivity.this.finish();
            }).setNegativeButton("Cancel", (dialog, id) -> dialog.cancel());
            AlertDialog alert = builder.create();
            alert.show();
        } else {
            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
            ApplyForLeaveActivity.this.finish();
        }
    }


    @SuppressLint("SetTextI18n")
    private void leaveDetails() {
        db.open();
        if (!db.getinserted_leave_requestList(counterId, username, visit_date, null).isEmpty()) {
            db.open();
            leaveRequestList = db.get_leave_List(username, visit_date, false);
        } else {
            db.open();
            leaveRequestList = db.get_leave_List(username, visit_date, true);
        }

        if (!leaveRequestList.isEmpty()) {
            //Collections.reverse(leaveRequestList);
            tvHeader.setVisibility(View.VISIBLE);
            recycl_leave_status.setVisibility(View.VISIBLE);
            recycl_leave_status.setAdapter(new ValueAdapter(context, leaveRequestList));
            recycl_leave_status.setLayoutManager(new LinearLayoutManager(context));
        } else {
            tvHeader.setVisibility(View.GONE);
            recycl_leave_status.setVisibility(View.GONE);
        }
    }

    private class ValueAdapter extends RecyclerView.Adapter<ValueAdapter.MyViewHolder> {
        LayoutInflater inflator;
        List<T_LeaveRequest> data;

        public ValueAdapter(Context context, List<T_LeaveRequest> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;
        }

        @NonNull
        @Override
        public ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.details_leave_mangement, parent, false);
            return new ValueAdapter.MyViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final ValueAdapter.MyViewHolder holder, final int position) {
            final T_LeaveRequest current = data.get(position);

            holder.txt_date_of_applied_leave.setText(current.getRequestDate());
            holder.txt_date_of_applied_leave.setId(position);

            holder.txt_from_date.setText(current.getFromDate());
            holder.txt_from_date.setId(position);

            holder.txt_to_date.setText(current.getToDate());
            holder.txt_to_date.setId(position);

            holder.txt_leavetype.setText(current.getStr_leaveType());
            holder.txt_leavetype.setId(position);

            if (current.getLeaveStatus().equalsIgnoreCase("Pending")) {
                holder.txt_leave_status.setText(" " + current.getLeaveStatus());
                holder.txt_leave_status.setTextColor(getResources().getColor(R.color.red));
                holder.txt_leave_status.setId(position);
            } else if (current.getLeaveStatus().equalsIgnoreCase("Accept")) {
                holder.txt_leave_status.setText(" " + current.getLeaveStatus());
                holder.txt_leave_status.setTextColor(getResources().getColor(R.color.green));
                holder.txt_leave_status.setId(position);
            } else if (current.getLeaveStatus().equalsIgnoreCase("Reject")) {
                holder.txt_leave_status.setText(" " + current.getLeaveStatus());
                holder.txt_leave_status.setTextColor(getResources().getColor(R.color.sticky));
                holder.txt_leave_status.setId(position);
            } else {
                holder.txt_leave_status.setText(" " + current.getLeaveStatus());
                holder.txt_leave_status.setId(position);
                holder.txt_leave_status.setTextColor(getResources().getColor(R.color.black));
            }
        }


        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView txt_date_of_applied_leave, txt_from_date, txt_to_date, txt_leave_status, txt_leavetype;

            public MyViewHolder(View itemView) {
                super(itemView);
                txt_date_of_applied_leave = (TextView) itemView.findViewById(R.id.txt_date_of_applied_leave);
                txt_from_date = (TextView) itemView.findViewById(R.id.txt_from_date);
                txt_to_date = (TextView) itemView.findViewById(R.id.txt_to_date);
                txt_leave_status = (TextView) itemView.findViewById(R.id.txt_leave_status);
                txt_leavetype = (TextView) itemView.findViewById(R.id.txt_leavetype);
            }
        }
    }


}

