package com.project.ilsaenterprise.monitoring;

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

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.airbnb.lottie.LottieAnimationView;
import com.denzcoskun.imageslider.ImageSlider;
import com.denzcoskun.imageslider.constants.ScaleTypes;
import com.denzcoskun.imageslider.interfaces.ItemClickListener;
import com.denzcoskun.imageslider.models.SlideModel;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
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.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.project.ilsaenterprise.R;
import com.project.ilsaenterprise.models.MonitoringListModel;
import com.project.ilsaenterprise.models.MonitoringModel;
import com.squareup.picasso.Picasso;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import de.hdodenhof.circleimageview.CircleImageView;

public class ShowSelfMonitoring extends AppCompatActivity {

    private String idMonitoring;
    private ImageSlider imageSlider;
    List<MonitoringModel> postList;
    ListView listView;
    private TextView afdeling, blok, deskripsi, distrik, farm, fullName, jabatan, jenisLaporan, tipeLaporan, uploadDate, uploadTime, jenisLap2, countComment, jabatan1, jabatan2, jabatan3, jabatanNew, yearBottom;
    private GoogleMap googleMap;
    private MapView mapView;
    private ImageView btnComment, ivProfile;
    SupportMapFragment mapFragment;
    private static final float DEFAULT_ZOOM = 20.5f;
    private static final int ERROR_DIALOG_REQUEST = 9001;
    ArrayList<Double> myList = new ArrayList<Double>();
    private BottomSheetDialog bottomSheetDialog;
    private String uid, displayName, displayImage;
    private String currentDate = new SimpleDateFormat("yyyy", Locale.getDefault()).format(new Date());
    private DatabaseReference imageRef;
    DatePicker datePicker;
    private CircleImageView imageComment;
    private RelativeLayout relComment, btnDelete;
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference("monitoring");
    private HashMap<Object, String> commentMap = new HashMap<>();
    private static final int SECOND_MILLIS = 1000;
    private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
    private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
    private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
    DatabaseReference refUser = FirebaseDatabase.getInstance().getReference("users");
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_self_monitoring);
        if(getSupportActionBar() != null){
            getSupportActionBar().hide();;
        }

        mAuth = FirebaseAuth.getInstance();

        idMonitoring = getIntent().getExtras().get("idMonitoring").toString();
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapViewMonitoring);
        imageSlider = (ImageSlider) findViewById(R.id.imageSlider);
        btnDelete = findViewById(R.id.btnDelete);
        LinearLayout btnBack = findViewById(R.id.btnBack);

        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ShowSelfMonitoring.this, HistoryMonitoring.class));
                finish();
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog = new BottomSheetDialog(
                        ShowSelfMonitoring.this, R.style.BottomSheetDialogTheme
                );
                bottomSheetDialog.setCancelable(false);
                View bottomSheetView = LayoutInflater.from(getApplicationContext())
                        .inflate(
                                R.layout.layout_popup_delete_data,
                                (LinearLayout)findViewById(R.id.deleteSuccessContainer)
                        );

                RelativeLayout btnCancel = bottomSheetView.findViewById(R.id.btnCancel);
                RelativeLayout btnDelete = bottomSheetView.findViewById(R.id.btnOk);
                bottomSheetDialog.setContentView(bottomSheetView);
                bottomSheetDialog.show();

                btnDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try{
                            ref.child(idMonitoring).removeValue();
                            Toast.makeText(getBaseContext(), "Laporan telah dihapus.", Toast.LENGTH_LONG).show();

                            bottomSheetDialog.cancel();
                            startActivity(new Intent(ShowSelfMonitoring.this, HistoryMonitoring.class));
                            finish();
                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                });

                btnCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomSheetDialog.dismiss();
                    }
                });

            }
        });

        final List<SlideModel> slideModelList = new ArrayList<>();
        InitializeFields();

        FirebaseDatabase.getInstance().getReference().child("monitoring").child(idMonitoring).child("media")
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapshot) {
                        for(DataSnapshot data:snapshot.getChildren()){
                            slideModelList.add(new SlideModel(data.child("link").getValue().toString(), ScaleTypes.CENTER_INSIDE));
                        }

                        imageSlider.setImageList(slideModelList, ScaleTypes.FIT);
                        imageSlider.setItemClickListener(new ItemClickListener() {
                            @Override
                            public void onItemSelected(int i) {
                                String urlZoom = slideModelList.get(i).getImageUrl().toString();
                                Intent groupChatIntent = new Intent(ShowSelfMonitoring.this, ZoomMonitoring.class);
                                groupChatIntent.putExtra("urlZoom", urlZoom);
                                startActivity(groupChatIntent);
                            }
                        });
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError error) {

                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
        userFirebase = mAuth.getCurrentUser();
        retrieveInfo();
    }

    private void retrieveInfo(){
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference("monitoring").child(idMonitoring);
        DatabaseReference userRef = FirebaseDatabase.getInstance().getReference("users");

        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if((snapshot.exists())){
                    MonitoringListModel monitoringModel = snapshot.getValue(MonitoringListModel.class);
                    uid = monitoringModel.getUid();

                    userRef.child(uid).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot snapshot) {
                            String username = snapshot.child("namaLengkap").getValue(String.class);
                            String getJabatan = snapshot.child("jabatan").getValue(String.class);
                            String role = snapshot.child("role").getValue(String.class);
                            String imgProfile = snapshot.child("image").getValue(String.class);
                            getRoleUser(role);
                            fullName.setText(username);
                            jabatan.setText(getJabatan);
                            if(imgProfile != null){
                                Picasso.get().load(imgProfile).placeholder(R.drawable.employee_img).into(ivProfile);
                            }
                            else
                                ivProfile.setImageResource(R.drawable.user_farmer);
                        }

                        @Override
                        public void onCancelled(@NonNull DatabaseError error) {

                        }
                    });


                    double lat = Double.parseDouble(monitoringModel.getLatitude());
                    double lon = Double.parseDouble(monitoringModel.getLongitude());
                    myList.add(lat);
                    myList.add(lon);

                    afdeling.setText(monitoringModel.getAfdeling());
                    blok.setText(monitoringModel.getBlok());
                    deskripsi.setText(monitoringModel.getDeskripsi());
                    farm.setText(monitoringModel.getFarm());
                    distrik.setText(monitoringModel.getDistrict());
                    jenisLaporan.setText(monitoringModel.getJenisLaporan());
                    tipeLaporan.setText(monitoringModel.getTipeLaporan());
                    uploadDate.setText(getDate(Long.parseLong(monitoringModel.getTimestamp())));
                    jenisLap2.append(monitoringModel.getJenisLaporan());

                    mapFragment.getMapAsync(new OnMapReadyCallback() {
                        @Override
                        public void onMapReady(GoogleMap mMap) {
                            googleMap = mMap;
                            googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                            LatLng lokasi = new LatLng(lat, lon);
                            googleMap.addMarker(new MarkerOptions().position(lokasi).title(monitoringModel.getDistrict()).snippet(monitoringModel.getFarm()));

                            CameraPosition cameraPosition = new CameraPosition.Builder().target(lokasi).zoom(16).build();
                            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                        }
                    });
                    ImageView imgFullscreen = findViewById(R.id.imgFullscreen);

                    imgFullscreen.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(ShowSelfMonitoring.this, LokasiMonitoring.class);
                            intent.putExtra("monitoringList", myList);
                            startActivity(intent);
                        }
                    });
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });

        userRef.child(userFirebase.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String imgProfile = snapshot.child("image").getValue(String.class);
                if(imgProfile == null){
                    Picasso.get().load(userFirebase.getPhotoUrl()).placeholder(R.drawable.employee_img).into(imageComment);
                }
                if(imgProfile != null){
                    Picasso.get().load(imgProfile).placeholder(R.drawable.employee_img).into(imageComment);
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }

    private String getDate(long time) {
        Calendar cal = Calendar.getInstance(Locale.ENGLISH);
        cal.setTimeInMillis(time);
        String date = DateFormat.format(" HH:mm  |  dd MMMM yyyy", cal).toString();
        return date;
    }

    private void getRoleUser(String role){
        if(role != null)
        {
            if(Objects.equals(role, "Level 1")){
                jabatan1.setText(Objects.requireNonNull(role));
                jabatan1.setVisibility(View.VISIBLE);
            }
            if(Objects.equals(role, "Level 2")){
                jabatan2.setText(Objects.requireNonNull(role));
                jabatan2.setVisibility(View.VISIBLE);
            }
            if(Objects.equals(role, "Level 3")){
                jabatan3.setText(Objects.requireNonNull(role));
                jabatan3.setVisibility(View.VISIBLE);
            }
        }
        else {
            jabatanNew.setVisibility(View.VISIBLE);
        }
    }

    private void InitializeFields() {
        afdeling = findViewById(R.id.afdelingMonitoring);
        blok = findViewById(R.id.blokMonitoring);
        deskripsi = findViewById(R.id.deskripsiMonitoring);
        distrik = findViewById(R.id.distrikMonitoring);
        farm = findViewById(R.id.kebunMonitoring);
        fullName = findViewById(R.id.uploaderMonitoring);
        jabatan = findViewById(R.id.tvJabatan);
        jenisLaporan = findViewById(R.id.jenisLaporMonitoring);
        tipeLaporan = findViewById(R.id.tipeLaporMonitoring);
        uploadDate = findViewById(R.id.dayMonitoring);
        jenisLap2 = findViewById(R.id.jenisLapor2Monitoring);
        countComment = findViewById(R.id.countComment);
        btnComment = findViewById(R.id.imageViewComment);
        jabatan1 = findViewById(R.id.jabatanLevel1);
        jabatan2 = findViewById(R.id.jabatanLevel2);
        jabatan3 = findViewById(R.id.jabatanLevel3);
        jabatanNew = findViewById(R.id.jabatanLevel4);
        ivProfile = findViewById(R.id.ivProfile);
        imageComment = findViewById(R.id.image_comment_profile);
    }
}