package com.project.ilsaenterprise.monitoring;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
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.adapter.CommentAdapter;
import com.project.ilsaenterprise.models.Comment;
import com.project.ilsaenterprise.models.MonitoringListModel;
import com.project.ilsaenterprise.models.MonitoringModel;
import com.squareup.picasso.Picasso;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;

import de.hdodenhof.circleimageview.CircleImageView;

public class DisplayMonitoring 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, 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;
    DatabaseReference commentRef = 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 GoogleSignInAccount googleLogin;
    private FirebaseAuth mAuth;
    private FirebaseUser userFirebase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.Dark));
        setContentView(R.layout.activity_display_monitoring);
        if(getSupportActionBar() != null){
            getSupportActionBar().hide();
        }

        googleLogin = GoogleSignIn.getLastSignedInAccount(getApplicationContext());
        mAuth = FirebaseAuth.getInstance();

        idMonitoring = getIntent().getExtras().get("idMonitoring").toString();
        mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapViewMonitoring);
        imageSlider = (ImageSlider) findViewById(R.id.imageSlider);
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);

        bottomSheetDialog = new BottomSheetDialog(
                DisplayMonitoring.this, R.style.BottomSheetDialogTheme
        );

        final List<SlideModel> slideModelList = new ArrayList<>();
        imageRef = FirebaseDatabase.getInstance().getReference("users");
        InitializeFields();
        yearBottom = findViewById(R.id.yearBottom);
        yearBottom.setText(String.valueOf(year));
        countComment();

        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(DisplayMonitoring.this, ZoomMonitoring.class);
                                groupChatIntent.putExtra("urlZoom", urlZoom);
                                startActivity(groupChatIntent);
                            }
                        });
                    }

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

                    }
                });

        btnComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                comment();
            }
        });
    }

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

        userFirebase = mAuth.getCurrentUser();
        retrieveInfo();
    }

    private String getTimeAgo(long time) {
        if (time < 1000000000000L) {
            time *= 1000;
        }

//        String dateNow = getDateNow();
        long now = System.currentTimeMillis();
        if (time > now || time <= 0) {
            return null;
        }

        final long diff = now - time;
        if (diff < MINUTE_MILLIS) {
            return "Baru saja";
        } else if (diff < 2 * MINUTE_MILLIS) {
            return "semenit yang lalu";
        } else if (diff < 50 * MINUTE_MILLIS) {
            return diff / MINUTE_MILLIS + " menit yang lalu";
        } else if (diff < 90 * MINUTE_MILLIS) {
            return "sejam yang lalu";
        } else if (diff < 24 * HOUR_MILLIS) {
            int count = Integer.parseInt(getDateNow()) - Integer.parseInt(getDateTS(time));
            if(count == 0){
                Calendar cal = Calendar.getInstance(Locale.ENGLISH);
                cal.setTimeInMillis(time);
                String date = DateFormat.format("HH:mm", cal).toString();
                return "Hari ini, " + date;
            }
            else {
                Calendar cal = Calendar.getInstance(Locale.ENGLISH);
                cal.setTimeInMillis(time);
                String date = DateFormat.format("HH:mm", cal).toString();
                return "Kemarin, " + date;
            }
//            return diff / HOUR_MILLIS + " jam yang lalu";
        }
//        else if (diff < 48 * HOUR_MILLIS) {
//            Calendar cal = Calendar.getInstance(Locale.ENGLISH);
//            cal.setTimeInMillis(time);
//            String date = DateFormat.format("HH:mm", cal).toString();
//            return "Kemarin, " + date;
//                return "kemarin";
        else {
            return ((diff / DAY_MILLIS) + 1) + " hari yang lalu";
        }
    }

    private String getDateTS(long time){
        Calendar cal = Calendar.getInstance(Locale.ENGLISH);
        cal.setTimeInMillis(time);
        String date = DateFormat.format("dd", cal).toString();

        return date;
    }

    private String getDateNow(){
        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("dd", Locale.getDefault());
        String formattedDate = df.format(c);

        return formattedDate;
    }

    private void countComment(){
        TextView showCount = findViewById(R.id.countComment);

        commentRef.child(idMonitoring).child("komentar").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                showCount.setText(String.valueOf(dataSnapshot.getChildrenCount()));
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getBaseContext(), "" +databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void comment(){
        View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(
                R.layout.layout_comment_monitoring,
                (LinearLayout)findViewById(R.id.bottomSheetContainer)
        );

        CircleImageView imageProfile = bottomSheetView.findViewById(R.id.image_message_profile);
        ImageView closeView = bottomSheetView.findViewById(R.id.btnCloseView);
        TextView komenTv = bottomSheetView.findViewById(R.id.komenTxt);
        loadComment(bottomSheetView);

        imageRef.child(userFirebase.getUid()).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if(snapshot.hasChild("image")){
                    String retrieveImg = snapshot.child("image").getValue().toString();
                    Picasso.get().load(retrieveImg).placeholder(R.drawable.employee_img).into(imageProfile);
                }
                else
                    Picasso.get().load(userFirebase.getPhotoUrl()).placeholder(R.drawable.employee_img).into(imageProfile);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(getBaseContext(), error.toString(), Toast.LENGTH_SHORT).show();
            }
        });

        bottomSheetDialog.setCancelable(false);
//        bottomSheetDialog.setDismissWithAnimation(true);
        bottomSheetDialog.setContentView(bottomSheetView);
        bottomSheetDialog.show();

        komenTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.cancel();
                View keyView = LayoutInflater.from(getApplicationContext()).inflate(
                        R.layout.layout_open_keyboard,
                        (ConstraintLayout)findViewById(R.id.keySheetContainer)
                );
                String cUser = userFirebase.getUid();
                String timeStamp = String.valueOf(System.currentTimeMillis());
                EditText comment = keyView.findViewById(R.id.komentarTxt);
                ImageButton kirim = keyView.findViewById(R.id.kirimKomen);

                kirim.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        commentMap.put("timestamp", timeStamp);
                        commentMap.put("komentar", comment.getText().toString());
                        commentMap.put("user", cUser);
                        commentRef.child(idMonitoring).child("komentar").child(timeStamp).setValue(commentMap);

                        Toast.makeText(keyView.getContext(), "Komentar ditambahkan", Toast.LENGTH_SHORT).show();
                        bottomSheetDialog.cancel();
                    }
                });

                bottomSheetDialog.setCancelable(true);
                bottomSheetDialog.setContentView(keyView);
                bottomSheetDialog.show();
            }
        });

        closeView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetDialog.cancel();
            }
        });
    }

    private void loadComment(View view) {
        final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        progressBar.setVisibility(View.VISIBLE);
        ListView listView = view.findViewById(R.id.lvComment);
        List<Comment> commentList = new ArrayList<>();

        commentRef.child(idMonitoring).child("komentar").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                commentList.clear();
                for (DataSnapshot ds : dataSnapshot.getChildren()) {
                    Comment comment = ds.getValue(Comment.class);
                    comment.setTimestamp(getTimeAgo(Long.parseLong(comment.getTimestamp())));
                    commentList.add(comment);
                }
                Collections.reverse(commentList);
                CommentAdapter commentAdapter = new CommentAdapter(commentList, getBaseContext());
                listView.setAdapter(commentAdapter);
                progressBar.setVisibility(View.INVISIBLE);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(getBaseContext(), "Data Error" + databaseError.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    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())){
                    MonitoringModel monitoringModel = snapshot.getValue(MonitoringModel.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())));

                    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(DisplayMonitoring.this, LokasiMonitoring.class);
                            intent.putExtra("monitoringList", myList);
                            startActivity(intent);
                        }
                    });
                }
                else
                {
                    Toast.makeText(DisplayMonitoring.this, "Kesalahan Jaringan", Toast.LENGTH_LONG).show();
                }
            }

            @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 = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
        cal.setTimeInMillis(time);
        String clock = cal.getTime().getHours() + ":" + cal.getTime().getMinutes();
        String date = "";

        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH);
        int year = cal.get(Calendar.YEAR);

        if(month == 0)
            date += day + " Januari " + year;
        if(month == 1)
            date += day + " Februari " + year;
        if(month == 2)
            date += day + " Maret " + year;
        if(month == 3)
            date += day + " April " + year;
        if(month == 4)
            date += day + " Mei " + year;
        if(month == 5)
            date += day + " Juni " + year;
        if(month == 6)
            date += day + " Juli " + year;
        if(month == 7)
            date += day + " Agustus " + year;
        if(month == 8)
            date += day + " September " + year;
        if(month == 9)
            date += day + " Oktober " + year;
        if(month == 10)
            date += day + " November " + year;
        if(month == 11)
            date += day + " Desember " + year;

        return clock + " | " + 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);
        tipeLaporan = findViewById(R.id.tvReport);
        jenisLaporan = findViewById(R.id.tvSubReport);
        uploadDate = findViewById(R.id.dayMonitoring);
        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);
    }
}