package com.utopiaindustries.qualitychecker.ui.fragments;

import static android.app.Activity.RESULT_OK;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
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.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.utopiaindustries.qualitychecker.R;
import com.utopiaindustries.qualitychecker.apiservice.ApiService;
import com.utopiaindustries.qualitychecker.apiservice.ApiServiceFactory;
import com.utopiaindustries.qualitychecker.db.ReportRepository;
import com.utopiaindustries.qualitychecker.models.InspectionItemCheckPoint;
import com.utopiaindustries.qualitychecker.models.InspectionItemDimension;
import com.utopiaindustries.qualitychecker.models.InspectionReport;
import com.utopiaindustries.qualitychecker.models.callback.SaveDraftReportCallback;
import com.utopiaindustries.qualitychecker.models.callback.SaveReportCallback;
import com.utopiaindustries.qualitychecker.models.VoiceOfCustomer;
import com.utopiaindustries.qualitychecker.notification.NotificationHelper;
import com.utopiaindustries.qualitychecker.service.InspectionReportService;
import com.utopiaindustries.qualitychecker.store.Store;
import com.utopiaindustries.qualitychecker.ui.adapter.DimensionAdapter;
import com.utopiaindustries.qualitychecker.ui.adapter.ImageAdapter;
import com.utopiaindustries.qualitychecker.ui.adapter.ItemDimensionAdapter;
import com.utopiaindustries.qualitychecker.ui.adapter.VocAdapter;
import com.utopiaindustries.qualitychecker.utils.FileUtils;
import com.utopiaindustries.qualitychecker.utils.ImageUriHolder;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

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

public class ThirdStepFragment extends Fragment implements View.OnClickListener {
    private NavController navController;
    private Button backBtn, nextBtn, openDimensionDialog, btnDraft, closeBtn;
    private ImageButton imagePicker, deleteImage;
    private TextView profileName;
    private ImageView profileImage;
    private InspectionReportService inspectionReportService;
    private RecyclerView vocRecyclerView, itemDimensionsRecyclerView;
    private Store store;
    private Spinner resultSpinner, sectionSpinner;
    private ApiService apiService;
    private EditText generalRemarks, etQualityAuditor, etProdRepresentative, etQcRepresentative, etFloor;
    private static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 100;
    private static final int MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE = 101;
    private static final int MY_PERMISSIONS_REQUEST_CAMERA = 102;

    private static final int CAMERA_REQUEST = 10111;
    private static final int GALLERY_REQUEST = 20111;

    private ImageAdapter imageAdapter;
    private RecyclerView imageRecyclerView;

    private TextView minorCountTv, majorCountTv, criticalCountTv, txtMajor, txtMinor;

    ArrayList<String> sectionArrayList = new ArrayList<>();

    private EditText etHandFeelNotOk, etHandFeelOk, etHandFeelPercent;
    private ImageView imgCalendar;
    private TextView txtDate;
    private int year, month, day;
    private Calendar calendar;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_third_step, container, false);

        inspectionReportService = InspectionReportService.getInstance();
        store = Store.getInstance();
        apiService = ApiServiceFactory.getApiService();

        setCurrentVersion();
        initializeViews(view);
        checkPermissions();
        populateViews();
        setOnClickListeners();
        updateProfileViews();
        vocRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        itemDimensionsRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        String asin = store.getReport().getItems().get(0).getAsin();
        apiService.fetchVocs(asin).enqueue(
                new Callback<List<VoiceOfCustomer>>() {
                    @Override
                    public void onResponse(Call<List<VoiceOfCustomer>> call,
                                           Response<List<VoiceOfCustomer>> response) {
                        if (response.isSuccessful() && response.body() != null) {
                            VocAdapter adapter = new VocAdapter(response.body(), getContext());
                            vocRecyclerView.setAdapter(adapter);
                        }
                    }

                    @Override
                    public void onFailure(Call<List<VoiceOfCustomer>> call, Throwable t) {
                        System.out.println(t.getMessage());
                    }
                }
        );

        Log.e("Dimensions: ",""+store.getReport().getItems().get(0).getDimensions());
        ItemDimensionAdapter adapter = new ItemDimensionAdapter(store.getReport().getItems().get(0).getDimensions());
        itemDimensionsRecyclerView.setAdapter(adapter);

        etQcRepresentative.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().setQcRepresentative(s.toString());
                } catch (Exception e) {
                    store.getReport().setQcRepresentative("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etFloor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().setFloor(s.toString());
                } catch (Exception e) {
                    store.getReport().setFloor("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etProdRepresentative.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().setProductionRepresentative(s.toString());
                } catch (Exception e) {
                    store.getReport().setProductionRepresentative("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etQualityAuditor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().setQualityAuditor(s.toString());
                } catch (Exception e) {
                    store.getReport().setQualityAuditor("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        generalRemarks.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                try {
                    store.getReport().setGeneralRemarks(s.toString());
                } catch (Exception e) {
                    store.getReport().setGeneralRemarks("");
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        imagePicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                builder.setTitle("Choose an Option");

                String[] options = {"Gallery", "Camera"};
                builder.setItems(options, (dialog, which) -> {
                    switch (which) {
                        case 0:
                            Log.e("Gallery", "**********");
                            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                            intent.addCategory(Intent.CATEGORY_OPENABLE);
                            intent.setType("image/*");
                            //startActivityForResult( intent,  GALLERY_REQUEST );
                            ((Activity) getContext()).startActivityForResult(intent, GALLERY_REQUEST);
                            break;
                        case 1:
                            Log.e("Camera: ", "***********");
                            Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            File imageFile = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES), "captured_image.jpg");
                            Uri imageUri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", imageFile);
                            //Log.e("imageUri: ",""+imageUri);
                            ImageUriHolder.getInstance().setImageUri(imageUri);
                            camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                            //startActivityForResult(camera_intent, CAMERA_REQUEST);
                            ((Activity) getContext()).startActivityForResult(camera_intent, CAMERA_REQUEST);
                            break;
                    }
                });

                builder.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());

                AlertDialog dialog = builder.create();
                dialog.show();

            }
        });

        deleteImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!store.getReport().getItems().get(0).getDimensionImages().isEmpty()) {
                    store.getReport().getItems().get(0).getDimensionImages().remove(store.getReport().getItems().get(0).getDimensionImages().size() - 1);
                    updateImageAdapter(store.getReport().getItems().get(0).getDimensionImages());
                } else {
                    System.out.println("The list is empty");
                }
            }
        });

        imgCalendar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDatePickerDialog(getActivity());
            }
        });

        return view;
    }

    private void showDatePickerDialog(Context context) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(
                context,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        // Month is 0-indexed, so we add 1
                        Calendar selectedCalendar = Calendar.getInstance();
                        selectedCalendar.set(year, monthOfYear, dayOfMonth);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                        String selectedDate = dateFormat.format(selectedCalendar.getTime());
                        txtDate.setText(selectedDate);
                        store.getReport().setAuditDate(selectedDate);
                    }
                },
                year, month, day
        );
        datePickerDialog.show();
    }

    public void onImagePickerResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST) {
            Uri selectedImageUri = ImageUriHolder.getInstance().getImageUri();
            saveImage(selectedImageUri);
        } else if (requestCode == GALLERY_REQUEST) {
            Uri selectedImageUri = data.getData();
            assert selectedImageUri != null;
            saveImage(selectedImageUri);
        }
    }

    private void saveImage(Uri imageUri) {
        FileUtils.convertUriToByteArrayAsync(
                getContext(),
                imageUri,
                100,  // Target size in KB
                compressedImage -> {
                    // Handle the compressed image here, e.g., display it
                    requireActivity().runOnUiThread(() -> {
                        store.getReport().getItems().get(0).addDimensionImageList(compressedImage);
                        updateImageAdapter(store.getReport().getItems().get(0).getDimensionImages());
                        //adapter.notifyItemChanged(requestCode);
                    });
                },
                error -> {
                    // Handle any errors
                    requireActivity().runOnUiThread(() -> {
                        Toast.makeText(getContext(), "Error compressing image: " + error.getMessage(), Toast.LENGTH_SHORT).show();
                    });
                }
        );


    }

    private void updateImageAdapter(List<byte[]> imgFiles) {
        imageRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        imageAdapter = new ImageAdapter(imgFiles, getContext());
        imageRecyclerView.setAdapter(imageAdapter);

        int position = imgFiles.size();
        imageAdapter.notifyItemInserted(position);

    }

    @Override
    public void onClick(View v) {
        navController = Navigation.findNavController(requireView());
        if (v.getId() == R.id.button_left_frag_3) {
            navController.navigate(R.id.action_thirdStepFragment_to_secondStepFragment);
        }
        if (v.getId() == R.id.button_draft_third) {
            //--
            if (store.getReport() != null) {
                inspectionReportService.saveDraftInLocalDb(getContext(), store.getReport(), new SaveDraftReportCallback() {
                    @Override
                    public void onSuccess() {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(() -> {
                            SharedPreferences sharedPreferences = getContext().getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();

                            editor.putString("draftReportId", "0");
                            editor.apply();
                            // progressBar.setVisibility(View.INVISIBLE);
                            //Objects.requireNonNull(getActivity()).finish();
                            NotificationHelper.showNotification(Objects.requireNonNull(getContext()),
                                    "Utopia QA App",
                                    "Report is successfully drafted");

                            Toast.makeText(getContext(), "Report saved as Draft", Toast.LENGTH_SHORT).show();
                        });
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        Handler handler = new Handler(Looper.getMainLooper());
                        handler.post(() -> {
                            Toast.makeText(getContext(), throwable.getMessage(), Toast.LENGTH_LONG).show();
                            //progressBar.setVisibility(View.INVISIBLE);
                            NotificationHelper.showNotification(Objects.requireNonNull(getContext()),
                                    "Utopia QA App",
                                    "Error in saving report");
                        });
                    }
                });
            }

            //---
        }
        if (v.getId() == R.id.button_right_frag_3) {
            saveReportDialog();
        }
        if (v.getId() == R.id.button_open_dimension) {
            openDimensionDialog();
        }

        if (v.getId() == R.id.button_close) {
            if (getActivity() != null) {
                getActivity().finish();
            }
        }
    }

    /*private void saveReportDirectlyToServer(Store store) {
        apiService.saveInspectionReport(store.getReport()).enqueue(new Callback<Map<String, String>>() {
                    @Override
                    public void onResponse(Call<Map<String, String>> call, Response<Map<String, String>> response) {
                        progressBar.setVisibility(View.GONE);
                        if (response.isSuccessful()) {
                            System.out.println(response.body());
                            Log.e("Response-Successful: ",""+response.body());
                            if (response.body().get("result").equalsIgnoreCase("success")) {
                                Toast.makeText(getContext(), "Report saved successfully", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(getContext(), "Error in saving report", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getContext(), "Error in saving report", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Map<String, String>> call, Throwable t) {
                        progressBar.setVisibility(View.GONE);
                        Log.e("onFailure-message",""+t.getMessage());
                    }
                }
        );
    }*/

    private void saveReportDialog() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View dialogView = inflater.inflate(R.layout.save_report_dialog, null);
        // progress bar
        ProgressBar progressBar = dialogView.findViewById(R.id.save_report_progress);

        AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getContext()));
        builder.setView(dialogView)
                .setTitle("So you want to save report?")
                .setPositiveButton("Save", (dialog, which) -> {
                    progressBar.setVisibility(View.VISIBLE);
                    NotificationHelper.showNotification(Objects.requireNonNull(getContext()),
                            "Utopia QA App",
                            "Report is saving keep patience...");
                    inspectionReportService.saveInLocalDb(getContext(), store.getReport(), new SaveReportCallback() {
                        @Override
                        public void onSuccess() {
                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(() -> {

                                calculateDimensions();
                                //Log.e("Report-ToString: ", "" + store.getReport().toString());
                                SharedPreferences sharedPreferences = getContext().getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
                                long draftReportId = Long.parseLong(sharedPreferences.getString("draftReportId", null));

                                new ReportRepository(getContext()).deleteDraftRecordById(draftReportId);
                                Toast.makeText(getContext(), "Report saved Successfully", Toast.LENGTH_LONG).show();
                                progressBar.setVisibility(View.INVISIBLE);
                                Objects.requireNonNull(getActivity()).finish();
                                NotificationHelper.showNotification(Objects.requireNonNull(getContext()),
                                        "Utopia QA App",
                                        "Report is successfully saved");
                            });
                        }

                        @Override
                        public void onFailure(Throwable throwable) {
                            Handler handler = new Handler(Looper.getMainLooper());
                            handler.post(() -> {
                                Toast.makeText(getContext(), throwable.getMessage(), Toast.LENGTH_LONG).show();
                                progressBar.setVisibility(View.INVISIBLE);
                                NotificationHelper.showNotification(Objects.requireNonNull(getContext()),
                                        "Utopia QA App",
                                        "Error in saving report");
                            });
                        }
                    });
                })
                .setNegativeButton("Cancel", (dialog, which) -> {
                    // Handle Cancel button click
                    dialog.dismiss();
                });
        // Show the dialog
        AlertDialog dialog = builder.create();
        progressBar.setVisibility(View.GONE);
        dialog.show();

    }

    private void openDimensionDialog() {
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View dialogView = inflater.inflate(R.layout.dimension_dialog, null);
        // recycler view
        RecyclerView dimensionRecyclerView = dialogView.findViewById(R.id.dimension_recycler_view);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        dimensionRecyclerView.setLayoutManager(layoutManager);
        // set adapter
        DimensionAdapter dimensionAdapter = new DimensionAdapter(store.getDimensions(),
                store.getDimensionList(),
                store.getItemUnits());
        dimensionRecyclerView.setAdapter(dimensionAdapter);
        AlertDialog.Builder builder = new AlertDialog.Builder(Objects.requireNonNull(getContext()));
        builder.setView(dialogView)
                .setTitle("Select Dimensions")
                .setPositiveButton("Save", (dialog, which) -> {
                    calculateDimensions();
                    dialog.dismiss();
                })
                .setNegativeButton("Cancel", (dialog, which) -> {
                    // Handle Cancel button click
                    dialog.dismiss();
                });

        Button addItemBtn = dialogView.findViewById(R.id.add_dimension_item);
        addItemBtn.setOnClickListener(v -> {
            int position = store.getDimensions().size();
            store.getDimensions().add(new InspectionItemDimension());
            dimensionAdapter.notifyItemInserted(position);
            dimensionRecyclerView.smoothScrollToPosition(position);

        });

        // Show the dialog
        AlertDialog dialog = builder.create();

        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setAttributes(layoutParams);

        dialog.show();
        // After show, clear the flags and set the soft input mode
        Objects.requireNonNull(dialog.getWindow()).clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

    }

    @SuppressLint("DefaultLocale")
    private void populateViews() {
        generalRemarks.setText(store.getReport().getGeneralRemarks());
        etQualityAuditor.setText(store.getReport().getQualityAuditor());
        etProdRepresentative.setText(store.getReport().getProductionRepresentative());
        etQcRepresentative.setText(store.getReport().getQcRepresentative());
        etFloor.setText(store.getReport().getFloor());
        txtDate.setText(store.getReport().getAuditDate());
        etHandFeelNotOk.setText(String.valueOf(store.getReport().getItems().get(0).getHandFeelNotOkay()));

        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_spinner_item,
                inspectionReportService.getReportResult());
        resultSpinner.setAdapter(adapter);

        resultSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = parent.getItemAtPosition(position).toString();
                store.getReport().setReportResult(result);
            }

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

            }
        });

        ArrayAdapter<String> adapter2 = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_spinner_item,
                sectionArrayList);
        sectionSpinner.setAdapter(adapter2);

        sectionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String result = parent.getItemAtPosition(position).toString().trim().replace(" ", "");
                store.getReport().getItems().get(0).setSection(result.trim());
                store.getReport().getItems().get(0).setSectionForDraft(parent.getItemAtPosition(position).toString());
                Log.e("Section: ", "" + result);
            }

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

            }
        });

        minorCountTv.setText(String.valueOf(0));
        majorCountTv.setText(String.valueOf(0));
        criticalCountTv.setText(String.valueOf(0));

        InspectionReport inspectionReport = store.getReport();
        if (Objects.nonNull(inspectionReport) && inspectionReport.getItems() != null &&
                !inspectionReport.getItems().isEmpty() &&
                !inspectionReport.getItems().get(0).getCheckPoints().isEmpty()) {
            int minor = 0;
            int major = 0;
            int crirical = 0;
            for (InspectionItemCheckPoint itemCp : inspectionReport.getItems().get(0).getCheckPoints()) {
                for (int i = 0; i < itemCp.getDefectSeverites().size(); i++) {
                    String status = itemCp.getDefectSeverites().get(i);
                    System.out.println(status);
                    float quantity = itemCp.getQuantities().get(i);
                    if (status.equalsIgnoreCase("minor")) {
                        minor += (int) quantity;
                    }
                    ;
                    if (status.equalsIgnoreCase("major")) {
                        major += (int) quantity;
                    }
                    if (status.equalsIgnoreCase("critical")) {
                        crirical += (int) quantity;
                    }
                }
            }

            minorCountTv.setText(String.format("Minor : %d", minor));
            majorCountTv.setText(String.format("Major : %d", major));
            criticalCountTv.setText(String.format("Critical : %d", crirical));

            double majorInspection = store.getReport().getItems().get(0).getLevelMajorDefects();
            Log.e("majorInspection: ",""+majorInspection);
            double minorInspection = store.getReport().getItems().get(0).getLevelMinorDefects();
            Log.e("minorInspection: ",""+minorInspection);

            if ((double) minor <= minorInspection
                    && (double) major <= majorInspection
                    && (double) crirical == 0) {
                //resultStatus.setText("PASSED");
                String defaultSelection = "PASSED";
                int defaultIndexResultIndex = inspectionReportService.getReportResult().indexOf(defaultSelection);
                resultSpinner.setSelection(defaultIndexResultIndex);
                store.getReport().setReportResult("PASSED");
                //resultStatus.setTextColor(ContextCompat.getColor(requireContext(),R.color.success));
                //resultStatus.setBackgroundResource( R.drawable.passed_bg );
            } else {
                //resultStatus.setText("FAILED");
                //resultStatus.setTextColor(ContextCompat.getColor(requireContext(),R.color.red));
                String defaultSelection = "FAILED";
                int defaultIndexResultIndex = inspectionReportService.getReportResult().indexOf(defaultSelection);
                resultSpinner.setSelection(defaultIndexResultIndex);
                store.getReport().setReportResult("FAILED");
                //resultStatus.setBackgroundResource( R.drawable.failed_bg );
            }

            //Log.e("majorCount: ",""+majorInspection);
            //Log.e("minorCount: ",""+minorInspection);
            txtMajor.setText(String.format("Major : %s/%d", (int) majorInspection, (int) (majorInspection + 1)));
            txtMinor.setText(String.format("Minor : %s/%d", (int) minorInspection, (int) (minorInspection + 1)));
        }

        if (!store.getReport().getItems().get(0).getDimensionImages().isEmpty()) {
            updateImageAdapter(store.getReport().getItems().get(0).getDimensionImages());
        }

        SharedPreferences sharedPreferences = getContext().getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        long draftReportId = Long.parseLong(sharedPreferences.getString("draftReportId", null));

        if (draftReportId > 0) {
            Log.e("draft-Report-ID: ",""+draftReportId);
            String selectedString = store.getReport().getItems().get(0).getSectionForDraft();
            Log.e("draft-Report-selected: ",""+selectedString);
            int index = sectionArrayList.indexOf(selectedString);
            Log.e("draft-index: ",""+index);
            sectionSpinner.setSelection(index);

            etHandFeelNotOk.setText(String.valueOf(store.getReport().getItems().get(0).getHandFeelNotOkay()));
            txtDate.setText(store.getReport().getAuditDate());
        }
        else {
            String currentDate = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
            txtDate.setText(currentDate);
            store.getReport().setAuditDate(currentDate);
        }
    }

    private void setCurrentVersion() {
        PackageManager packageManager = getContext().getPackageManager();
        try {
            PackageInfo info = packageManager.getPackageInfo( getContext().getPackageName(), 0 );
            //Log.e("VersionName: ",""+info.versionName);
            //Log.e("VersionCode: ",""+info.versionCode);
            String currentVersion = String.format("v-%s", String.valueOf(info.versionName));
            store.getReport().setAppVersion(currentVersion);
        } catch ( Exception e ) {
            e.printStackTrace();
        }
    }

    private void calculateDimensions() {
        List<InspectionItemDimension> dimensions = store.getDimensions();
        System.out.println(dimensions);
        //    List<InspectionItemDimension> newDimensions = new ArrayList<>();
        try {
//            if(! dimensions.isEmpty() ){
            // calculations for averaging
//                Map<String,List<InspectionItemDimension>> typeToDimensionsMap =
//                        dimensions.stream().collect(Collectors.groupingBy( InspectionItemDimension::getType) );

//                for( Map.Entry<String,List<InspectionItemDimension>> entry : typeToDimensionsMap.entrySet() ){
//                    InspectionItemDimension newDimen = getInspectionItemDimension( entry );
//                    newDimensions.add( newDimen );
//                }
            store.getReport().getItems().get(0).setDimensions(dimensions);
            ItemDimensionAdapter adapter = new ItemDimensionAdapter(dimensions);
            itemDimensionsRecyclerView.setAdapter(adapter);
        } catch (NullPointerException ex) {
            Toast.makeText(getContext(), "Please fill the required Fields", Toast.LENGTH_LONG).show();
        }
    }

    @NonNull
    private static InspectionItemDimension getInspectionItemDimension(Map.Entry<String, List<InspectionItemDimension>> entry) {
        float required = 0f;
        float actual = 0f;
        float difference = 0f;
        String unit = null;
        float size = entry.getValue().size();

        for (InspectionItemDimension dimen : entry.getValue()) {
            required += dimen.getRequired();
            actual += dimen.getActual();
            difference += dimen.getDifference();
            if (unit == null) {
                unit = dimen.getUnit();
            }
        }
        // average
        required /= size;
        actual /= size;
        difference /= size;

        return new InspectionItemDimension(
                entry.getKey(),
                actual,
                required,
                difference,
                unit
        );
    }

    private void initializeViews(View view) {
        backBtn = view.findViewById(R.id.button_left_frag_3);
        nextBtn = view.findViewById(R.id.button_right_frag_3);
        btnDraft = view.findViewById(R.id.button_draft_third);
        closeBtn = view.findViewById(R.id.button_close);
        imagePicker = view.findViewById(R.id.image_picker);
        deleteImage = view.findViewById(R.id.delete_image);
        imageRecyclerView = view.findViewById(R.id.imageRecyclerView);
        openDimensionDialog = view.findViewById(R.id.button_open_dimension);
        profileImage = view.findViewById(R.id.third_step_profile_image);
        profileName = view.findViewById(R.id.third_profile_name);
        vocRecyclerView = view.findViewById(R.id.voc_recyclerview);
        resultSpinner = view.findViewById(R.id.result_spinner);
        sectionSpinner = view.findViewById(R.id.section_spinner);
        //resultStatus = view.findViewById( R.id.result_status);
        generalRemarks = view.findViewById(R.id.general_remarks);
        itemDimensionsRecyclerView = view.findViewById(R.id.item_dimensions_recyclerview);
        minorCountTv = view.findViewById(R.id.minor_count);
        majorCountTv = view.findViewById(R.id.major_count);
        criticalCountTv = view.findViewById(R.id.critical_count);
        etQualityAuditor = view.findViewById(R.id.et_quality_auditor);
        etProdRepresentative = view.findViewById(R.id.et_prod_represent);
        etQcRepresentative = view.findViewById(R.id.et_qc_represent);
        txtMajor = view.findViewById(R.id.txt_major);
        txtMinor = view.findViewById(R.id.txt_minor);
        etFloor = view.findViewById(R.id.et_floor);

        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        month = calendar.get(Calendar.MONTH);
        day = calendar.get(Calendar.DAY_OF_MONTH);

        imgCalendar = view.findViewById(R.id.img_calendar);
        txtDate = view.findViewById(R.id.txt_date);

        etHandFeelNotOk = view.findViewById(R.id.et_hand_feel_not_ok);
        etHandFeelOk = view.findViewById(R.id.et_hand_feel_ok);
        etHandFeelPercent = view.findViewById(R.id.et_not_ok_percent);

        sectionArrayList.add("Comforter & Mattress Pad");
        sectionArrayList.add("Bedding");
        sectionArrayList.add("Blanket & Table Linen");
        sectionArrayList.add("Pillow");
        sectionArrayList.add("Terry Towel");
        sectionArrayList.add("Garments");
        sectionArrayList.add("Mattress Protector");

        etHandFeelNotOk.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.e("onTextChanged: ","****");
                try {
                    int sampleSize = 0;
                    if (store.getReport().getItems().get(0).getSampleSize() != 0) {
                        sampleSize = Integer.parseInt(String.valueOf(store.getReport().getItems().get(0).getSampleSize()));;

                        int handFeelNotOk = Integer.parseInt(s.toString());
                        int handFeelOk = sampleSize - handFeelNotOk;
                        etHandFeelOk.setText(String.valueOf(handFeelOk));
                        double percent = (double) handFeelNotOk / sampleSize * 100;
                        etHandFeelPercent.setText(String.format("%s%%", percent));
                        store.getReport().getItems().get(0).setHandFeelNotOkay(Long.parseLong(s.toString()));
                    }

                } catch (Exception e) {
                    store.getReport().getItems().get(0).setHandFeelNotOkay(0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    private void setOnClickListeners() {
        nextBtn.setOnClickListener(this);
        backBtn.setOnClickListener(this);
        btnDraft.setOnClickListener(this);
        closeBtn.setOnClickListener(this);
        openDimensionDialog.setOnClickListener(this);
    }

    private void updateProfileViews() throws NullPointerException {
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("login_prefs", Context.MODE_PRIVATE);
        profileName.setText(sharedPreferences.getString("name", null));
        Glide.with(getContext())
                .load(store.getProfileImage())
                .into(profileImage);
    }

    // PERMISSIONS
    private void checkPermissions() {
        // Check if permission is not granted
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // Permission is not granted, request it
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
        }

        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CAMERA);
        }
    }

}
